From 41042a1b7ce3d0e55c6d11af485d3bc321cb1ac9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:50:54 -0800 Subject: [PATCH 01/11] chore(quest): claim quest/m1/ffi-refusals/moq-excluded.md Quest-Claim: 7b3950be29ba62a2 From a71bf246f789e60669eaa14d157d6763fc1e2261 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:14:59 -0800 Subject: [PATCH 02/11] wip(ffi): export what moq's excludes hide at main --- ffi/fixtures/api/examples/transcript.rs | 25 ++ ffi/fixtures/api/src/lib.rs | 102 ++++++- ffi/fixtures/tls/src/lib.rs | 40 +++ ffi/runtime/rt.rs | 24 +- ffi/src/collect.rs | 353 ++++++++++++++++++++---- ffi/src/dart.rs | 6 +- ffi/src/glue.rs | 28 +- ffi/src/ir.rs | 24 +- ffi/tests/api.c | 52 ++++ ffi/tests/api.cpp | 38 +++ ffi/tests/api.dart | 28 ++ ffi/tests/api.go | 28 ++ ffi/tests/api.kt | 25 ++ ffi/tests/api.py | 24 ++ ffi/tests/api.swift | 33 +++ 15 files changed, 758 insertions(+), 72 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 34183ea08..53a9d7358 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -611,6 +611,25 @@ fn main() { String::from_utf8_lossy(&api::cert_der(cert)), api::chain_len(chain) ); + // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. + let resolver = api::resolver("r1"); + println!("resolver {}", api::resolved(resolver)); + let mut codecs = api::Codecs::new(); + println!("codecs {}", codecs.ids()); + let mut list = codecs.list.clone(); + list.reverse(); + codecs.list = list; + println!("codecs reversed {}", codecs.ids()); + // A standard library value no type maps, in a handle. + let failure = api::failure("boom"); + println!("failure {} {}", api::failure_message(&failure), api::failure_kind(failure)); + // Iterators, passed as the arrays of their items. + println!("sum_all {}", api::sum_all(vec![1u32, 2, 3].into_iter())); + println!("offered_len {}", api::offered_len([&b"h3"[..], b"moq-00"].into_iter())); + println!("join_words {}", api::join_words(["a", "b", "c"])); + // Bytes that must be `'static`, interned. + println!("der {}", String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes())); + println!("der again {}", String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes())); let session = api::resume("h3", 60).unwrap(); println!("resume {} {}", session.alpn(), session.lifetime().seconds); println!("resume err {}", api::resume("", 60).err().unwrap()); @@ -622,6 +641,11 @@ fn main() { println!("cleared {}", meters.first().count()); meters.last.add(4); println!("field lent {}", meters.last.add(1)); + // An optional field that is not Clone, lent as `Some` of a handle. + println!("spare {}", meters.spare.is_some()); + meters.spare = Some(api::Meter::default()); + meters.spare.as_ref().unwrap().add(5); + println!("spare lent {}", meters.spare.as_ref().unwrap().add(1)); let tallies = api::Tallies::new(); tallies.first().bump(); println!("tallied {}", tallies.first().bump()); @@ -732,6 +756,7 @@ fn main() { // Slices, passed in and returned as clones, and the socket address of each family. println!("shapes {:?} greetings {:?}", api::Shape::ALL, api::GREETINGS); + println!("both {:?} primes {:?}", api::Shape::BOTH, api::PRIMES); let trail = api::Trail::new( &[api::Point { x: 1, y: 2 }, api::Point { x: 3, y: 4 }], &["a".to_string(), "b".to_string()], diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index f5315426e..10e3170d6 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -458,11 +458,13 @@ impl Meter { } } -/// Owns a meter it lends, and one in a field, lent as the method's is. +/// Owns a meter it lends, and one in a field, lent as the method's is, and an optional one, +/// lent as `Some` of it. #[derive(Default)] pub struct Meters { first: Meter, pub last: Meter, + pub spare: Option, } impl Meters { @@ -2359,6 +2361,98 @@ pub fn blame(err: tls::held::Invalid) -> String { /// A session of `alpn` lasting `seconds`, from a crate the facade re-exports nothing from: /// its type exports by its path there, and its error crosses as its message. +/// Another crate's trait object behind an `Arc`: an opaque handle, taken back as the `Arc`. +pub fn resolver(name: &str) -> Arc { + Arc::new(tls::held::Named(name.to_string())) +} + +/// The name a resolver resolves, from its handle. +pub fn resolved(resolver: Arc) -> String { + resolver.name() +} + +/// Codecs, each another crate's `&'static dyn Codec`, held by value in an opaque handle. +pub struct Codecs { + pub list: Vec<&'static dyn tls::held::Codec>, + seen: u8, +} + +impl Codecs { + pub fn new() -> Self { + Self { + list: vec![&tls::held::ZLIB, &tls::held::BROTLI], + seen: 0, + } + } + + /// The ids of the listed codecs, in order, as one number of a digit each. + pub fn ids(&mut self) -> u32 { + self.seen += 1; + self.list.iter().fold(0, |n, codec| n * 10 + u32::from(codec.id())) + } +} + +impl Default for Codecs { + fn default() -> Self { + Self::new() + } +} + +/// A standard library value no exported type maps: an opaque handle held by value. +pub fn failure(message: &str) -> std::io::Error { + std::io::Error::other(message.to_string()) +} + +/// The failure's message, borrowed from its handle. +pub fn failure_message(error: &std::io::Error) -> String { + error.to_string() +} + +/// The failure's kind, taken back by value. +pub fn failure_kind(error: std::io::Error) -> String { + format!("{:?}", error.kind()) +} + +/// The sum of what an iterator yields, which C passes as the array of its items. +pub fn sum_all(items: impl Iterator) -> u32 { + items.sum() +} + +/// The total length of borrowed byte strings, as moq-tokio's TLS acceptor reads offered ALPNs. +pub fn offered_len<'a>(alpns: impl Iterator) -> usize { + alpns.map(<[u8]>::len).sum() +} + +/// Words joined with spaces: an `IntoIterator` of what converts to `&str`, as moq-tokio's +/// WebSocket listener takes its protocols. +pub fn join_words(words: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + let words: Vec = words.into_iter().map(|w| w.as_ref().to_string()).collect(); + words.join(" ") +} + +/// Bytes that must outlive every handle, as rustls's `CertificateDer::from_slice` borrows +/// its DER: the glue interns them. +pub struct Der<'a>(&'a [u8]); + +impl<'a> Der<'a> { + pub fn from_slice(bytes: &'a [u8]) -> Self { + Self(bytes) + } + + pub fn bytes(&self) -> Vec { + self.0.to_vec() + } +} + +/// Reads a stream no type C holds implements: left out, as C never holds one. +pub fn pump(mut stream: T) -> u8 { + stream.read() +} + pub fn resume(alpn: &str, seconds: u32) -> Result { tls::resume(alpn, seconds) } @@ -2711,11 +2805,17 @@ impl Site { impl Shape { /// Every shape, as a constant slice. pub const ALL: &'static [Shape] = &[Shape::Circle, Shape::Square]; + + /// Every shape, as a constant array, returned as the array of its elements. + pub const BOTH: [Shape; 2] = [Shape::Circle, Shape::Square]; } /// Greetings, as a constant slice of references, each returned as a clone. pub const GREETINGS: &[&str] = &["hi", "hello"]; +/// Primes, as a constant array of a block's element. +pub const PRIMES: [u32; 3] = [2, 3, 5]; + /// A trail through points, each labeled: slices passed in and lent back out. pub struct Trail { points: Vec, diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index 5bbd68985..3ca094c47 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -193,4 +193,44 @@ pub mod held { /// A `Copy` token, which an opaque handle holds by value. #[derive(Clone, Copy, Debug)] pub struct Token(pub u32); + + /// A trait C never implements, whose `Arc` an opaque handle holds, as + /// moq-tokio's TLS server takes rustls's certificate resolver. + pub trait Resolver: Send + Sync { + fn name(&self) -> String; + } + + /// A resolver of a fixed name. + pub struct Named(pub String); + + impl Resolver for Named { + fn name(&self) -> String { + self.0.clone() + } + } + + /// A trait whose `&'static dyn Codec` an opaque handle holds by value, as rustls's + /// client config lists its certificate compressors. + pub trait Codec: Send + Sync { + fn id(&self) -> u8; + } + + /// A codec of a fixed id. + pub struct Fixed(pub u8); + + impl Codec for Fixed { + fn id(&self) -> u8 { + self.0 + } + } + + /// The codecs there are, each `'static`. + pub static ZLIB: Fixed = Fixed(1); + pub static BROTLI: Fixed = Fixed(2); + + /// A stream no type C holds implements, which C cannot implement either, as tokio's + /// `AsyncRead` bounds the stream moq-tokio's TLS acceptor takes. + pub trait Stream { + fn read(&mut self) -> u8; + } } diff --git a/ffi/runtime/rt.rs b/ffi/runtime/rt.rs index 89e8c27a6..61cf66588 100644 --- a/ffi/runtime/rt.rs +++ b/ffi/runtime/rt.rs @@ -36,19 +36,33 @@ pub fn intern(s: &str) -> &'static str { s } +/// `b` for as long as the program runs, as [`intern`] keeps a string: keyed by its +/// contents, never by the caller's pointer, which the caller may free or reuse. +pub fn intern_bytes(b: &[u8]) -> &'static [u8] { + static INTERNED: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + let mut interned = INTERNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(&b) = interned.get(b) { + return b; + } + let b: &'static [u8] = Box::leak(Box::from(b)); + interned.insert(b); + b +} + /// An `Arc` of another crate's type, held erased behind a handle with none of its API, so /// the export names neither the type nor its crate. Rust takes it back as the `Arc` it /// gave, and a handle of another such type aborts. A clone clones the `Arc` itself, so /// Rust counts each handle as an owner. pub struct Opaque(Box); -/// An `Arc` of any `T`, erased. +/// An `Arc` of any `T`, a trait object's too, erased. trait Held: Send + Sync { fn any(&self) -> &dyn std::any::Any; fn clone_box(&self) -> Box; } -impl Held for Arc { +impl Held for Arc { fn any(&self) -> &dyn std::any::Any { self } @@ -65,18 +79,18 @@ impl Clone for Opaque { } impl Opaque { - pub fn new(value: Arc) -> Self { + pub fn new(value: Arc) -> Self { Self(Box::new(value)) } /// The `Arc` it holds, lent. - pub fn get(&self, what: &str) -> &Arc { + pub fn get(&self, what: &str) -> &Arc { (self.0.any().downcast_ref()) .unwrap_or_else(|| fail(what, "an opaque handle holds another type")) } /// A clone of the `Arc` it holds. - pub fn arc(&self, what: &str) -> Arc { + pub fn arc(&self, what: &str) -> Arc { Arc::clone(self.get(what)) } } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 46a9e237f..aab78b5df 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -63,12 +63,17 @@ pub const NOT_INFERRED: &str = "instance not inferred"; /// What C can never hold: left out and listed in the census rather than refused, since /// exporting it would need constructors or returns the crate has no use for. -const UNHELD: [&str; 3] = [ +const UNHELD: [&str; 4] = [ "object no export returns", "generic type no export instantiates", "type C never holds", + UNMET, ]; +/// The construct of a type parameter bounded by another crate's trait that no export +/// implements and C cannot: no value C holds could be passed for it. +const UNMET: &str = "bound no type C holds meets"; + fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -257,6 +262,8 @@ struct Collector<'tcx> { /// lent from the receiver's handle. lending: std::cell::Cell, bytes: Option, + /// `std::vec::IntoIter`, which an `impl Iterator` parameter takes. + vec_iter: Option, /// `serde_json::Map`, a map of `serde_json::Value`s. json_map: Option, /// The standard library's crates, `core`, `alloc`, and `std`, known by what each @@ -327,6 +334,26 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { }; let bytes = root("bytes", "Bytes"); let json_map = root("serde_json", "Map"); + // What `Vec` iterates by value as. + let vec_iter = (|| { + let into_iter = tcx.get_diagnostic_item(sym::IntoIterator)?; + let assoc = (tcx + .associated_items(into_iter) + .filter_by_name_unhygienic(rustc_span::Symbol::intern("IntoIter"))) + .next()?; + let vec = tcx.get_diagnostic_item(sym::Vec)?; + let alloc = tcx.lang_items().global_alloc_ty()?; + let alloc = Ty::new_adt(tcx, tcx.adt_def(alloc), ty::GenericArgs::empty()); + let vec = Ty::new_adt(tcx, tcx.adt_def(vec), tcx.mk_args(&[tcx.types.u8.into(), alloc.into()])); + let iter = Ty::new_projection(tcx, ty::IsRigid::No, assoc.def_id, [vec]); + let iter = tcx + .try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), ty::Unnormalized::new_wip(iter)) + .ok()?; + match iter.kind() { + ty::Adt(adt, _) => Some(adt.did()), + _ => None, + } + })(); let sysroot: Vec = [ tcx.lang_items().sized_trait(), tcx.lang_items().owned_box(), @@ -398,6 +425,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { impls: Default::default(), lending: Default::default(), bytes, + vec_iter, json_map, sysroot: sysroot.clone(), foreign: Vec::new(), @@ -900,25 +928,45 @@ impl<'tcx> Collector<'tcx> { return None; } let inner = args.type_at(0); - let ty::Adt(adt, inner_args) = inner.kind() else { - return None; + let (did, inner_args) = match inner.kind() { + ty::Adt(adt, inner_args) => (adt.did(), inner_args.as_slice()), + ty::Dynamic(..) => (self.held_trait(inner)?, &[][..]), + _ => return None, }; - let did = adt.did(); let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); let held = !self.walked(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; (held && inner_args.is_empty() && self.is_send(inner, TypingEnv::fully_monomorphized()) && self.is_sync(inner)) .then_some(did) } + /// The trait of a trait object an opaque handle may hold: one of a crate the walk from + /// the root does not reach, and not the standard library's, whose traits are closures and + /// markers; taking no arguments, as its handle names none; and with no associated type + /// fixed, which would be one. + fn held_trait(&self, ty: Ty<'tcx>) -> Option { + let ty::Dynamic(preds, ..) = ty.kind() else { return None }; + let principal = preds.principal()?.skip_binder(); + let did = principal.def_id; + let plain = principal.args.is_empty() && preds.projection_bounds().next().is_none(); + (plain && !self.walked(did.krate) && !self.sysroot.contains(&did.krate)).then_some(did) + } + /// The type a handle holds by value, if it exports as an opaque handle: as /// [`Self::opaque_arc`]'s, a type of a crate the walk from the root does not reach, /// taking no type parameters, and `Send` and `Sync`, but not an iterator or a future, /// nor one that exports by its own crate's path. Its lifetimes are `'static`, as an object's are. fn opaque_value(&self, ty: Ty<'tcx>) -> Option { + // A `'static` borrow of a trait object is a value, as `&'static dyn Trait` is `Copy`, + // held as the `Arc` form's trait is. + if let ty::Ref(region, inner, ty::Mutability::Not) = ty.kind() { + let did = self.held_trait(*inner).filter(|_| region.is_static())?; + return (self.opaque(did) && self.is_send(ty, TypingEnv::fully_monomorphized()) && self.is_sync(ty)) + .then_some(did); + } let ty::Adt(adt, args) = ty.kind() else { return None }; let did = adt.did(); - let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); - let held = !self.walked(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; + let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did) || self.by_role(did); + let held = !self.walked(did.krate) && !mapped; // Each lifetime is `'static` in the export, as an object's is. let erasable = args.iter().all(|arg| matches!(arg.kind(), GenericArgKind::Lifetime(_))); // Asked of a signature's type, whose lifetimes may be bound by it. @@ -939,6 +987,30 @@ impl<'tcx> Collector<'tcx> { .then_some(did) } + /// Whether `did` is one of the standard library's types that crosses by its role rather + /// than in a handle, such as `String` or `SocketAddr`, or that will: `IpAddr` and its + /// families, which stay refused until they cross as `SocketAddr` does. A collection's + /// allocator and hasher are part of the collection's role. + fn by_role(&self, did: DefId) -> bool { + const ROLES: [&str; 14] = [ + "String", + "Duration", + "Path", + "PathBuf", + "Waker", + "Context", + "SocketAddr", + "SocketAddrV4", + "SocketAddrV6", + "IpAddr", + "Ipv4Addr", + "Ipv6Addr", + "Global", + "RandomState", + ]; + self.sysroot.contains(&did.krate) && ROLES.contains(&self.tcx.item_name(did).as_str()) + } + /// Whether `did`, the type of `ty`, exports with its API by its public path in its own /// crate once a signature names it: an error never does, crossing as its message. fn reaches(&self, ty: Ty<'tcx>, did: DefId) -> bool { @@ -1664,23 +1736,33 @@ impl<'tcx> Collector<'tcx> { let name = tcx.item_name(def_id); if self.opaque(def_id) { let owned = self.owned.contains(&def_id); + // A trait's handle holds a trait object of it. + let held = match tcx.def_kind(def_id) { + DefKind::Trait if owned => format!("&'static dyn {}", tcx.def_path_str(def_id)), + DefKind::Trait => format!("dyn {}", tcx.def_path_str(def_id)), + _ => tcx.def_path_str(def_id), + }; let docs = match owned { true => format!( - "`{}`: a handle to another crate's value, which Rust takes back or borrows, with none of its API.", - tcx.def_path_str(def_id) + "`{held}`: a handle to another crate's value, which Rust takes back or borrows, with none of its API." ), false => format!( - "`Arc<{}>`: a handle to another crate's value, which Rust takes back, with none of its API.", - tcx.def_path_str(def_id) + "`Arc<{held}>`: a handle to another crate's value, which Rust takes back, with none of its API." ), }; + // The standard library's is named through its module, as `std::io::Error`, since its + // names repeat across modules. + let path: Path = match self.sysroot.contains(&def_id.krate) { + true => tcx.def_path_str(def_id).split("::").map(str::to_string).collect(), + false => vec![krate.to_string(), name.to_string()], + }; return Object { - path: vec![krate.to_string(), name.to_string()], home: Home { krate: self.keys[&def_id.krate].clone(), outside: 2, }, - shown: vec![self.report.root.clone(), krate.to_string(), name.to_string()], + shown: [&[self.report.root.clone()][..], &path].concat(), + path, args: Vec::new(), span, on: On::ALL, @@ -1881,7 +1963,20 @@ impl<'tcx> Collector<'tcx> { fn arg(&self, ty: Ty<'tcx>) -> Result { let arg = match ty.kind() { ty::Tuple(list) if list.is_empty() => Type::Unit, - _ => self.ty(ty, Pos::Behind)?, + _ => match self.ty(ty, Pos::Behind) { + Ok(arg) => arg, + // A type a handle holds erased, which the glue never names, names no instance C + // holds. + Err(why) + if why.construct == "foreign type" + && let ty::Adt(adt, _) = ty.kind() + && (self.barred.contains(&adt.did()) + || self.foreign.iter().any(|&(other, _)| other == adt.did())) => + { + return Err(self::why("type C never holds", self.spell(ty))); + } + Err(why) => return Err(why), + }, }; match arg { Type::Unit @@ -2210,8 +2305,7 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) - || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) + }) || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if !used { self.api.enums.pop(); @@ -2235,9 +2329,8 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) - || (api.objects.iter().enumerate()) - .any(|(i, o)| i != gone && (args(&o.args) || o.methods.iter().any(signature))) + }) || (api.objects.iter().enumerate()) + .any(|(i, o)| i != gone && (args(&o.args) || o.methods.iter().any(signature))) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if used { continue; @@ -2333,8 +2426,13 @@ impl<'tcx> Collector<'tcx> { let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); // A field that is an object but not `Clone` is lent from the receiver's handle, // as a method's borrowed return of one is. + // So is an `Option` of one, as `Some` of the borrow. + let object = match ty.kind() { + ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => args.type_at(0), + _ => ty, + }; let lends = !self.is_clone(ty) - && matches!(ty.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); + && matches!(object.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); let mapped = { self.lending.set(lends); let get = self.ty(read, Pos::Return); @@ -2385,8 +2483,7 @@ impl<'tcx> Collector<'tcx> { instance: None, home: Home::default(), }; - let lent = lends - && matches!(&get, Type::Ref(Mutability::Not, inner) if matches!(**inner, Type::Object(_))); + let lent = lends && lent(&get); let mut getter = accessor(Receiver::Ref, Vec::new(), get, false); getter.lends = lent; accessors.push(getter); @@ -2813,8 +2910,7 @@ impl<'tcx> Collector<'tcx> { // is, takes it from the future, as it would a parameter. ty::Ref(_, inner, _) if Some(*inner) == self_ty - && polled.is_some() - && let Some(kind) = self.task(ty, true) => + && polled.is_some() && let Some(kind) = self.task(ty, true) => { tasks.push(Task { at: 0, kind }); None @@ -2967,6 +3063,22 @@ impl<'tcx> Collector<'tcx> { if future && params.iter().any(|p: &Param| p.ty.written()) { errs.push(why("&mut of a value in a future", "")); } + // Each borrowed item is lent for the call, which a future outlives, and a callback + // would take an iterator from Rust, which no language holds. + if (future || callback) + && params + .iter() + .any(|p: &Param| matches!(p.ty, Type::List(Collection::IterRef, _))) + { + errs.push(why("iterator of borrows in a future or callback", "")); + } + if callback + && params + .iter() + .any(|p: &Param| matches!(p.ty, Type::List(Collection::Iter, _))) + { + errs.push(why("iterator in a callback", "")); + } // A reader is lent for the call, which a future outlives. if future && params.iter().any(|p: &Param| *p.ty.base() == Type::Reader) { errs.push(why("reader lent to a future", "")); @@ -3056,8 +3168,7 @@ impl<'tcx> Collector<'tcx> { } } } - let lends = matches!(ok, Ok(Type::Ref(Mutability::Not, ref inner)) if matches!(**inner, Type::Object(_))) - && !self.is_clone(ok_ty.peel_refs()); + let lends = ok.as_ref().is_ok_and(lent) && !self.is_clone(ok_ty.peel_refs()); let ok = ok.map_err(|why| errs.push(why)).ok(); let err = match err { Some(Ok(err)) => Some(err), @@ -3067,13 +3178,24 @@ impl<'tcx> Collector<'tcx> { } None => None, }; + // What interning costs, which the caller cannot see from the parameter's type. + let mut docs = docs(tcx, def_id); + for param in params.iter().filter(|p| p.interned) { + if !docs.is_empty() { + docs.push_str("\n\n"); + } + docs.push_str(&format!( + "`{}` must live as long as the program, so each distinct value passed is copied once and never freed: memory grows with each distinct value.", + param.name + )); + } match (errs.is_empty(), ok) { (true, Some(ok)) => Ok(Function { path, shown, span: tcx.def_span(def_id), on: On::ALL, - docs: docs(tcx, def_id), + docs, receiver, params, units, @@ -3118,7 +3240,11 @@ impl<'tcx> Collector<'tcx> { let mut kept = Vec::new(); // Each choice of the parameters so far, with the arguments that name it. let mut choices: Vec<(Vec>, Vec>)> = vec![(args, Vec::new())]; - for (i, arg) in identity.iter().enumerate() { + // A parameter another iterates, as `S` in `I: IntoIterator`, is chosen first, + // so the iterator's choice sees its items. + let mut order: Vec<(usize, ty::GenericArg<'tcx>)> = identity.iter().enumerate().collect(); + order.sort_by_key(|&(_, arg)| !arg.as_type().is_some_and(|ty| self.iterated(def_id, ty))); + for (i, arg) in order { let param = match arg.kind() { _ if i < count => continue, GenericArgKind::Lifetime(_) => continue, @@ -3334,14 +3460,23 @@ impl<'tcx> Collector<'tcx> { } else if tcx.is_diagnostic_item(sym::IntoIterator, tr) { // Borrowed items iterate a slice C lends, borrowed for the items' own lifetime, // so the signature's borrows decide whether C's slice lives long enough. - let items = self.items(&identity.clauses, param).and_then(|item| match item.kind() { - ty::Ref(region, elem, ty::Mutability::Not) - if !outlives && !matches!(region.kind(), ty::ReBound(..)) => - { - Some(Ty::new_imm_ref(tcx, *region, Ty::new_slice(tcx, *elem))) - } - _ => self.vec_of(item), - }); + let items = self + .items(&identity.clauses, param, sym::IntoIterator) + .and_then(|item| match item.kind() { + ty::Ref(region, elem, ty::Mutability::Not) + if !outlives && !matches!(region.kind(), ty::ReBound(..)) => + { + Some(Ty::new_imm_ref(tcx, *region, Ty::new_slice(tcx, *elem))) + } + _ => self.vec_of(item), + }); + candidates.extend(items.map(|ty| (ty, None))); + } else if tcx.is_diagnostic_item(sym::Iterator, tr) { + // The array of its items, which Rust iterates by value: a borrowed string or bytes + // borrow what C lends for the call, the rest are owned. + let items = (self.items(&identity.clauses, param, sym::Iterator)) + .filter(|item| !outlives || !item.is_ref()) + .and_then(|item| self.vec_iter_of(item)); candidates.extend(items.map(|ty| (ty, None))); } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("IoRead"), tr) && !outlives { // What it reads, which C lends for the call. @@ -3362,8 +3497,11 @@ impl<'tcx> Collector<'tcx> { // `impl Into>` takes a `String` too, which maps where `Arc` does not. // Not another crate's type a handle holds: the glue never names it, so nothing would // fix the call's type argument. + let iterated = self.iterated(def_id, param); candidates.retain(|&(candidate, _)| { - self.at(def_id, param, base, candidate).is_some() + // An array's items are owned, as C lends nothing inside one. + !(iterated && candidate.is_ref()) + && self.at(def_id, param, base, candidate).is_some() && self.maps(candidate, Pos::Param) && !(candidate.walk().filter_map(|arg| arg.as_type())).any(|ty| self.is_opaque(ty)) }); @@ -3397,12 +3535,37 @@ impl<'tcx> Collector<'tcx> { .filter(|b| !sized.contains(&Some(b.def_id()))) .map(|b| tcx.def_path_str(b.def_id())) .collect(); + // Another crate's trait, which no type the export holds meets, as instantiating found + // none, and C cannot implement: no value C holds could be passed. The standard library's + // traits are met by values C passes, which the rules may yet take. + let unmet = (bounds.iter().map(|b| b.def_id())).any(|tr| { + !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate) + || matches!(self.trait_decl(tr), Some(Decl::Refused(_))) + }); match local[..] { [_] => Err(why("callback bound", names.join(" + "))), + [] if unmet => Err(why(UNMET, names.join(" + "))), _ => Err(why("generic parameter", names.join(" + "))), } } + /// Whether `param` is the `Item` of another of `def_id`'s parameters' `IntoIterator` or + /// `Iterator` bounds. + fn iterated(&self, def_id: DefId, param: Ty<'tcx>) -> bool { + let tcx = self.tcx; + (tcx.clauses_of(def_id).instantiate_identity(tcx).clauses.iter()) + .filter_map(|clause| clause.skip_norm_wip().as_projection_clause()) + .map(|pred| pred.skip_binder()) + .any(|pred| { + let item = pred.projection_term.expect_projection_def_id(); + let iterator = tcx.parent(item); + (tcx.is_diagnostic_item(sym::IntoIterator, iterator) || tcx.is_diagnostic_item(sym::Iterator, iterator)) + && tcx.item_name(item) == sym::Item + && pred.projection_term.self_ty() != param + && pred.term.as_type() == Some(param) + }) + } + /// `serde_json::Value`, if it exports as a foreign object. fn json(&self) -> Option> { let tcx = self.tcx; @@ -3413,7 +3576,12 @@ impl<'tcx> Collector<'tcx> { /// The `Item` that `clauses` bind `param`'s `IntoIterator` to, if it names no type /// parameter, which a `Vec` of it then iterates as. - fn items(&self, clauses: &[ty::Unnormalized<'tcx, ty::Clause<'tcx>>], param: Ty<'tcx>) -> Option> { + fn items( + &self, + clauses: &[ty::Unnormalized<'tcx, ty::Clause<'tcx>>], + param: Ty<'tcx>, + iterator: rustc_span::Symbol, + ) -> Option> { let tcx = self.tcx; (clauses.iter()) .filter_map(|clause| clause.skip_norm_wip().as_projection_clause()) @@ -3422,7 +3590,7 @@ impl<'tcx> Collector<'tcx> { let term = pred.projection_term; let item = term.expect_projection_def_id(); term.self_ty() == param - && tcx.is_diagnostic_item(sym::IntoIterator, tcx.parent(item)) + && tcx.is_diagnostic_item(iterator, tcx.parent(item)) && tcx.item_name(item) == sym::Item }) .and_then(|pred| pred.term.as_type()) @@ -3806,8 +3974,7 @@ impl<'tcx> Collector<'tcx> { .inputs() .iter() .filter(|&&input| input == param) - .count() - > 1 + .count() > 1 { return Some(Err(why("closure type taken twice", param.to_string()))); } @@ -3991,6 +4158,15 @@ impl<'tcx> Collector<'tcx> { } /// `Vec`. + /// `std::vec::IntoIter`, an iterator C passes as the array of its items. + fn vec_iter_of(&self, item: Ty<'tcx>) -> Option> { + let tcx = self.tcx; + let ty::Adt(_, args) = self.vec_of(item)?.kind() else { + return None; + }; + Some(Ty::new_adt(tcx, tcx.adt_def(self.vec_iter?), *args)) + } + fn vec_of(&self, item: Ty<'tcx>) -> Option> { let tcx = self.tcx; let vec = tcx.get_diagnostic_item(sym::Vec)?; @@ -4151,16 +4327,11 @@ impl<'tcx> Collector<'tcx> { let plain = matches!( ty.kind(), ty::Adt(..) - | ty::Bool - | ty::Char - | ty::Int(_) - | ty::Uint(_) - | ty::Float(_) - | ty::Str - | ty::Array(..) - | ty::Slice(_) - | ty::Ref(..) - | ty::Tuple(_) + | ty::Bool | ty::Char + | ty::Int(_) | ty::Uint(_) + | ty::Float(_) | ty::Str + | ty::Array(..) | ty::Slice(_) + | ty::Ref(..) | ty::Tuple(_) ); let (method, driven) = match (implements(iterator, ty), implements(into_iterator, ty)) { (true, _) => (next, item), @@ -4268,12 +4439,13 @@ impl<'tcx> Collector<'tcx> { let mut refused = Vec::new(); let mut interned = Vec::new(); for &(region, n, input) in &lent { - // A string lives as long as the program once interned, which a binding passes - // as it passes any other. + // A string or bytes live as long as the program once interned, which a binding + // passes as it passes any other. Shared and never freed, the copy is as good as + // the caller's: equal contents differ only by address. if statics.contains(®ion) && let ty::Ref(r, inner, ty::Mutability::Not) = input.kind() && *r == region - && inner.is_str() + && (inner.is_str() || matches!(inner.kind(), ty::Slice(elem) if *elem == tcx.types.u8)) { interned.push(n); continue; @@ -4363,6 +4535,8 @@ impl<'tcx> Collector<'tcx> { let mut lent = Vec::new(); for ty in ty.walk().filter_map(|arg| arg.as_type()) { match ty.kind() { + // Another crate's `&'static dyn Trait`, which a handle holds. + ty::Ref(region, ..) if self.opaque_value(ty).is_some() => held.push(*region), ty::Ref(region, ..) => lent.push(*region), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_))) @@ -4736,6 +4910,25 @@ impl<'tcx> Collector<'tcx> { ty::Float(ty::FloatTy::F64) => Type::F64, ty::Uint(ty::UintTy::U128) => Type::U128, ty::Int(_) | ty::Uint(_) => Type::Int(int(ty).ok_or_else(|| why("128-bit integer", ty.to_string()))?), + // Another crate's `&'static dyn Trait`, held by value. + ty::Ref(..) + if let Some(did) = self.opaque_value(ty) + && let Some(&(_, i)) = self.foreign.iter().find(|&&(other, _)| other == did) => + { + if self.both.contains(&did) { + return Err(why(BOTH, tcx.def_path_str(did))); + } + if self.orphans.contains(&Key { + def_id: did, + args: None, + }) { + return Err(why("type C never holds", tcx.def_path_str(did))); + } + match pos { + Pos::Field => return Err(why("object in a value", tcx.def_path_str(did))), + _ => Type::Object(i), + } + } ty::Ref(_, inner, m) => { let inner_ty = match inner.kind() { ty::Str => Type::Str, @@ -4797,6 +4990,16 @@ impl<'tcx> Collector<'tcx> { // another crate's value, which a handle holds only erased and by value. (Type::Object(_), Pos::Return, Mutability::Not) if self.lending.take() && self.opaque_value(*inner).is_none() => {} + // A borrowed `Option` of one is lent as `Some` of a borrow of it, so C holds the + // handle the bare borrow would be. + (Type::Option(object), Pos::Return, Mutability::Not) + if matches!(**object, Type::Object(_)) + && let ty::Adt(_, args) = inner.kind() + && self.opaque_value(args.type_at(0)).is_none() + && self.lending.take() => + { + return Ok(Type::Option(Box::new(Type::Ref(Mutability::Not, object.clone())))); + } // A slice's clone is a `Vec` of its elements' clones. (_, Pos::Return | Pos::Returned, _) if !self.is_clone(match inner.kind() { @@ -4879,6 +5082,28 @@ impl<'tcx> Collector<'tcx> { Type::List(c, Box::new(inner)) } else if Some(did) == self.bytes { Type::Bytes + } else if Some(did) == self.vec_iter { + // An `impl Iterator` parameter's, which C passes as the array of its items. A + // borrowed string or bytes borrow what C lends for the call. + if pos != Pos::Param { + return Err(why("iterator outside a parameter", ty.to_string())); + } + let elem = args.type_at(0); + match elem.kind() { + ty::Ref(_, inner, ty::Mutability::Not) if inner.is_str() => { + Type::List(Collection::IterRef, Box::new(Type::String)) + } + ty::Ref(_, inner, ty::Mutability::Not) if matches!(inner.kind(), ty::Slice(byte) if *byte == tcx.types.u8) => { + Type::List(Collection::IterRef, Box::new(Type::Vec)) + } + _ => { + let inner = self.ty(elem, pos.inner())?; + if borrows(&inner) { + return Err(why("iterator of references", elem.to_string())); + } + Type::List(Collection::Iter, Box::new(inner)) + } + } } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("Duration"), did) { Type::Duration } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("NonZero"), did) { @@ -4968,7 +5193,8 @@ impl<'tcx> Collector<'tcx> { } else if tcx.is_diagnostic_item(sym::Arc, did) { let inner = args.type_at(0); match inner.kind() { - ty::Dynamic(preds, ..) => { + // Another crate's trait is held as its other types are, below. + ty::Dynamic(preds, ..) if self.opaque_arc(ty).is_none() => { return self.dynamic(preds.principal_def_id(), Dyn::Arc, inner, pos); } // Held erased, as a handle with none of its API, which Rust takes back. @@ -5084,6 +5310,15 @@ impl<'tcx> Collector<'tcx> { Err(_) => return Err(why("array too long", ty.to_string())), } } + // Returned as the array of its elements, as a returned slice is: C has no fixed-size + // array of a value that is not plain bytes. + ty::Array(elem, len) if matches!(pos, Pos::Return | Pos::Returned) => { + let n = len + .try_to_target_usize(tcx) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| why("array of unknown length", ty.to_string()))?; + Type::List(Collection::Array(n), Box::new(self.ty(*elem, Pos::Returned)?)) + } ty::Array(..) => return Err(why("array of an element other than u8", ty.to_string())), ty::Slice(_) | ty::Str => return Err(why("unsized type", ty.to_string())), ty::Dynamic(..) => return Err(why("trait object", ty.to_string())), @@ -5295,6 +5530,16 @@ fn lends_inside(ty: &Type) -> bool { } } +/// Whether a return of `ty` is a borrowed object, or `Some` of one, which its receiver's +/// handle may lend. +fn lent(ty: &Type) -> bool { + let borrowed = |ty: &Type| matches!(ty, Type::Ref(Mutability::Not, inner) if matches!(**inner, Type::Object(_))); + match ty { + Type::Option(inner) => borrowed(inner), + ty => borrowed(ty), + } +} + /// Whether a callback can return `ty`: a value with no memory to own. fn foreign_return(ty: &Type) -> bool { matches!( diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 922cfefb2..41c5e3d03 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -613,12 +613,10 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 - | Ty::Duration + | Ty::U128 | Ty::Duration | Ty::SocketAddr | Ty::Struct(_) - | Ty::Waker - | Ty::ForeignFuture + | Ty::Waker | Ty::ForeignFuture | Ty::ForeignReader ) } diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 485fede70..573b7b267 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -82,6 +82,8 @@ fn collection(c: Collection) -> String { Collection::Vec => "::std::vec::Vec".to_string(), Collection::Box => "::std::boxed::Box".to_string(), Collection::Slice => unreachable!("a slice is spelled `[T]`"), + Collection::Array(_) => unreachable!("an array is spelled `[T; N]`"), + Collection::Iter | Collection::IterRef => "::std::vec::IntoIter".to_string(), Collection::BTreeSet => "::std::collections::BTreeSet".to_string(), Collection::BTreeMap => "::std::collections::BTreeMap".to_string(), Collection::JsonMap => format!("::{}::Map", foreign("serde_json")), @@ -628,6 +630,9 @@ impl Gen<'_> { } (Collection::Box, _) => format!("{}<[{}]>", collection(*c), self.rust(inner)), (Collection::Slice, _) => format!("[{}]", self.rust(inner)), + (Collection::Array(n), _) => format!("[{}; {n}]", self.rust(inner)), + (Collection::IterRef, Type::String) => format!("{}<&str>", collection(*c)), + (Collection::IterRef, _) => format!("{}<&[u8]>", collection(*c)), _ => format!("{}<{}>", collection(*c), self.rust(inner)), }, Type::Option(inner) => format!("Option<{}>", self.rust(inner)), @@ -682,6 +687,12 @@ impl Gen<'_> { _ => "::std::vec::Vec::<_>", } ), + // An iterator iterates the `Vec` of its items. + Type::List(Collection::Iter, inner) => format!( + "::std::iter::IntoIterator::into_iter({})", + self.lift(&Type::List(Collection::Vec, inner.clone()), e, take) + ), + Type::List(Collection::IterRef, _) => unreachable!("an iterator of borrows is lent by `arg`"), Type::List(c, inner) => format!( "unsafe {{ {e}.items(w) }}.iter().map(|c| {}).collect::<{}>()", // An array's items are behind its pointer, so only read. @@ -691,6 +702,9 @@ impl Gen<'_> { Collection::Box => format!("{}<[_]>", collection(*c)), Collection::Vec | Collection::Slice => format!("{}<_>", collection(Collection::Vec)), Collection::BTreeSet => format!("{}<_>", collection(*c)), + Collection::Array(_) | Collection::Iter | Collection::IterRef => { + unreachable!("{c:?} is lifted apart") + } } ), // A foreign enum's option converts into its filter, as `tracing::LevelFilter`. @@ -873,7 +887,7 @@ impl Gen<'_> { Type::Array(n) => format!("{} {{ items: {e} }}", self.abi.array(*n)), Type::SocketAddr(_) => format!("rt::SocketAddr::lower(::std::net::SocketAddr::from({e}))"), // A block hands over its own allocation. - Type::List(Collection::Box, _) if ty.block().is_some() => { + Type::List(Collection::Box | Collection::Array(_), _) if ty.block().is_some() => { format!("rt::List::owned(::std::vec::Vec::from({e}))") } Type::List(..) if ty.block().is_some() => format!("rt::List::owned({e})"), @@ -1561,6 +1575,14 @@ impl Gen<'_> { (format!("{binding} {local} = {};", self.lift(inner, c, "true")), pass) } }, + // An iterator of borrowed strings or bytes, each lent from its owned copy for the call. + Type::List(Collection::IterRef, item) => ( + format!( + "let {local}_items = {};\n\tlet {local} = {local}_items.iter().map(|v| &v[..]).collect::<::std::vec::Vec<_>>();", + self.lift(&Type::List(Collection::Vec, item.clone()), c, "true") + ), + format!("::std::iter::IntoIterator::into_iter({local})"), + ), // `Some` of a borrow, lent as the borrow alone is: a null handle or buffer is `None`. Type::Option(opt) if let Type::Ref(m, inner) = &**opt => match (&**inner, future) { (Type::Object(i), _) => { @@ -1784,6 +1806,10 @@ impl Gen<'_> { pass, ) } + _ if param.interned && *param.ty.base() == Type::Slice => ( + format!("let a{n} = rt::intern_bytes(unsafe {{ p{n}.hold(w) }}.bytes());"), + format!("a{n}"), + ), _ if param.interned => ( format!("let a{n} = rt::intern(unsafe {{ p{n}.hold(w) }}.str(w));"), format!("a{n}"), diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index caa894a74..044d51580 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -419,8 +419,9 @@ pub enum Receiver { pub struct Param { pub name: String, pub ty: Type, - /// Whether it is a `&str` that must be `'static`, which the glue interns: it leaks each - /// distinct string once and lends that copy to every later call with equal content. + /// Whether it is a `&str` or `&[u8]` that must be `'static`, which the glue interns: it + /// leaks each distinct value once and lends that copy to every later call with equal + /// content. pub interned: bool, } @@ -555,6 +556,13 @@ pub enum Collection { BTreeMap, /// `serde_json::Map`, of `String` keys and `serde_json::Value`s. JsonMap, + /// `[T; N]` of any `T` but `u8`, which is [`Type::Array`]: only returned. + Array(usize), + /// `std::vec::IntoIter`, which an `impl Iterator` parameter takes: only a parameter. + Iter, + /// `std::vec::IntoIter<&str>` or `std::vec::IntoIter<&[u8]>`, of a [`Type::String`] or + /// [`Type::Vec`], each lent for the call: only a parameter. + IterRef, } /// The addresses a socket address type holds. @@ -660,11 +668,13 @@ impl Type { /// one array type holds them on every target. pub fn block(&self) -> Option<&Type> { match self { - Type::List(Collection::Vec | Collection::Slice | Collection::Box, inner) => match &**inner { - Type::Int(Int::Usize | Int::Isize) => None, - Type::Int(_) | Type::F32 | Type::F64 => Some(inner), - _ => None, - }, + Type::List(Collection::Vec | Collection::Slice | Collection::Box | Collection::Array(_), inner) => { + match &**inner { + Type::Int(Int::Usize | Int::Isize) => None, + Type::Int(_) | Type::F32 | Type::F64 => Some(inner), + _ => None, + } + } _ => None, } } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index fd1b933ff..d54a58b56 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1480,6 +1480,37 @@ static int script(void) { printf("%llu\n", (unsigned long long)api_chain_len((api_vec_tls_Cert){.ptr = chain, .len = 2})); api_tls_Cert_free(chain[0]); api_tls_Cert_free(chain[1]); + /* Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. */ + api_tls_Resolver *resolver = api_resolver(str("r1")); + print("resolver ", api_resolved(resolver), "\n"); + api_tls_Resolver_free(resolver); + api_Codecs *codecs = api_Codecs_new(); + printf("codecs %u\n", api_Codecs_ids(codecs)); + api_vec_tls_Codec listed = api_Codecs_list_get(codecs); + api_tls_Codec *codecs_reversed[2] = {listed.ptr[1], listed.ptr[0]}; + api_Codecs_list_set(codecs, (api_vec_tls_Codec){.ptr = codecs_reversed, .len = 2}); + /* The setter took each handle's value: the array, and the handles, are still ours to free. */ + api_vec_tls_Codec_free(listed); + printf("codecs reversed %u\n", api_Codecs_ids(codecs)); + api_Codecs_free(codecs); + /* A standard library value no type maps, in a handle. */ + api_std_io_Error *failure = api_failure(str("boom")); + print("failure ", api_failure_message(failure), " "); + print("", api_failure_kind(failure), "\n"); + api_std_io_Error_free(failure); + /* Iterators, passed as the arrays of their items. */ + const uint32_t summed_items[] = {1, 2, 3}; + printf("sum_all %u\n", api_sum_all((api_vec_u32){.ptr = summed_items, .len = 3})); + const api_buf alpns[] = {str("h3"), str("moq-00")}; + printf("offered_len %zu\n", api_offered_len((api_vec_bytes){.ptr = alpns, .len = 2})); + const api_buf joined_words[] = {str("a"), str("b"), str("c")}; + print("join_words ", api_join_words((api_vec_string){.ptr = joined_words, .len = 3}), "\n"); + /* Bytes that must be `'static`, interned. */ + for (int i = 0; i < 2; i++) { + api_Der *der = api_Der_from_slice(str("der")); + print(i == 0 ? "der " : "der again ", api_Der_bytes(der), "\n"); + api_Der_free(der); + } /* Another crate's type only signatures name, exported by its path there, and its error, * which crosses as its message. */ api_tls_Session *session; @@ -1513,6 +1544,14 @@ static int script(void) { api_Meter_add(last, 4); printf("field lent %llu\n", (unsigned long long)api_Meter_add(last, 1)); api_Meter_free(last); + /* An optional field that is not Clone, lent as `Some` of a handle. */ + api_Meter *spare = api_Meters_spare_get(lender); + printf("spare %s\n", spare != NULL ? "true" : "false"); + api_Meters_spare_set(lender, api_Meter_default()); + spare = api_Meters_spare_get(lender); + api_Meter_add(spare, 5); + printf("spare lent %llu\n", (unsigned long long)api_Meter_add(spare, 1)); + api_Meter_free(spare); api_Meters_free(lender); /* One lent from a handle that is not Sync, on one thread at a time. */ api_Tallies *tallies = api_Tallies_new(); @@ -1714,6 +1753,19 @@ static int script(void) { } printf("]\n"); api_vec_string_free(greetings); + api_vec_Shape shapes_both = api_Shape_BOTH(); + printf("both ["); + for (size_t i = 0; i < shapes_both.len; i++) { + print(i == 0 ? "" : ", ", api_Shape_debug(&shapes_both.ptr[i]), ""); + } + api_vec_Shape_free(shapes_both); + api_vec_u32 primes = api_PRIMES(); + printf("] primes ["); + for (size_t i = 0; i < primes.len; i++) { + printf("%s%u", i == 0 ? "" : ", ", primes.ptr[i]); + } + printf("]\n"); + api_vec_u32_free(primes); api_Point trail_points[] = {{.x = 1, .y = 2}, {.x = 3, .y = 4}}; api_buf trail_names[] = {str("a"), str("b")}; api_Trail *trail = diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 356ceacba..5bfd84aa6 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -932,6 +932,27 @@ int script() { chain.push_back(api::certify("a")); chain.push_back(api::certify("bc")); std::printf("%llu\n", ull(api::chain_len(std::move(chain)))); + // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. + print("resolver ", api::resolved(api::resolver("r1")), "\n"); + auto codecs = api::Codecs::new_(); + std::printf("codecs %u\n", unsigned(codecs.ids())); + auto listed = codecs.list_get(); + std::vector reversed; + reversed.push_back(std::move(listed[1])); + reversed.push_back(std::move(listed[0])); + codecs.list_set(std::move(reversed)); + std::printf("codecs reversed %u\n", unsigned(codecs.ids())); + // A standard library value no type maps, in a handle. + auto failure = api::failure("boom"); + print("failure ", api::failure_message(failure), " "); + print("", api::failure_kind(std::move(failure)), "\n"); + // Iterators, passed as the arrays of their items. + std::printf("sum_all %u\n", unsigned(api::sum_all({1, 2, 3}))); + std::printf("offered_len %llu\n", ull(api::offered_len({"h3", "moq-00"}))); + print("join_words ", api::join_words({"a", "b", "c"}), "\n"); + // Bytes that must be `'static`, interned. + print("der ", api::Der::from_slice("der").bytes(), "\n"); + print("der again ", api::Der::from_slice("der").bytes(), "\n"); auto session = api::resume("h3", 60); print("resume ", session.value().alpn(), " "); std::printf("%u\n", unsigned(session.value().lifetime().seconds)); @@ -946,6 +967,12 @@ int script() { auto last = meters.last_get(); last.add(4); std::printf("field lent %llu\n", ull(last.add(1))); + // An optional field that is not Clone, lent as `Some` of a handle. + std::printf("spare %s\n", meters.spare_get() ? "true" : "false"); + meters.spare_set(api::Meter::default_()); + auto spare = meters.spare_get(); + spare->add(5); + std::printf("spare lent %llu\n", ull(spare->add(1))); auto tallies = api::Tallies::new_(); tallies.first().bump(); std::printf("tallied %u\n", tallies.first().bump()); @@ -1093,6 +1120,17 @@ int script() { std::printf("] greetings "); print_strings(api::GREETINGS()); std::printf("\n"); + auto both = api::Shape_BOTH(); + std::printf("both ["); + for (std::size_t i = 0; i < both.size(); i++) { + print(i == 0 ? "" : ", ", api::Shape_debug(both[i]), ""); + } + std::printf("] primes ["); + auto primes = api::PRIMES(); + for (std::size_t i = 0; i < primes.size(); i++) { + std::printf("%s%u", i == 0 ? "" : ", ", unsigned(primes[i])); + } + std::printf("]\n"); api::Trail trail = api::Trail::new_({api::Point{1, 2}, api::Point{3, 4}}, {"a", "b"}); auto points = trail.points(); std::printf("trail ["); diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 6249ba440..5aeadceeb 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -573,6 +573,26 @@ Future script() async { final certLen = api.certLen(cert); print('cert $certLen ${text(api.certDer(cert))} ${api.chainLen([api.certify(utf8.encode('a')), api.certify(utf8.encode('bc'))])}'); config.close(); + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print('resolver ${api.resolved(api.resolver('r1'))}'); + final codecs = api.Codecs(); + print('codecs ${codecs.ids()}'); + codecs.listSet(codecs.listGet.reversed.toList()); + print('codecs reversed ${codecs.ids()}'); + codecs.close(); + // A standard library value no type maps, in a handle. + final failure = api.failure('boom'); + print('failure ${api.failureMessage(failure)} ${api.failureKind(failure)}'); + // Iterators, passed as the arrays of their items. + print('sum_all ${api.sumAll([1, 2, 3])}'); + print('offered_len ${api.offeredLen([utf8.encode('h3'), utf8.encode('moq-00')])}'); + print('join_words ${api.joinWords(['a', 'b', 'c'])}'); + // Bytes that must be `'static`, interned. + for (final label in ['der', 'der again']) { + final der = api.Der.fromSlice(utf8.encode('der')); + print('$label ${text(der.bytes())}'); + der.close(); + } final session = api.resume('h3', 60); print('resume ${session.alpn()} ${session.lifetime().seconds}'); session.close(); @@ -592,6 +612,13 @@ Future script() async { lastMeter.add(4); print('field lent ${lastMeter.add(1)}'); lastMeter.close(); + // An optional field that is not Clone, lent as `Some` of a handle. + print('spare ${meters.spareGet != null}'); + meters.spareSet(api.Meter.default_()); + final spare = meters.spareGet!; + spare.add(5); + print('spare lent ${spare.add(1)}'); + spare.close(); meters.close(); final tallies = api.Tallies(); tallies.first().bump(); @@ -668,6 +695,7 @@ Future script() async { _ => throw ArgumentError(v), }).join(', ')}]'; print('shapes ${debugs(api.Shape.ALL)} greetings ${quoted(api.GREETINGS)}'); + print('both ${debugs(api.Shape.BOTH)} primes ${api.PRIMES}'); final trail = api.Trail([const api.Point(x: 1, y: 2), const api.Point(x: 3, y: 4)], ['a', 'b']); print('trail ${debugs(trail.points())} ${debugs(trail.labels())}'); // Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.go b/ffi/tests/api.go index c20fdce5b..0ce704e0a 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -674,6 +674,27 @@ func script() { cert := api.Certify(rt.NewBytes([]byte("der"))) certLen := must(api.CertLen(cert)) fmt.Printf("cert %d %s %d\n", certLen, must(api.CertDer(cert)).Copy(), must(api.ChainLen([]*tls.Cert{api.Certify(rt.NewBytes([]byte("a"))), api.Certify(rt.NewBytes([]byte("bc")))}))) + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + fmt.Printf("resolver %s\n", must(api.Resolved(api.Resolver("r1")))) + codecs := api.NewCodecs() + fmt.Printf("codecs %d\n", must(codecs.Ids())) + listed := must(codecs.ListGet()) + ok(codecs.ListSet([]*tls.Codec{listed[1], listed[0]})) + fmt.Printf("codecs reversed %d\n", must(codecs.Ids())) + codecs.Close() + // A standard library value no type maps, in a handle. + failure := api.Failure("boom") + fmt.Printf("failure %s %s\n", must(api.FailureMessage(failure)), must(api.FailureKind(failure))) + // Iterators, passed as the arrays of their items. + fmt.Printf("sum_all %d\n", api.SumAll([]uint32{1, 2, 3})) + fmt.Printf("offered_len %d\n", api.OfferedLen([]rt.Bytes{rt.NewBytes([]byte("h3")), rt.NewBytes([]byte("moq-00"))})) + fmt.Printf("join_words %s\n", api.JoinWords([]string{"a", "b", "c"})) + // Bytes that must be `'static`, interned. + for _, label := range []string{"der", "der again"} { + der := api.DerFromSlice(rt.NewBytes([]byte("der"))) + fmt.Printf("%s %s\n", label, must(der.Bytes()).Copy()) + der.Close() + } session := must(api.Resume("h3", 60)) fmt.Printf("resume %s %d\n", must(session.Alpn()), must(session.Lifetime()).Seconds) session.Close() @@ -689,6 +710,12 @@ func script() { lastMeter := must(meters.LastGet()) _ = must(lastMeter.Add(4)) fmt.Printf("field lent %d\n", must(lastMeter.Add(1))) + // An optional field that is not Clone, lent as `Some` of a handle. + fmt.Printf("spare %t\n", must(meters.SpareGet()) != nil) + ok(meters.SpareSet(api.MeterDefault())) + spare := must(meters.SpareGet()) + _ = must(spare.Add(5)) + fmt.Printf("spare lent %d\n", must(spare.Add(1))) tallies := api.NewTallies() _ = must(must(tallies.First()).Bump()) fmt.Printf("tallied %d\n", must(must(tallies.First()).Bump())) @@ -780,6 +807,7 @@ func script() { // Slices, passed in and returned as clones, and the socket address of each family. fmt.Printf("shapes %s greetings %s\n", list(api.ShapeALL(), func(s api.Shape) string { return shapes[s] }), list(api.GREETINGS(), quoted)) + fmt.Printf("both %s primes %s\n", list(api.ShapeBOTH(), func(s api.Shape) string { return shapes[s] }), list(api.PRIMES(), func(n uint32) string { return fmt.Sprint(n) })) trail := api.NewTrail([]api.Point{{X: 1, Y: 2}, {X: 3, Y: 4}}, []string{"a", "b"}) point := func(p api.Point) string { return p.GoString() } labeled := func(l api.Label) string { return l.GoString() } diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 910d68e8b..76b984d67 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -491,6 +491,23 @@ fun script() { val cert = certify(Bytes("der".encodeToByteArray())) val certLen = certLen(cert) println("cert $certLen ${certDer(cert).text()} ${chainLen(listOf(certify(Bytes("a".encodeToByteArray())), certify(Bytes("bc".encodeToByteArray()))))}") + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + println("resolver ${resolved(resolver("r1"))}") + Codecs.new().use { codecs -> + println("codecs ${codecs.ids()}") + codecs.listSet(codecs.listGet.reversed()) + println("codecs reversed ${codecs.ids()}") + } + // A standard library value no type maps, in a handle. + val failure = failure("boom") + println("failure ${failureMessage(failure)} ${failureKind(failure)}") + // Iterators, passed as the arrays of their items. + println("sum_all ${sumAll(listOf(1u, 2u, 3u))}") + println("offered_len ${offeredLen(listOf(Bytes("h3".encodeToByteArray()), Bytes("moq-00".encodeToByteArray())))}") + println("join_words ${joinWords(listOf("a", "b", "c"))}") + // Bytes that must be `'static`, interned. + Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der ${it.bytes().text()}") } + Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der again ${it.bytes().text()}") } resume("h3", 60u).use { session -> println("resume ${session.alpn()} ${session.lifetime().seconds}") } try { resume("", 60u) @@ -508,6 +525,13 @@ fun script() { last.add(4uL) println("field lent ${last.add(1uL)}") } + // An optional field that is not Clone, lent as `Some` of a handle. + println("spare ${meters.spareGet != null}") + meters.spareSet(Meter.default()) + meters.spareGet!!.use { spare -> + spare.add(5uL) + println("spare lent ${spare.add(1uL)}") + } } Tallies.new().use { tallies -> tallies.first().use { it.bump() } @@ -580,6 +604,7 @@ fun script() { // Slices, passed in and returned as clones, and the socket address of each family. println("shapes ${Shape.ALL.joinToString(", ", "[", "]") { it.debug() }} greetings ${GREETINGS.joinToString(", ", "[", "]") { "\"$it\"" }}") + println("both ${Shape.BOTH.joinToString(", ", "[", "]") { it.debug() }} primes ${PRIMES.joinToString(", ", "[", "]")}") Trail.new(listOf(Point(1, 2), Point(3, 4)), listOf("a", "b")).use { trail -> println("trail ${trail.points().joinToString(", ", "[", "]") { it.debug() }} ${trail.labels().joinToString(", ", "[", "]") { it.debug() }}") // Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 2ea7d631d..07aaf860f 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -577,6 +577,22 @@ async def polls(): print(f"secure {api.alpn_lent(config)} {api.alpn(config.clone())}") cert = api.certify(b"der") print(f"cert {api.cert_len(cert)} {text(api.cert_der(cert))} {api.chain_len([api.certify(b'a'), api.certify(b'bc')])}") + # Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print(f"resolver {api.resolved(api.resolver('r1'))}") + codecs = api.Codecs.new() + print(f"codecs {codecs.ids()}") + codecs.list_set(list(reversed(codecs.list_get))) + print(f"codecs reversed {codecs.ids()}") + # A standard library value no type maps, in a handle. + failure = api.failure("boom") + print(f"failure {api.failure_message(failure)} {api.failure_kind(failure)}") + # Iterators, passed as the arrays of their items. + print(f"sum_all {api.sum_all(iter([1, 2, 3]))}") + print(f"offered_len {api.offered_len([b'h3', b'moq-00'])}") + print(f"join_words {api.join_words(['a', 'b', 'c'])}") + # Bytes that must be `'static`, interned. + print(f"der {text(api.Der.from_slice(b'der').bytes())}") + print(f"der again {text(api.Der.from_slice(b'der').bytes())}") session = api.resume("h3", 60) print(f"resume {session.alpn()} {session.lifetime().seconds}") try: @@ -592,6 +608,13 @@ async def polls(): lent_last = meters.last_get lent_last.add(4) print(f"field lent {lent_last.add(1)}") + # An optional field that is not Clone, lent as `Some` of a handle. + print(f"spare {str(meters.spare_get is not None).lower()}") + meters.spare_set(api.Meter.default()) + spare = meters.spare_get + assert spare is not None + spare.add(5) + print(f"spare lent {spare.add(1)}") tallies = api.Tallies.new() tallies.first().bump() print(f"tallied {tallies.first().bump()}") @@ -654,6 +677,7 @@ async def polls(): # Slices, passed in and returned as clones, and the socket address of each family. print(f"shapes {debugs(api.Shape.ALL)} greetings {quoted(api.GREETINGS)}") + print(f"both {debugs(api.Shape.BOTH)} primes {list(api.PRIMES)}") trail = api.Trail.new([api.Point(1, 2), api.Point(3, 4)], ["a", "b"]) print(f"trail {debugs(trail.points())} {debugs(trail.labels())}") # Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 78de5055a..fdc990c02 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -669,6 +669,27 @@ func script() { chain.append(certify(Bytes("a".utf8))) chain.append(certify(Bytes("bc".utf8))) print("cert \(certLength) \(der) \(chainLen(chain))") + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print("resolver \(resolved(resolver("r1")))") + var codecs = Codecs.new() + print("codecs \(codecs.ids())") + var listed = codecs.listGet + var reversed = UniqueArray() + reversed.append(listed.remove(at: 1)) + reversed.append(listed.remove(at: 0)) + codecs.listSet(reversed) + print("codecs reversed \(codecs.ids())") + // A standard library value no type maps, in a handle. + let failed = failure("boom") + let message = failureMessage(failed) + print("failure \(message) \(failureKind(failed))") + // Iterators, passed as the arrays of their items. + print("sum_all \(sumAll([1, 2, 3]))") + print("offered_len \(offeredLen([Bytes("h3".utf8), Bytes("moq-00".utf8)]))") + print("join_words \(joinWords(["a", "b", "c"]))") + // Bytes that must be `'static`, interned. + print("der \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") + print("der again \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") let session = try! resume("h3", 60) print("resume \(session.alpn()) \(session.lifetime().seconds)") do { @@ -687,6 +708,17 @@ func script() { let last = meters.lastGet _ = last.add(4) print("field lent \(last.add(1))") + // An optional field that is not Clone, lent as `Some` of a handle. + var hasSpare = false + if let _ = meters.spareGet { + hasSpare = true + } + print("spare \(hasSpare)") + meters.spareSet(Meter.default()) + if let spare = meters.spareGet { + _ = spare.add(5) + print("spare lent \(spare.add(1))") + } let tallies = Tallies.new() _ = tallies.first().bump() print("tallied \(tallies.first().bump())") @@ -748,6 +780,7 @@ func script() { // Slices, passed in and returned as clones, and the socket address of each family. print("shapes \(Shape.ALL) greetings \(GREETINGS)") + print("both \(Shape.BOTH) primes \(PRIMES)") var trail = Trail.new([Point(x: 1, y: 2), Point(x: 3, y: 4)], ["a", "b"]) print("trail \(trail.points()) \(trail.labels())") // Returned iterators, each collected at the call: drained labels are gone after. From 6fb51a691e51e292e090972cf188c174dfeef4d6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:15:07 -0800 Subject: [PATCH 03/11] wip: revert stray fmt --- ffi/src/dart.rs | 105 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 77 insertions(+), 28 deletions(-) diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 41c5e3d03..1eb2014f8 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -613,10 +613,12 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 | Ty::Duration + | Ty::U128 + | Ty::Duration | Ty::SocketAddr | Ty::Struct(_) - | Ty::Waker | Ty::ForeignFuture + | Ty::Waker + | Ty::ForeignFuture | Ty::ForeignReader ) } @@ -681,6 +683,15 @@ impl<'a> Gen<'a> { fields.push((format!("_{n}"), abi.ty(element))); } } else if let Some(i) = (0..abi.api.records.len()).find(|&i| abi.record(i) == name) { + if let Some(opaque) = &abi.api.records[i].opaque { + let code = format!( + "final class {class} extends ffi.Struct {{\n\t@ffi.Array({})\n\texternal ffi.Array $opaque;\n}}\n\n", + opaque.units(), + opaque.unit() * 8 + ); + self.structs.insert(name, code); + return class; + } for field in &abi.api.records[i].fields { fields.push((abi::escape(&field.name), abi.ty(&field.ty))); } @@ -969,6 +980,11 @@ impl<'a> Gen<'a> { let dt = self.dt(ty); let abi = self.abi; let body = match ty { + Type::Record(i) if abi.api.records[*i].opaque.is_some() => { + let units = abi.api.records[*i].opaque.as_ref().map_or(0, |o| o.units()); + let lines: Vec = (0..units).map(|k| format!("c.$opaque[{k}] = v._{k};")).collect(); + lines.join("\n\t") + } Type::Record(i) => { let record = &abi.api.records[*i]; let mut lines = Vec::new(); @@ -1086,6 +1102,12 @@ impl<'a> Gen<'a> { let abi = self.abi; let dt = self.dt(ty); let (param, body) = match ty { + Type::Record(i) if abi.api.records[*i].opaque.is_some() => { + let class = self.struct_class(&Ty::Struct(c.to_string())); + let units = abi.api.records[*i].opaque.as_ref().map_or(0, |o| o.units()); + let words: Vec = (0..units).map(|k| format!("c.$opaque[{k}]")).collect(); + (class, format!("{dt}._({})", words.join(", "))) + } Type::Record(i) => { let class = self.struct_class(&Ty::Struct(c.to_string())); let record = &abi.api.records[*i]; @@ -1481,6 +1503,30 @@ impl<'a> Gen<'a> { let name = self.class(&c); let rust = abi.api.rust(&record.path, &record.args); let ty = Type::Record(i); + if let Some(opaque) = &record.opaque { + // Its bytes, in the units of its C struct, each an `int` of the same bits. + let units: Vec = (0..opaque.units()).map(|k| format!("_{k}")).collect(); + let mut members = Vec::new(); + let mut body = vec![format!( + "\tconst {name}._({});\n\n{}", + units.iter().map(|u| format!("this.{u}")).collect::>().join(", "), + units.iter().map(|u| format!("\tfinal int {u};\n")).collect::() + )]; + self.traits(&ty, &c, record.traits, &mut body, &mut members); + self.methods(&record.methods, &Ty::Struct(c.clone()), &ty, &mut body, &mut members); + self.check_members(&rust, &mut members); + let text = format!( + "{rust}\n\nIts bytes, which only Rust makes or reads: copy it, but never make one.\n\n{}", + record.docs + ); + let _ = write!( + self.types, + "{}final class {name} {{\n{}}}\n\n", + docs(text.trim(), ""), + body.join("\n") + ); + return; + } let fields: Vec<(String, String)> = (record.fields.iter()) .map(|f| (field_name(&f.name), self.dt(&f.ty))) .collect(); @@ -1832,11 +1878,7 @@ impl<'a> Gen<'a> { let mut lends = Vec::new(); for (n, ty) in closure.params.iter().enumerate() { match ty { - // An object, by reference or a `Copy` one by value, lent for the call. - Type::Object(_) => { - lends.push(format!("{}._lent(p{n})", self.dt(ty))); - args.push(format!("l{}", lends.len() - 1)); - } + // An object, by reference, lent for the call. Type::Ref(_, object) if matches!(**object, Type::Object(_)) => { lends.push(format!("{}._lent(p{n})", self.dt(object))); args.push(format!("l{}", lends.len() - 1)); @@ -1861,9 +1903,10 @@ impl<'a> Gen<'a> { Type::Unit => format!("{call};"), ok => { let value = self.returned(ok, "r_"); - let write = match Self::scalar(&abi.ty(ok)) { - true => format!("p{at}.value = {value};"), - false => format!("_n.setBuf(p{at}, {value});"), + let write = match abi.ty(ok) { + c if Self::scalar(&c) => format!("p{at}.value = {value};"), + Ty::Buf => format!("_n.setBuf(p{at}, {value});"), + _ => format!("p{at}.ref = {value};"), }; format!("final r_ = {call};\n\t{write}") } @@ -1884,24 +1927,25 @@ impl<'a> Gen<'a> { } /// The C value of the Dart value `e` of type `ty` a closure returns, which Rust then - /// owns: text as a buffer `buf_copy` made, and a `Copy` object as a new handle to a - /// copy, made without its `Clone`, which Rust copies out and frees. + /// owns: text as a buffer `buf_copy` made, and a value as a struct it writes. fn returned(&mut self, ty: &Type, e: &str) -> String { - let abi = self.abi; match ty { Type::String => format!("_n.copied({e})"), - Type::Object(i) => { - let c = abi.object(*i); - let handle = Ty::Handle { - name: c.clone(), - constant: true, - }; - let clone = self.served_fn(&format!("{c}_copy"), vec![handle.clone()], handle); - format!("_n.handOver({e}, {clone})") - } - Type::Option(inner) if matches!(**inner, Type::Object(_)) => { - let given = self.returned(inner, "v"); - format!("switch ({e}) {{ final v? => {given}, null => ffi.nullptr }}") + Type::Record(_) | Type::Option(_) => { + let c = self.c_name(ty); + let name = format!("_ret_{c}"); + if !self.helpers.contains_key(&name) { + let class = self.struct_class(&Ty::Struct(c.clone())); + let w = self.writer(&c, ty); + let dt = self.dt(ty); + self.helpers.insert( + name.clone(), + format!( + "{class} {name}({dt} v) {{\n\tfinal a_ = _Arena();\n\ttry {{\n\t\tfinal c = ffi.Struct.create<{class}>();\n\t\t{w}(v, c, a_, true);\n\t\treturn c;\n\t}} finally {{\n\t\ta_.end();\n\t}}\n}}\n\n" + ), + ); + } + format!("{name}({e})") } ty => self.lower(ty, e), } @@ -2288,10 +2332,15 @@ impl<'a> Gen<'a> { } // A function of a type returning it is a constructor, which, unlike a static // member, may share its name with an instance member, as a Rust function may - // with a field. An object's `new` is its unnamed one, which a record's fields - // take. + // with a field. An object's or opaque value's `new` is its unnamed one, which a + // record's fields take. _ if is_static && !function.future && Some(&ok) == owner_ty => { - if snake == "new" && matches!(owner_ty, Some(Type::Object(_))) { + let unnamed = match owner_ty { + Some(Type::Object(_)) => true, + Some(Type::Record(i)) => self.abi.api.records[*i].opaque.is_some(), + _ => false, + }; + if snake == "new" && unnamed { (format!("factory {ret_type}({})", params.join(", ")), "new ".to_string()) } else { ( From 1d1687b5f688087a067c747086efb1515cd9f83b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:15:28 -0800 Subject: [PATCH 04/11] wip: restore dart.rs from base --- ffi/src/dart.rs | 99 +++++++++++++------------------------------------ 1 file changed, 26 insertions(+), 73 deletions(-) diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 1eb2014f8..922cfefb2 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -683,15 +683,6 @@ impl<'a> Gen<'a> { fields.push((format!("_{n}"), abi.ty(element))); } } else if let Some(i) = (0..abi.api.records.len()).find(|&i| abi.record(i) == name) { - if let Some(opaque) = &abi.api.records[i].opaque { - let code = format!( - "final class {class} extends ffi.Struct {{\n\t@ffi.Array({})\n\texternal ffi.Array $opaque;\n}}\n\n", - opaque.units(), - opaque.unit() * 8 - ); - self.structs.insert(name, code); - return class; - } for field in &abi.api.records[i].fields { fields.push((abi::escape(&field.name), abi.ty(&field.ty))); } @@ -980,11 +971,6 @@ impl<'a> Gen<'a> { let dt = self.dt(ty); let abi = self.abi; let body = match ty { - Type::Record(i) if abi.api.records[*i].opaque.is_some() => { - let units = abi.api.records[*i].opaque.as_ref().map_or(0, |o| o.units()); - let lines: Vec = (0..units).map(|k| format!("c.$opaque[{k}] = v._{k};")).collect(); - lines.join("\n\t") - } Type::Record(i) => { let record = &abi.api.records[*i]; let mut lines = Vec::new(); @@ -1102,12 +1088,6 @@ impl<'a> Gen<'a> { let abi = self.abi; let dt = self.dt(ty); let (param, body) = match ty { - Type::Record(i) if abi.api.records[*i].opaque.is_some() => { - let class = self.struct_class(&Ty::Struct(c.to_string())); - let units = abi.api.records[*i].opaque.as_ref().map_or(0, |o| o.units()); - let words: Vec = (0..units).map(|k| format!("c.$opaque[{k}]")).collect(); - (class, format!("{dt}._({})", words.join(", "))) - } Type::Record(i) => { let class = self.struct_class(&Ty::Struct(c.to_string())); let record = &abi.api.records[*i]; @@ -1503,30 +1483,6 @@ impl<'a> Gen<'a> { let name = self.class(&c); let rust = abi.api.rust(&record.path, &record.args); let ty = Type::Record(i); - if let Some(opaque) = &record.opaque { - // Its bytes, in the units of its C struct, each an `int` of the same bits. - let units: Vec = (0..opaque.units()).map(|k| format!("_{k}")).collect(); - let mut members = Vec::new(); - let mut body = vec![format!( - "\tconst {name}._({});\n\n{}", - units.iter().map(|u| format!("this.{u}")).collect::>().join(", "), - units.iter().map(|u| format!("\tfinal int {u};\n")).collect::() - )]; - self.traits(&ty, &c, record.traits, &mut body, &mut members); - self.methods(&record.methods, &Ty::Struct(c.clone()), &ty, &mut body, &mut members); - self.check_members(&rust, &mut members); - let text = format!( - "{rust}\n\nIts bytes, which only Rust makes or reads: copy it, but never make one.\n\n{}", - record.docs - ); - let _ = write!( - self.types, - "{}final class {name} {{\n{}}}\n\n", - docs(text.trim(), ""), - body.join("\n") - ); - return; - } let fields: Vec<(String, String)> = (record.fields.iter()) .map(|f| (field_name(&f.name), self.dt(&f.ty))) .collect(); @@ -1878,7 +1834,11 @@ impl<'a> Gen<'a> { let mut lends = Vec::new(); for (n, ty) in closure.params.iter().enumerate() { match ty { - // An object, by reference, lent for the call. + // An object, by reference or a `Copy` one by value, lent for the call. + Type::Object(_) => { + lends.push(format!("{}._lent(p{n})", self.dt(ty))); + args.push(format!("l{}", lends.len() - 1)); + } Type::Ref(_, object) if matches!(**object, Type::Object(_)) => { lends.push(format!("{}._lent(p{n})", self.dt(object))); args.push(format!("l{}", lends.len() - 1)); @@ -1903,10 +1863,9 @@ impl<'a> Gen<'a> { Type::Unit => format!("{call};"), ok => { let value = self.returned(ok, "r_"); - let write = match abi.ty(ok) { - c if Self::scalar(&c) => format!("p{at}.value = {value};"), - Ty::Buf => format!("_n.setBuf(p{at}, {value});"), - _ => format!("p{at}.ref = {value};"), + let write = match Self::scalar(&abi.ty(ok)) { + true => format!("p{at}.value = {value};"), + false => format!("_n.setBuf(p{at}, {value});"), }; format!("final r_ = {call};\n\t{write}") } @@ -1927,25 +1886,24 @@ impl<'a> Gen<'a> { } /// The C value of the Dart value `e` of type `ty` a closure returns, which Rust then - /// owns: text as a buffer `buf_copy` made, and a value as a struct it writes. + /// owns: text as a buffer `buf_copy` made, and a `Copy` object as a new handle to a + /// copy, made without its `Clone`, which Rust copies out and frees. fn returned(&mut self, ty: &Type, e: &str) -> String { + let abi = self.abi; match ty { Type::String => format!("_n.copied({e})"), - Type::Record(_) | Type::Option(_) => { - let c = self.c_name(ty); - let name = format!("_ret_{c}"); - if !self.helpers.contains_key(&name) { - let class = self.struct_class(&Ty::Struct(c.clone())); - let w = self.writer(&c, ty); - let dt = self.dt(ty); - self.helpers.insert( - name.clone(), - format!( - "{class} {name}({dt} v) {{\n\tfinal a_ = _Arena();\n\ttry {{\n\t\tfinal c = ffi.Struct.create<{class}>();\n\t\t{w}(v, c, a_, true);\n\t\treturn c;\n\t}} finally {{\n\t\ta_.end();\n\t}}\n}}\n\n" - ), - ); - } - format!("{name}({e})") + Type::Object(i) => { + let c = abi.object(*i); + let handle = Ty::Handle { + name: c.clone(), + constant: true, + }; + let clone = self.served_fn(&format!("{c}_copy"), vec![handle.clone()], handle); + format!("_n.handOver({e}, {clone})") + } + Type::Option(inner) if matches!(**inner, Type::Object(_)) => { + let given = self.returned(inner, "v"); + format!("switch ({e}) {{ final v? => {given}, null => ffi.nullptr }}") } ty => self.lower(ty, e), } @@ -2332,15 +2290,10 @@ impl<'a> Gen<'a> { } // A function of a type returning it is a constructor, which, unlike a static // member, may share its name with an instance member, as a Rust function may - // with a field. An object's or opaque value's `new` is its unnamed one, which a - // record's fields take. + // with a field. An object's `new` is its unnamed one, which a record's fields + // take. _ if is_static && !function.future && Some(&ok) == owner_ty => { - let unnamed = match owner_ty { - Some(Type::Object(_)) => true, - Some(Type::Record(i)) => self.abi.api.records[*i].opaque.is_some(), - _ => false, - }; - if snake == "new" && unnamed { + if snake == "new" && matches!(owner_ty, Some(Type::Object(_))) { (format!("factory {ret_type}({})", params.join(", ")), "new ".to_string()) } else { ( From fa078d06d2e4c6899441961fd94f910731c003bf Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:32:36 -0800 Subject: [PATCH 05/11] feat(ffi): export what moq's excludes hide at main Trait-object and std opaque handles, iterator parameters, a lent Option field, array returns, interned 'static bytes, and type parameters no type C holds meets left out. Removes the excludes that now export; IpAddr splits into its own quest and accept_with joins not-send. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 19 +- ffi/fixtures/api/examples/transcript.rs | 11 +- ffi/fixtures/reject/expected.txt | 272 ++++++++++++------------ ffi/fixtures/reject/src/lib.rs | 15 +- ffi/moq/ffi.toml | 12 +- ffi/src/collect.rs | 37 ++-- ffi/tests/fixtures.rs | 2 + quest/m1/ffi-export/not-send.md | 5 +- quest/m1/ffi-refusals/README.md | 4 +- quest/m1/ffi-refusals/ip-addr.md | 28 +++ quest/m1/ffi-refusals/moq-excluded.md | 58 ----- quest/m1/ffi-refusals/no-config.md | 2 +- 12 files changed, 232 insertions(+), 233 deletions(-) create mode 100644 quest/m1/ffi-refusals/ip-addr.md delete mode 100644 quest/m1/ffi-refusals/moq-excluded.md diff --git a/ffi/README.md b/ffi/README.md index 45c782460..992ffb3f6 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -111,14 +111,15 @@ public path names, or an error taken by value, is held by value as an opaque han | `bool`, integers but 128-bit, floats, `char` | `bool`, `` types, `float`, `double`, a `uint32_t` code point | | `u128` | `_u128`: its low and high 64 bits | | `NonZero` of an integer but 128-bit | `T`, in every binding too; a zero passed in aborts, and `Option>` is `T`'s option | -| `[u8; N]` | `_array_u8_`: a struct of its `N` bytes, `items`, copied across; an empty one, or one of any other element, is refused | +| `[u8; N]` | `_array_u8_`: a struct of its `N` bytes, `items`, copied across; an empty one is refused | +| `[T; N]` of any other `T`, returned or a constant's value | `Vec` of its `N` items; taken, it is refused | | `&str`, `String`, `&[u8]`, `Vec`, `bytes::Bytes` | `_buf`: an owned buffer returned; passed in, a view, or a buffer Rust returned, which Rust takes back without a copy unless it sits behind a pointer or in an array; `_buf_clone` shares one the caller keeps, which a `Vec`, `String`, or `PathBuf` parameter then copies, since only a sole owner's allocation becomes a `Vec` | | `&Path`, `PathBuf` | `_buf` of the path's bytes as the OS holds them on Unix, which need not be UTF-8, else UTF-8 | | `Duration` | `_duration` | | `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` | `_socket_addr`: its IP's bytes, port, and whether it is IPv6; one of the other family passed to `V4` or `V6` aborts | | `url::Url` | an object `_Url`, made by `_Url_parse`, which fails with the parse error's message, and printed by `_to_string` | -| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | -| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | +| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc`, or `Arc` and `&'static dyn Trait` of another crate's trait without generic arguments, `Send` and `Sync`, as rustls's `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | +| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names, or a standard library type no other rule maps, such as `io::Error`, named by its full path, `_std_io_Error` | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | | `std::time::Instant` | an object `_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq`, with none of its methods | | `tracing::Level` | `_Level`: a C enum of its five levels, `TRACE` to `ERROR` | | `tracing::level_filters::LevelFilter` | `Option`, whose `None` is `OFF` | @@ -138,6 +139,7 @@ public path names, or an error taken by value, is held by value as an opaque han | `impl Into`, where `X` does not map | what a `From` implementation into `X` takes: a source parameter by its bounds as above, so `impl> From for Timed` takes `Bytes`, and by each `Into` whose `Y` does not map, what converts into `Y` in turn, each `Y` once and refusing a chain longer than the crate's recursion limit; any other source as it is, so `impl<'a, V> From<&'a V> for Timed<&'a V>` takes `&V`. Two sources C passes as one buffer, such as `String` and `Vec`, are refused, unless they are forms of one value, as `&str` and `String` are | | `impl IntoIterator`, where `X` is no type parameter | `Vec`, or `&[Y]` where `X` is `&Y` | | `impl io::Read`, not bounded by `Seek` | `&[u8]` | +| `impl Iterator` taken | `Vec`, whose items Rust iterates; for `X` of `&str` or `&[u8]`, an array of buffers C lends for the call; an iterator of other references, or one a future or a callback takes, is refused | | another type parameter | `serde_json::Value` for a serde `Serialize` or `Deserialize` bound, else the first of `String`, `Bytes`, and `Vec` meeting its bounds, or a foreign implementation of its one exported trait; else an instance of the function at each type the exports implement a trait bounding it for, through a blanket impl at each type implementing what the impl requires, as `&X` where that meets its bounds too and no bound, its own or one a supertrait implies, makes it outlive the call, so C keeps its handle, and, as an argument of a generic type, at each argument of an instance that meets its bounds and makes each generic type the signature names an instance | | a const parameter of a function | an instance of the function at each value an instance of a generic type the signature passes it to has there, where each generic type the signature then names is an instance | | a const argument | a `bool` or an integer below 128 bits; any other is refused | @@ -157,11 +159,11 @@ A record or enum holds only values and `Copy` handles: one with a field that doe or that holds itself, is an object instead, and the census lists it. A borrowed return is returned as a clone, so it must be `Clone`, and a handle in it is a new handle to the clone, but for an object a `&self` method of an object returns borrowed from its receiver -alone, or an object's `pub` field holds: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it +alone, or an object's `pub` field holds, bare or as an `Option`'s `Some`: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it on each use, on one thread at a time where the receiver is not `Sync`. A handle outlives every call, so every lifetime an object takes is `'static`, as is every lifetime that must outlive one; any other lifetime is the call's. A signature may not lend C's borrow for one that is `'static`, but for a -`&str`, which Rust interns, nor return an object that borrows. A parameter is a reference +`&str` or `&[u8]`, which Rust interns, nor return an object that borrows. A parameter is a reference only at its top or as `Some` of an `Option`, lent as the reference alone is, so `Option<&T>` is a null or borrowed handle, a null or viewed buffer, or an option of a value, and not inside a `Box` or any other type. A `&mut` of a value, but a `str` or a @@ -169,7 +171,8 @@ slice, is in and out, and not inside an `Option`, a callback, or a future, nor b by what the call returns; a `&mut` of another crate's `Arc` is refused. Only a bare returned `&Object` is lent, never one inside what a call returns nor its error. What C could never hold, an object no export C can call returns or lends to a closure, a generic type no export -instantiates, and whatever takes one, is left out and listed in the census. Everything +instantiates, a type parameter bounded by another crate's trait no type C holds implements, +and whatever takes one, is left out and listed in the census. Everything else is refused, and the census counts why. ## Targets @@ -271,8 +274,8 @@ where it was while its file is unchanged. shared and aborts, naming the function, once it was since borrowed exclusively, moved out, or freed, which Rust's borrow checker would refuse. Borrowing a lent handle exclusively aborts too, as Rust lent it shared. -- **Interned strings**: a `&str` a function needs for `'static`, as `Path::from_static` - does, is leaked once per distinct content and reused for every later equal one, so a +- **Interned strings**: a `&str` or `&[u8]` a function needs for `'static`, as + `Path::from_static` and `CertificateDer::from_slice` do, is leaked once per distinct content and reused for every later equal one, so a caller passing ever-new strings grows the set without bound. - **Arrays** of a `Vec` are a pointer, a length, and an owner, as a buffer is: passed in, Rust copies each element out of C's array, or for a slice of a fixed-width integer diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 53a9d7358..6d2b6ace8 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -622,14 +622,21 @@ fn main() { println!("codecs reversed {}", codecs.ids()); // A standard library value no type maps, in a handle. let failure = api::failure("boom"); - println!("failure {} {}", api::failure_message(&failure), api::failure_kind(failure)); + println!( + "failure {} {}", + api::failure_message(&failure), + api::failure_kind(failure) + ); // Iterators, passed as the arrays of their items. println!("sum_all {}", api::sum_all(vec![1u32, 2, 3].into_iter())); println!("offered_len {}", api::offered_len([&b"h3"[..], b"moq-00"].into_iter())); println!("join_words {}", api::join_words(["a", "b", "c"])); // Bytes that must be `'static`, interned. println!("der {}", String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes())); - println!("der again {}", String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes())); + println!( + "der again {}", + String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes()) + ); let session = api::resume("h3", 60).unwrap(); println!("resume {} {}", session.alpn(), session.lifetime().seconds); println!("resume err {}", api::resume("", 60).err().unwrap()); diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 9ba588290..0e0da68bb 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -1,147 +1,149 @@ -fixtures/reject/src/lib.rs:1002:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1008:1: rust2-ffi: cannot export fn `poll_risky`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1024:1: rust2-ffi: cannot export fn `poll_loose`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1031:1: rust2-ffi: cannot export fn `among`: 3 optional borrowed objects, past the 2 Swift takes, which overloads each with and without it since its optional holds an object only by consuming it; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1037:1: rust2-ffi: cannot export fn `wrapped`: error holding an object Swift cannot copy, as `Swift.Error` requires; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1042:1: rust2-ffi: cannot export fn `sum_pair`: array of an element other than u8 `[u16; 2]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1047:1: rust2-ffi: cannot export fn `empty`: empty array `[u8; 0]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1053:1: rust2-ffi: cannot export enum `Wide`: discriminant outside `i32` `Large = 1099511627776`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1055:2: note: has this discriminant -fixtures/reject/src/lib.rs:105:1: rust2-ffi: cannot export fn `forever`: 'static borrow `&'static [u8]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1060:1: rust2-ffi: cannot export enum `Huge`: discriminant outside `i32` `Large = 18446744073709551616`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1062:2: note: has this discriminant -fixtures/reject/src/lib.rs:1067:1: rust2-ffi: cannot export enum `Top`: discriminant outside `i32` `Large = 340282366920938463463374607431768211455`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1069:2: note: has this discriminant -fixtures/reject/src/lib.rs:1073:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1078:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1084:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1098:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1104:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1109:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1114:1: rust2-ffi: cannot export fn `trust`: trait object `dyn Trusted`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1104:1: note: C cannot implement `Trusted`: unsafe trait -fixtures/reject/src/lib.rs:1119:1: rust2-ffi: cannot export fn `hazard`: trait object `dyn Hazard`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1109:1: note: C cannot implement `Hazard`: unsafe fn `risk` -fixtures/reject/src/lib.rs:111:1: rust2-ffi: cannot export fn `boxed`: reference inside a parameter `std::boxed::Box<&str>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1124:1: rust2-ffi: cannot export fn `wide_non_zero`: NonZero `u128`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1129:1: rust2-ffi: cannot export fn `hidden_answer`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1134:1: rust2-ffi: cannot export fn `hidden_items`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1139: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:1144: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:1003:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1009:1: rust2-ffi: cannot export fn `poll_risky`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1025:1: rust2-ffi: cannot export fn `poll_loose`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1032:1: rust2-ffi: cannot export fn `among`: 3 optional borrowed objects, past the 2 Swift takes, which overloads each with and without it since its optional holds an object only by consuming it; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1038:1: rust2-ffi: cannot export fn `wrapped`: error holding an object Swift cannot copy, as `Swift.Error` requires; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1043:1: rust2-ffi: cannot export fn `sum_pair`: array of an element other than u8 `[u16; 2]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1048:1: rust2-ffi: cannot export fn `empty`: empty array `[u8; 0]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1054:1: rust2-ffi: cannot export enum `Wide`: discriminant outside `i32` `Large = 1099511627776`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1056:2: note: has this discriminant +fixtures/reject/src/lib.rs:1061:1: rust2-ffi: cannot export enum `Huge`: discriminant outside `i32` `Large = 18446744073709551616`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1063:2: note: has this discriminant +fixtures/reject/src/lib.rs:1068:1: rust2-ffi: cannot export enum `Top`: discriminant outside `i32` `Large = 340282366920938463463374607431768211455`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1070:2: note: has this discriminant +fixtures/reject/src/lib.rs:106:1: rust2-ffi: cannot export fn `forever_mut`: 'static borrow `&'static mut [u8]`; &mut of a slice `[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1074:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1079:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1085:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1099:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1105:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1110:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1115:1: rust2-ffi: cannot export fn `trust`: trait object `dyn Trusted`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1105:1: note: C cannot implement `Trusted`: unsafe trait +fixtures/reject/src/lib.rs:1120:1: rust2-ffi: cannot export fn `hazard`: trait object `dyn Hazard`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1110:1: note: C cannot implement `Hazard`: unsafe fn `risk` +fixtures/reject/src/lib.rs:1125:1: rust2-ffi: cannot export fn `wide_non_zero`: NonZero `u128`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:112:1: rust2-ffi: cannot export fn `boxed`: reference inside a parameter `std::boxed::Box<&str>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1130:1: rust2-ffi: cannot export fn `hidden_answer`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1135:1: rust2-ffi: cannot export fn `hidden_items`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1140: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:1145: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:1150:1: rust2-ffi: cannot export fn `count_later`: iterator of borrows in a future or callback; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1155:1: rust2-ffi: cannot export fn `count_opaques`: generic parameter `std::iter::Iterator`; 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: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 +fixtures/reject/src/lib.rs:123: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:137: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:154: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 fixtures/reject/src/lib.rs:16:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `measure`: foreign type `tls::held::Local`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:178:1: rust2-ffi: cannot export fn `sealed`: refused type `reject::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:184:1: rust2-ffi: cannot export fn `echo`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:189:1: rust2-ffi: cannot export fn `blame`: borrowing output of a future from a function that is not async `std::result::Result>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:194:1: rust2-ffi: cannot export fn `relay`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:199:1: rust2-ffi: cannot export fn `resolve`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:204:1: rust2-ffi: cannot export fn `spend`: closure signature `tls::held::Token`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:209:1: rust2-ffi: cannot export fn `mint`: closure signature `tls::held::Token`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:219:1: rust2-ffi: cannot export fn `spent`: reference to a handle inside a value `[tls::held::Token]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:171:1: rust2-ffi: cannot export fn `measure`: foreign type `tls::held::Local`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:176:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:176:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:179:1: rust2-ffi: cannot export fn `sealed`: refused type `reject::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:185:1: rust2-ffi: cannot export fn `echo`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:190:1: rust2-ffi: cannot export fn `blame`: borrowing output of a future from a function that is not async `std::result::Result>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:195:1: rust2-ffi: cannot export fn `relay`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:200:1: rust2-ffi: cannot export fn `resolve`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:205:1: rust2-ffi: cannot export fn `spend`: closure signature `tls::held::Token`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:210:1: rust2-ffi: cannot export fn `mint`: closure signature `tls::held::Token`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:21:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `adopt`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:241:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:260:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject::Ping>>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:271:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:274:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject::Grow<(u32,)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:285:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:294:1: rust2-ffi: cannot export fn `shell`: refused type `reject::Shell<(u32,)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:305:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:220:1: rust2-ffi: cannot export fn `spent`: reference to a handle inside a value `[tls::held::Token]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:230:1: rust2-ffi: cannot export fn `adopt`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:242:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:261:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject::Ping>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:272:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:275:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject::Grow<(u32,)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:286:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:295:1: rust2-ffi: cannot export fn `shell`: refused type `reject::Shell<(u32,)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:306:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:30:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:310:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:315:1: rust2-ffi: cannot export fn `listed`: refused type `reject::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:320:1: rust2-ffi: cannot export instance `Fixed<'a'>`: const argument `'a'`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:323:1: rust2-ffi: cannot export fn `fixed`: refused type `reject::Fixed<'a'>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:328:9: rust2-ffi: cannot export use `HashSet`: re-export of the standard library's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:331:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter or a return; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:339:2: rust2-ffi: cannot export field `Tag::label`: 'static borrow `&'static str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:349:1: rust2-ffi: cannot export fn `gather`: closure signature `std::vec::Vec`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:354:1: rust2-ffi: cannot export fn `attempt`: closure signature `std::result::Result`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:359:1: rust2-ffi: cannot export fn `consume`: reader not lent as &mut `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:311:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:316:1: rust2-ffi: cannot export fn `listed`: refused type `reject::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:321:1: rust2-ffi: cannot export instance `Fixed<'a'>`: const argument `'a'`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:324:1: rust2-ffi: cannot export fn `fixed`: refused type `reject::Fixed<'a'>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:329:9: rust2-ffi: cannot export use `HashSet`: re-export of the standard library's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:332:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter or a return; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:340:2: rust2-ffi: cannot export field `Tag::label`: 'static borrow `&'static str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:350:1: rust2-ffi: cannot export fn `gather`: closure signature `std::vec::Vec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:355:1: rust2-ffi: cannot export fn `attempt`: closure signature `std::result::Result`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:35:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:364:1: rust2-ffi: cannot export fn `retain`: reader kept past the call `R`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:369:1: rust2-ffi: cannot export fn `rewrite`: reader bound `std::io::Write`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:374:1: rust2-ffi: cannot export fn `read_later`: reader kept past the call `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:379:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:385:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:391:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:396:1: rust2-ffi: cannot export fn `count_words`: Vec of references `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:360:1: rust2-ffi: cannot export fn `consume`: reader not lent as &mut `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:365:1: rust2-ffi: cannot export fn `retain`: reader kept past the call `R`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:370:1: rust2-ffi: cannot export fn `rewrite`: reader bound `std::io::Write`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:375:1: rust2-ffi: cannot export fn `read_later`: reader kept past the call `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:380:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:386:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:392:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:397:1: rust2-ffi: cannot export fn `count_words`: Vec of references `&str`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:39:1: rust2-ffi: cannot export macro `noop`: macro; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:401:1: rust2-ffi: cannot export fn `count_some`: Vec of references `std::option::Option<&str>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:406:1: rust2-ffi: cannot export fn `count_slice`: slice of references `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:411:1: rust2-ffi: cannot export fn `peek_all`: reference to a handle inside a value `[Opaque]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:416:1: rust2-ffi: cannot export fn `none_opaque`: borrowed return that is not Clone `[Opaque]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:428:1: rust2-ffi: cannot export fn `stash`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:443:1: rust2-ffi: cannot export fn `hold`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:448:1: rust2-ffi: cannot export fn `bound`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:453:1: rust2-ffi: cannot export fn `kept`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:467:1: rust2-ffi: cannot export fn `holder`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:402:1: rust2-ffi: cannot export fn `count_some`: Vec of references `std::option::Option<&str>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:407:1: rust2-ffi: cannot export fn `count_slice`: slice of references `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:412:1: rust2-ffi: cannot export fn `peek_all`: reference to a handle inside a value `[Opaque]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:417:1: rust2-ffi: cannot export fn `none_opaque`: borrowed return that is not Clone `[Opaque]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:429:1: rust2-ffi: cannot export fn `stash`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:444:1: rust2-ffi: cannot export fn `hold`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:449:1: rust2-ffi: cannot export fn `bound`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:454:1: rust2-ffi: cannot export fn `kept`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:468:1: rust2-ffi: cannot export fn `holder`: generic parameter `std::convert::Into`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:47:1: rust2-ffi: cannot export fn `excluded`: excluded type `Excluded`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:481:1: rust2-ffi: cannot export fn `lender`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:496:1: rust2-ffi: cannot export fn `outlived`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:511:1: rust2-ffi: cannot export fn `paired`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:482:1: rust2-ffi: cannot export fn `lender`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:497:1: rust2-ffi: cannot export fn `outlived`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:512:1: rust2-ffi: cannot export fn `paired`: generic parameter `std::convert::Into`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:52:1: rust2-ffi: cannot export fn `letters`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:534:1: rust2-ffi: cannot export fn `pinner`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:549:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:541:1: note: applies past the recursion limit -fixtures/reject/src/lib.rs:579:1: rust2-ffi: cannot export fn `call`: ambiguous conversion `std::vec::Vec`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:556:1: note: `std::string::String` converts too, which C passes alike -fixtures/reject/src/lib.rs:584:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:589:1: rust2-ffi: cannot export fn `naturals`: foreign type `std::ops::RangeFrom`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:594:1: rust2-ffi: cannot export fn `opaques`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:599:1: rust2-ffi: cannot export fn `tried`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:604:1: rust2-ffi: cannot export fn `eventually`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:630:1: rust2-ffi: cannot export fn `tallied`: unmet bound `u32: std::convert::From`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:635:1: rust2-ffi: cannot export fn `drain`: trait object `dyn Source`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:609:1: note: C cannot implement `Source`: callback signature `items` -fixtures/reject/src/lib.rs:640:1: rust2-ffi: cannot export fn `summed_forever`: 'static borrow `&'static [u32]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:645:1: rust2-ffi: cannot export fn `retext_last`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:645:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:652:1: rust2-ffi: cannot export fn `outlast`: 'static borrow `&'b [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:652:20: note: `'b` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:659:1: rust2-ffi: cannot export fn `retext_into`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:659:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:668:1: rust2-ffi: cannot export fn `ones`: foreign type `std::iter::Repeat`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:535:1: rust2-ffi: cannot export fn `pinner`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:550:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:542:1: note: applies past the recursion limit +fixtures/reject/src/lib.rs:580:1: rust2-ffi: cannot export fn `call`: ambiguous conversion `std::vec::Vec`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:557:1: note: `std::string::String` converts too, which C passes alike +fixtures/reject/src/lib.rs:585:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:590:1: rust2-ffi: cannot export fn `naturals`: foreign type `std::ops::RangeFrom`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:595:1: rust2-ffi: cannot export fn `opaques`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:600:1: rust2-ffi: cannot export fn `tried`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:605:1: rust2-ffi: cannot export fn `eventually`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:631:1: rust2-ffi: cannot export fn `tallied`: unmet bound `u32: std::convert::From`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:636:1: rust2-ffi: cannot export fn `drain`: trait object `dyn Source`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:610:1: note: C cannot implement `Source`: callback signature `items` +fixtures/reject/src/lib.rs:641:1: rust2-ffi: cannot export fn `summed_forever`: 'static borrow `&'static [u32]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:646:1: rust2-ffi: cannot export fn `retext_last`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:646:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:653:1: rust2-ffi: cannot export fn `outlast`: 'static borrow `&'b [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:653:20: note: `'b` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:660:1: rust2-ffi: cannot export fn `retext_into`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:660:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:669:1: rust2-ffi: cannot export fn `ones`: foreign type `std::iter::Repeat`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:66:2: rust2-ffi: cannot export method `Text::view`: returned object that borrows `Text<'_>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:674:1: rust2-ffi: cannot export fn `long_words`: foreign type `std::iter::Filter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:680:1: rust2-ffi: cannot export fn `kept_in`: foreign type `std::iter::Filter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:697:1: rust2-ffi: cannot export fn `launched`: foreign type `std::iter::Chain`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:675:1: rust2-ffi: cannot export fn `long_words`: foreign type `std::iter::Filter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:681:1: rust2-ffi: cannot export fn `kept_in`: foreign type `std::iter::Filter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:698:1: rust2-ffi: cannot export fn `launched`: foreign type `std::iter::Chain`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:6:1: rust2-ffi: cannot export fn `pair`: tuple of references `(&str, u8)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:714:1: rust2-ffi: cannot export fn `launches`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:737:1: rust2-ffi: cannot export fn `pumped`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:751:1: rust2-ffi: cannot export fn `skipped`: foreign type `std::iter::Skip`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:756:1: rust2-ffi: cannot export fn `merged`: foreign type `std::iter::Copied`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:763:1: rust2-ffi: cannot export fn `values`: foreign type `std::collections::btree_map::IntoValues`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:769:1: rust2-ffi: cannot export fn `floats`: collection not built from its items `std::collections::BTreeSet`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:774:1: rust2-ffi: cannot export fn `zeros`: foreign type `std::iter::RepeatN`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:779:1: rust2-ffi: cannot export fn `successes`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:715:1: rust2-ffi: cannot export fn `launches`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:738:1: rust2-ffi: cannot export fn `pumped`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:752:1: rust2-ffi: cannot export fn `skipped`: foreign type `std::iter::Skip`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:757:1: rust2-ffi: cannot export fn `merged`: foreign type `std::iter::Copied`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:764:1: rust2-ffi: cannot export fn `values`: foreign type `std::collections::btree_map::IntoValues`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:770:1: rust2-ffi: cannot export fn `floats`: collection not built from its items `std::collections::BTreeSet`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:775:1: rust2-ffi: cannot export fn `zeros`: foreign type `std::iter::RepeatN`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:77:1: rust2-ffi: cannot export fn `first`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:799:1: rust2-ffi: cannot export fn `allocated`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:806:1: rust2-ffi: cannot export fn `flattened`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:830:1: rust2-ffi: cannot export fn `lent`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:848:1: rust2-ffi: cannot export fn `halves`: foreign type `std::str::Split`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:853:1: rust2-ffi: cannot export fn `settled`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:858:1: rust2-ffi: cannot export fn `poll_named`: poll's parameter taken by value that is not Copy `std::string::String`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:864:1: rust2-ffi: cannot export fn `poll_first`: borrowed Poll `&u8`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:870:1: rust2-ffi: cannot export fn `poll_until`: poll's parameter taken by value that is not Copy `impl Fn(u8) -> bool`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:881:1: rust2-ffi: cannot export fn `context_later`: Context of a function returning a future; future not Send; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:900:1: rust2-ffi: cannot export fn `poll_ticket`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:905:1: rust2-ffi: cannot export fn `poll_both`: several task parameters; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:912:1: rust2-ffi: cannot export fn `poll_bump`: &mut of a value in a future; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:919:1: rust2-ffi: cannot export fn `peek_some`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:924:1: rust2-ffi: cannot export fn `bump_some`: &mut of a value inside an Option `std::option::Option<&mut u32>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:931:1: rust2-ffi: cannot export fn `rest`: returned borrow of a value written back `&[u8]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:936:1: rust2-ffi: cannot export fn `fill`: returned borrow of a value written back `impl std::future::Future`; &mut of a value in a future; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:941:1: rust2-ffi: cannot export fn `zero`: &mut of a slice `[u8]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:946:1: rust2-ffi: cannot export fn `reseat`: &mut of another crate's Arc `std::sync::Arc`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:959:2: rust2-ffi: cannot export method `Keeper::check`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:970:9: rust2-ffi: cannot export use `dep`: re-export of a whole crate `dep`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:973:9: rust2-ffi: cannot export use `renamed`: re-export of a whole crate `dep`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:984:2: rust2-ffi: cannot export method `Tally::poll_bump`: `&mut self` of a value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:780:1: rust2-ffi: cannot export fn `successes`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:800:1: rust2-ffi: cannot export fn `allocated`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:807:1: rust2-ffi: cannot export fn `flattened`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:831:1: rust2-ffi: cannot export fn `lent`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:849:1: rust2-ffi: cannot export fn `halves`: foreign type `std::str::Split`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:854:1: rust2-ffi: cannot export fn `settled`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:859:1: rust2-ffi: cannot export fn `poll_named`: poll's parameter taken by value that is not Copy `std::string::String`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:865:1: rust2-ffi: cannot export fn `poll_first`: borrowed Poll `&u8`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:871:1: rust2-ffi: cannot export fn `poll_until`: poll's parameter taken by value that is not Copy `impl Fn(u8) -> bool`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:882:1: rust2-ffi: cannot export fn `context_later`: Context of a function returning a future; future not Send; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:901:1: rust2-ffi: cannot export fn `poll_ticket`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:906:1: rust2-ffi: cannot export fn `poll_both`: several task parameters; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:913:1: rust2-ffi: cannot export fn `poll_bump`: &mut of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:920:1: rust2-ffi: cannot export fn `peek_some`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:925:1: rust2-ffi: cannot export fn `bump_some`: &mut of a value inside an Option `std::option::Option<&mut u32>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:932:1: rust2-ffi: cannot export fn `rest`: returned borrow of a value written back `&[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:937:1: rust2-ffi: cannot export fn `fill`: returned borrow of a value written back `impl std::future::Future`; &mut of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:942:1: rust2-ffi: cannot export fn `zero`: &mut of a slice `[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:947:1: rust2-ffi: cannot export fn `reseat`: &mut of another crate's Arc `std::sync::Arc`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:960:2: rust2-ffi: cannot export method `Keeper::check`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:971:9: rust2-ffi: cannot export use `dep`: re-export of a whole crate `dep`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:974:9: rust2-ffi: cannot export use `renamed`: re-export of a whole crate `dep`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:985:2: rust2-ffi: cannot export method `Tally::poll_bump`: `&mut self` of a value; exclude it in the config to leave it out fixtures/reject/src/lib.rs:99:2: rust2-ffi: cannot export method `Text::later`: returned object that borrows `impl std::future::Future>`; 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 6e6b20a1b..80729bbaf 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -101,8 +101,9 @@ impl<'a> Text<'a> { } } -/// Bytes that must be `'static`, which only a string's interning makes them. -pub fn forever(bytes: &'static [u8]) -> usize { +/// Bytes lent mutably for as long as the program runs, which interning would alias: every +/// call with equal bytes would share one copy. +pub fn forever_mut(bytes: &'static mut [u8]) -> usize { bytes.len() } @@ -1144,3 +1145,13 @@ pub fn hidden_option() -> impl Clone { pub fn boxed_bytes(bytes: Box<[u8]>) -> usize { bytes.len() } + +/// An iterator of borrowed strings a future keeps past the call that lent them. +pub async fn count_later<'a>(words: impl Iterator + Send) -> usize { + words.count() +} + +/// An iterator of borrowed objects, which C lends none of inside an array. +pub fn count_opaques<'a>(items: impl Iterator) -> usize { + items.count() +} diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index 4f87d828e..783c59cfb 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -11,10 +11,8 @@ exclude = [ "hang::moq_net", "kio", "moq_quic::VarInt::from_u64_unchecked", - "moq_sock::demux::Discard::ALL", "moq_tokio::accept::Failure::classify", "moq_tokio::accept::Health::failed", - "moq_tokio::quic::Controller::0", "moq_tokio::quic::demux::Datagram::local", "moq_tokio::quic::driver::connection::Connection::congestion_state", "moq_tokio::quic::driver::connection::Connection::poll_closed", @@ -23,7 +21,7 @@ exclude = [ "moq_tokio::quic::driver::send::Options::group", "moq_tokio::quic::driver::send::Stream::write", "moq_tokio::tcp::TlsAcceptor::accept", - "moq_tokio::tcp::TlsAcceptor::offered", + "moq_tokio::websocket::Listener::accept", "mp4_atom::TrunSamples::iter", "mp4_atom::Tx3g::box_record", "mux::catalog::Guard", @@ -55,17 +53,9 @@ exclude = [ "mux::container::Producer::modify", "mux::container::Producer::modify", "mux::container::fmp4::mp4_atom", - "rustls::ClientConfig::cert_compressors", - "rustls::ClientConfig::cert_decompressors", - "rustls::ClientConfig::client_auth_cert_resolver", - "rustls::ClientConfig::key_log", - "rustls::ClientConfig::time_provider", "rustls::ConfigBuilder", "rustls::ConfigBuilder", "rustls::client::Resumption::store", - "rustls_pki_types::CertificateDer::from_slice", - "rustls_pki_types::Der::from_slice", - "tokio::server::Config::websocket", "tokio::server::Request::within", "tokio::tls::Serve::resolver", ] diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index aab78b5df..bd1b80570 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2305,7 +2305,8 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) + }) + || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if !used { self.api.enums.pop(); @@ -2329,8 +2330,9 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) || (api.objects.iter().enumerate()) - .any(|(i, o)| i != gone && (args(&o.args) || o.methods.iter().any(signature))) + }) + || (api.objects.iter().enumerate()) + .any(|(i, o)| i != gone && (args(&o.args) || o.methods.iter().any(signature))) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if used { continue; @@ -2910,7 +2912,8 @@ impl<'tcx> Collector<'tcx> { // is, takes it from the future, as it would a parameter. ty::Ref(_, inner, _) if Some(*inner) == self_ty - && polled.is_some() && let Some(kind) = self.task(ty, true) => + && polled.is_some() + && let Some(kind) = self.task(ty, true) => { tasks.push(Task { at: 0, kind }); None @@ -3974,7 +3977,8 @@ impl<'tcx> Collector<'tcx> { .inputs() .iter() .filter(|&&input| input == param) - .count() > 1 + .count() + > 1 { return Some(Err(why("closure type taken twice", param.to_string()))); } @@ -4327,11 +4331,16 @@ impl<'tcx> Collector<'tcx> { let plain = matches!( ty.kind(), ty::Adt(..) - | ty::Bool | ty::Char - | ty::Int(_) | ty::Uint(_) - | ty::Float(_) | ty::Str - | ty::Array(..) | ty::Slice(_) - | ty::Ref(..) | ty::Tuple(_) + | ty::Bool + | ty::Char + | ty::Int(_) + | ty::Uint(_) + | ty::Float(_) + | ty::Str + | ty::Array(..) + | ty::Slice(_) + | ty::Ref(..) + | ty::Tuple(_) ); let (method, driven) = match (implements(iterator, ty), implements(into_iterator, ty)) { (true, _) => (next, item), @@ -5082,12 +5091,12 @@ impl<'tcx> Collector<'tcx> { Type::List(c, Box::new(inner)) } else if Some(did) == self.bytes { Type::Bytes - } else if Some(did) == self.vec_iter { + } else if Some(did) == self.vec_iter + && pos == Pos::Param + && tcx.lang_items().global_alloc_ty() == args.type_at(1).ty_adt_def().map(|adt| adt.did()) + { // An `impl Iterator` parameter's, which C passes as the array of its items. A // borrowed string or bytes borrow what C lends for the call. - if pos != Pos::Param { - return Err(why("iterator outside a parameter", ty.to_string())); - } let elem = args.type_at(0); match elem.kind() { ty::Ref(_, inner, ty::Mutability::Not) if inner.is_str() => { diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index b49f615a2..021df6651 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2013,6 +2013,8 @@ fn relative_target() { "- `handover`: type C never holds `tls::held::Handoff`", "- `Unnamed`: generic type no export instantiates", "- `blame`: type C never holds `tls::held::Invalid`", + // A type parameter only another crate's trait bounds, which no export implements. + "- `pump`: bound no type C holds meets `tls::held::Stream`", // An exclude that names what exports, by its generic or instance path or as a field, // even where a method of the field's name is refused. "## Excluded by the config, though it exports", diff --git a/quest/m1/ffi-export/not-send.md b/quest/m1/ffi-export/not-send.md index 4ccccf05e..36b6563af 100644 --- a/quest/m1/ffi-export/not-send.md +++ b/quest/m1/ffi-export/not-send.md @@ -6,7 +6,10 @@ thread that made it: a call, poll, or drop from another thread never runs Rust code on that value there. Three of moq's own are refused for it at moq `ffcb7cd9`: `clock::Entered`, `clock::Rng`, and `catalog::Guard` -([#675](https://github.com/kixel-ai/rust2/pull/675)). Proven per language by a fixture +([#675](https://github.com/kixel-ai/rust2/pull/675)). At moq's `main` (`a11a584`, measured on 2026-11-14 in +[#802](https://github.com/kixel-ai/rust2/pull/802)), moq-tokio's `server::Listener::accept_with` +is a fourth: its future borrows `&self` of a `Listener` that is not `Sync`, through a +`FuturesUnordered` of boxed futures that are not, so the future is not `Send`. Proven per language by a fixture type holding an `Rc`, called, awaited, and dropped from a second thread. ## Plan diff --git a/quest/m1/ffi-refusals/README.md b/quest/m1/ffi-refusals/README.md index abd4153d9..15f9153be 100644 --- a/quest/m1/ffi-refusals/README.md +++ b/quest/m1/ffi-refusals/README.md @@ -79,7 +79,9 @@ Decided with the maintainer on 2026-11-12, in the quest audit: `NonZero`, which exports, the rest of the errors at moq's main (exported since by rules for another crate's value, a borrowing future of a function that is not `async`, and an object field that is not `Clone`), and - [what the excludes still hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md); + what the excludes still hide at moq's main, exported since but for + [`IpAddr`](/quest/m1/ffi-refusals/ip-addr.md) and `server::Listener::accept_with`, which + [not-send](/quest/m1/ffi-export/not-send.md) owns; `just ffi census` fails on an exclude that names what exports. The bump is then only the bump. The types refused for not being `Send` (`clock::Entered`, `clock::Rng`, `catalog::Guard`) clear with [not-send](/quest/m1/ffi-export/not-send.md). diff --git a/quest/m1/ffi-refusals/ip-addr.md b/quest/m1/ffi-refusals/ip-addr.md new file mode 100644 index 000000000..25a94b0a1 --- /dev/null +++ b/quest/m1/ffi-refusals/ip-addr.md @@ -0,0 +1,28 @@ +# [S] IpAddr crosses by family + +## Goal + +`std::net::IpAddr`, `Ipv4Addr`, and `Ipv6Addr` export in every binding, as `SocketAddr` +already does: its IP's bytes and whether it is IPv6, with no port. moq-tokio's +`quic::demux::Datagram::local` is the one item at moq's `main` (`a11a584`, measured on +2026-11-14 in [#802](https://github.com/kixel-ai/rust2/pull/802)) refused for it, and the +census lists no `IpAddr` refusal there. + +## Plan + +Decided with the maintainer on 2026-11-13, in +[moq-excluded](https://github.com/kixel-ai/rust2/pull/802)'s Plan: ✅ `IpAddr` crosses as +`SocketAddr` already does, by family. #802 split it out, since it is a new IR type +through the glue and all seven generators, apart from that quest's collector rules. + +- A new `_ip_addr` C struct of 16 bytes and an `is_v6` flag, `SocketAddr`'s + without the port, and each binding's own address type where it is exact, as each maps + `SocketAddr` today (Kotlin `InetAddress`, Python `ipaddress`, Swift, Go `netip.Addr`, + Dart `InternetAddress`, C++). Recommended: reuse each binding's `SocketAddr` mapping of + the IP for the address and drop the port, so one family check covers both. +- `Ipv4Addr` and `Ipv6Addr` cross as that struct too; one of the other family passed in + aborts, as `SocketAddrV4` does. +- Prove it in the api fixture's transcript in all seven languages, both families, in and + out. + +Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/moq-excluded.md b/quest/m1/ffi-refusals/moq-excluded.md deleted file mode 100644 index 1e3a4267b..000000000 --- a/quest/m1/ffi-refusals/moq-excluded.md +++ /dev/null @@ -1,58 +0,0 @@ -# [M] What the excludes hide at moq's main - -## Goal - -Each construct `just ffi census ` still refuses at moq's `main` behind an -exclude in `ffi/moq/ffi.toml` exports by a rule, or is left out as what C can never hold, -beyond `NonZero`, which exports, and the types -[not-send](/quest/m1/ffi-export/not-send.md) exports. Measured on 2026-11-13 at moq -`98e54e7`, with #721's reach of other crates' types and the rules for another crate's -value, a non-`async` function's borrowing future, and a lent object field in place: 23 -items beyond not-send's, 13 of them in crates #721 newly reaches. - -## Plan - -[The epic](/quest/m1/ffi-refusals/README.md)'s decisions apply: rust2 asks moq for no -source change, and what C can never hold is left out and listed. Measure again first. - -The maintainer kept this quest on 2026-11-13 and accepted each recommendation below as its plan. - -- `std::io::Error` taken by value (`accept::Failure::classify`, `accept::Health::failed`) - and `std::net::IpAddr` (`quic::demux::Datagram::local`). Decided: `IpAddr` crosses - as `SocketAddr` already does, by family; `io::Error` as an opaque handle, as another - crate's value now is, with the standard library no longer exempt. -- Trait objects: `quic::Controller`'s `Arc` - field and `tls::Serve::resolver`'s `Arc`. - Decided: an opaque handle to the `Arc`, as another crate's `Arc` already is. -- Generic parameters: `server::Request::within` (`impl Future`), - `websocket::Listener::with_protocols` (`impl IntoIterator>`), - `tcp::TlsAcceptor::offered` (`impl Iterator`), and `tcp::TlsAcceptor::accept` (an IO - stream). Decided: `AsRef` items as strings and an `Iterator` parameter as the - array of its items, as returns already are; a foreign future as #705's is; the IO - stream left out as what C can never hold, since no export returns one. -- `server::Config::websocket`, a borrowed `Option` of a listener that is not `Clone`. - Decided: lent as `Some` of a handle, as a bare field now is. -- `server::Listener::accept_with`'s future is not `Send`. Left out today as what C can - never hold, since it takes a `qmux::Session` no export returns once the excludes go; - confirm the census lists it so. - -- Reached since #721 exports other crates' types with their API: rustls's - `ClientConfig` fields of `Arc` (5) and `client::Resumption::store`, under the - trait-object decision above. Four more constructs, decided by the maintainer on 2026-11-13: - - A `'static` borrow parameter (`CertificateDer::from_slice`, `Der::from_slice`): - ✅ exported by interning by content (rejected: left out and listed). The binding keeps - one process-wide table keyed by the bytes' contents; the first call with given bytes - copies them into a leaked Rust allocation, and later calls with equal bytes reuse it. - Never key by C's pointer, which C may free or reuse. The generated docs on such a - parameter say memory grows with each distinct value and is never freed. This is sound - for a shared `&'static [u8]`: the copy is immutable and never freed, and equal bytes - differ only by address. Refuse with a span any other `'static` borrow, such as a - `&'static mut` (interning would alias it) or a non-byte element type. - - `rustls::ConfigBuilder`, both by value and behind an `Arc`: - ✅ left out and listed (rejected: a handle everywhere). - - `qmux::Session::connect` and `accept`, bounded by qmux's `Transport`: ✅ left out and - listed (rejected: a callback interface). - - `moq_sock::demux::Discard::ALL` (`[Discard; 4]`): ✅ crosses as the `Vec` of its - elements, as a returned slice does (rejected: left out). - -Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/no-config.md b/quest/m1/ffi-refusals/no-config.md index c483171da..9b9653380 100644 --- a/quest/m1/ffi-refusals/no-config.md +++ b/quest/m1/ffi-refusals/no-config.md @@ -30,5 +30,5 @@ that passes them). ## Required - [The moq pin bump](/quest/m1/ffi-refusals/moq-pin.md) - the pin is at moq's `main`, where the census is taken -- [What the excludes hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md) - exports the constructs the census still refuses there behind an exclude +- [`IpAddr`](/quest/m1/ffi-refusals/ip-addr.md) - exports `quic::demux::Datagram::local`, the last item moq's main refuses beyond not-send's - [Not Send](/quest/m1/ffi-export/not-send.md) - exports the three types the census still refuses for not being `Send` From 46f915c8e43c78c63e5b19a415d422d031a7af6d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:51:20 -0800 Subject: [PATCH 06/11] fix(ffi): one trait-object form per trait, its lifetime held, and bounds an export meets refused Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 2 +- ffi/fixtures/reject/expected.txt | 3 +++ ffi/fixtures/reject/src/lib.rs | 25 +++++++++++++++++++ ffi/src/collect.rs | 42 +++++++++++++++++++++++++++++--- 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 97327629a..52c748116 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -119,7 +119,7 @@ public path names, or an error taken by value, is held by value as an opaque han | `Duration` | `_duration` | | `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` | `_socket_addr`: its IP's bytes, port, and whether it is IPv6; one of the other family passed to `V4` or `V6` aborts | | `url::Url` | an object `_Url`, made by `_Url_parse`, which fails with the parse error's message, and printed by `_to_string` | -| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc`, or `Arc` and `&'static dyn Trait` of another crate's trait without generic arguments, `Send` and `Sync`, as rustls's `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | +| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc`, or `Arc` and `&'static dyn Trait` of another crate's trait without generic arguments, whose auto traits are `Send` and `Sync` but those the trait implies, borrowing nothing C lends, as rustls's `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | | another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names, or a standard library type no other rule maps, such as `io::Error`, named by its full path, `_std_io_Error` | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | | `std::time::Instant` | an object `_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq`, with none of its methods | | `tracing::Level` | `_Level`: a C enum of its five levels, `TRACE` to `ERROR` | diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 6bfa56a88..05465e117 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -35,6 +35,9 @@ fixtures/reject/src/lib.rs:1193:1: rust2-ffi: cannot export fn `boxed_bytes`: bo fixtures/reject/src/lib.rs:1198:1: rust2-ffi: cannot export fn `count_later`: iterator of borrows in a future or callback; 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:1203:1: rust2-ffi: cannot export fn `count_opaques`: generic parameter `std::iter::Iterator`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1208:1: rust2-ffi: cannot export fn `unpin_resolver`: trait object `dyn tls::held::Resolver + std::marker::Unpin`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1213:1: rust2-ffi: cannot export fn `borrowed_resolver`: returned object that borrows `std::sync::Arc<(dyn tls::held::Resolver + 'a)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1228:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:123: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:137: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:154: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 bd693cf3d..05219e992 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1203,3 +1203,28 @@ pub async fn count_later<'a>(words: impl Iterator + Send) -> usi pub fn count_opaques<'a>(items: impl Iterator) -> usize { items.count() } + +/// A trait object with another auto trait than the one form its handle names. +pub fn unpin_resolver() -> std::sync::Arc { + std::sync::Arc::new(tls::held::Named("unpin".into())) +} + +/// A trait object that borrows, which no handle outliving the call may hold. +pub fn borrowed_resolver<'a>(_ids: &'a [u32]) -> std::sync::Arc { + std::sync::Arc::new(tls::held::Named("borrowed".into())) +} + +/// A stream an exported type implements, so the bound is met by a value C holds: refused, +/// not left out. +pub struct Pipe(pub u8); + +impl tls::held::Stream for Pipe { + fn read(&mut self) -> u8 { + self.0 + } +} + +/// Reads one byte of a stream. +pub fn pump_pipe(mut stream: T) -> u8 { + stream.read() +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 9e82d3743..93062a57d 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -946,12 +946,28 @@ impl<'tcx> Collector<'tcx> { /// the root does not reach, and not the standard library's, whose traits are closures and /// markers; taking no arguments, as its handle names none; and with no associated type /// fixed, which would be one. + /// + /// One object type per trait, as the handle names only the trait: its auto traits are + /// `Send` and `Sync` but those the trait implies, as `dyn Trait + Send + Sync` and, where + /// the trait has them as supertraits, `dyn Trait` are. Its lifetime is held, as + /// [`Self::lifetimes`] says, so one that borrows what C lends is refused. fn held_trait(&self, ty: Ty<'tcx>) -> Option { - let ty::Dynamic(preds, ..) = ty.kind() else { return None }; + let tcx = self.tcx; + let ty::Dynamic(preds, _) = ty.kind() else { + return None; + }; let principal = preds.principal()?.skip_binder(); let did = principal.def_id; let plain = principal.args.is_empty() && preds.projection_bounds().next().is_none(); - (plain && !self.walked(did.krate) && !self.sysroot.contains(&did.krate)).then_some(did) + let implied: Vec = rustc_middle::ty::elaborate::supertrait_def_ids(tcx, did).collect(); + let canonical: Vec = [tcx.get_diagnostic_item(sym::Send), tcx.get_diagnostic_item(sym::Sync)] + .into_iter() + .flatten() + .filter(|tr| !implied.contains(tr)) + .collect(); + let auto: Vec = preds.auto_traits().collect(); + let same = auto.len() == canonical.len() && auto.iter().all(|tr| canonical.contains(tr)); + (plain && same && !self.walked(did.krate) && !self.sysroot.contains(&did.krate)).then_some(did) } /// The type a handle holds by value, if it exports as an opaque handle: as @@ -3659,9 +3675,25 @@ impl<'tcx> Collector<'tcx> { // Another crate's trait, which no type the export holds meets, as instantiating found // none, and C cannot implement: no value C holds could be passed. The standard library's // traits are met by values C passes, which the rules may yet take. + // An impl for a type the export names, or for any type at all, may yet meet it. let unmet = (bounds.iter().map(|b| b.def_id())).any(|tr| { - !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate) - || matches!(self.trait_decl(tr), Some(Decl::Refused(_))) + let foreign = !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate); + let met = || { + tcx.all_impls(tr).any(|imp| { + // A blanket impl for any type, not one for a reference to any type, which + // needs that type to meet the bound itself. + let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + match ty.peel_refs().kind() { + ty::Param(_) => matches!(ty.kind(), ty::Param(_)), + ty::Adt(adt, _) => { + self.items.iter().any(|(item, _)| *item == adt.did()) + || self.foreign.iter().any(|&(f, _)| f == adt.did()) + } + _ => false, + } + }) + }; + foreign && !met() || matches!(self.trait_decl(tr), Some(Decl::Refused(_))) }); match local[..] { [_] => Err(why("callback bound", names.join(" + "))), @@ -4669,6 +4701,8 @@ impl<'tcx> Collector<'tcx> { // Another crate's `&'static dyn Trait`, which a handle holds. ty::Ref(region, ..) if self.opaque_value(ty).is_some() => held.push(*region), ty::Ref(region, ..) => lent.push(*region), + // A trait object a handle holds holds its own lifetime, as `dyn Trait + 'a` does. + ty::Dynamic(_, region) if self.held_trait(ty).is_some() => held.push(*region), // An object, an opaque value, or another crate's value an opaque handle holds, holds // what its lifetime parameters name. ty::Adt(adt, args) From 54645e569f242dec83d8d534a02d320d7ca45843 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:54:42 -0800 Subject: [PATCH 07/11] fix(ffi): a reference impl that needs no bound of its own may meet a foreign bound Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 1 + ffi/fixtures/reject/src/lib.rs | 5 +++++ ffi/fixtures/tls/src/lib.rs | 11 +++++++++++ ffi/src/collect.rs | 14 ++++++++++---- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 05465e117..8d5357c97 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -38,6 +38,7 @@ fixtures/reject/src/lib.rs:1203:1: rust2-ffi: cannot export fn `count_opaques`: fixtures/reject/src/lib.rs:1208:1: rust2-ffi: cannot export fn `unpin_resolver`: trait object `dyn tls::held::Resolver + std::marker::Unpin`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1213:1: rust2-ffi: cannot export fn `borrowed_resolver`: returned object that borrows `std::sync::Arc<(dyn tls::held::Resolver + 'a)>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1228:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1233:1: rust2-ffi: cannot export fn `pump_sink`: generic parameter `tls::held::Sink`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:123: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:137: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:154: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 05219e992..edaef9782 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1228,3 +1228,8 @@ impl tls::held::Stream for Pipe { pub fn pump_pipe(mut stream: T) -> u8 { stream.read() } + +/// A sink a reference to any exported type meets: refused, not left out. +pub fn pump_sink(sink: T) -> u8 { + sink.write(1) +} diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index 3ca094c47..cd12b34f9 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -233,4 +233,15 @@ pub mod held { pub trait Stream { fn read(&mut self) -> u8; } + + /// A sink every reference meets, whatever it refers to, so a value C holds may meet it. + pub trait Sink { + fn write(&self, byte: u8) -> u8; + } + + impl Sink for &T { + fn write(&self, byte: u8) -> u8 { + byte + } + } } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 93062a57d..b4fabe429 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3680,11 +3680,17 @@ impl<'tcx> Collector<'tcx> { let foreign = !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate); let met = || { tcx.all_impls(tr).any(|imp| { - // A blanket impl for any type, not one for a reference to any type, which - // needs that type to meet the bound itself. + // A blanket impl for any type, or for a reference to any type but one that + // needs that type to meet the bound itself, as tokio's `&mut T` impls do. let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); - match ty.peel_refs().kind() { - ty::Param(_) => matches!(ty.kind(), ty::Param(_)), + let inner = ty.peel_refs(); + match inner.kind() { + ty::Param(_) => { + ty == inner + || !(tcx.clauses_of(imp).instantiate_identity(tcx).clauses.iter()) + .filter_map(|clause| clause.skip_norm_wip().as_trait_clause()) + .any(|bound| bound.def_id() == tr && bound.self_ty().skip_binder() == inner) + } ty::Adt(adt, _) => { self.items.iter().any(|(item, _)| *item == adt.did()) || self.foreign.iter().any(|&(f, _)| f == adt.did()) From 7f07fad89cd94c2c7e3063f2b00c3ae4c2a296f2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:57:35 -0800 Subject: [PATCH 08/11] fix(ffi): a role type may meet a foreign bound, and an iterator's items stay owned An impl of another crate's trait for a value C passes by role, such as `u32`, now meets it when that value meets every bound, so the parameter stays refused rather than left out. An iterator's item parameter no longer falls back to a reference impl, and an explicit `I: Iterator` parameter names its `vec::IntoIter` instance as it maps there. The api C test frees the handle it passes to `Meters::spare`'s setter. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 1 + ffi/fixtures/api/src/lib.rs | 26 ++++++++++++++++++++ ffi/fixtures/reject/expected.txt | 1 + ffi/fixtures/reject/src/lib.rs | 5 ++++ ffi/fixtures/tls/src/lib.rs | 11 +++++++++ ffi/src/collect.rs | 32 ++++++++++++++++--------- ffi/tests/api.c | 8 ++++++- ffi/tests/api.cpp | 3 +++ ffi/tests/api.dart | 1 + ffi/tests/api.go | 1 + ffi/tests/api.kt | 1 + ffi/tests/api.py | 1 + ffi/tests/api.swift | 3 +++ 13 files changed, 82 insertions(+), 12 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index f5136a570..46ae8e425 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -657,6 +657,7 @@ fn main() { ); // Iterators, passed as the arrays of their items. println!("sum_all {}", api::sum_all(vec![1u32, 2, 3].into_iter())); + println!("weigh_all {}", api::weigh_all(vec![Counter::new("w", 3)].into_iter())); println!("offered_len {}", api::offered_len([&b"h3"[..], b"moq-00"].into_iter())); println!("join_words {}", api::join_words(["a", "b", "c"])); // Bytes that must be `'static`, interned. diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 1606226a2..e5ba0a571 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2570,6 +2570,32 @@ pub fn sum_all(items: impl Iterator) -> u32 { items.sum() } +/// What a counter weighs, owned or borrowed, which C cannot implement for its constant. +pub trait Weigh { + const SCALE: u64; + fn weight(&self) -> u64; +} + +impl Weigh for Counter { + const SCALE: u64 = 1; + fn weight(&self) -> u64 { + self.get() * Self::SCALE + } +} + +impl Weigh for &Counter { + const SCALE: u64 = 10; + fn weight(&self) -> u64 { + self.get() * Self::SCALE + } +} + +/// The weights of an iterator's items summed: C passes the array of its counters, each +/// moved in, so `&Counter`'s weight is not taken. +pub fn weigh_all, W: Weigh>(items: I) -> u64 { + items.map(|item| item.weight()).sum() +} + /// The total length of borrowed byte strings, as moq-tokio's TLS acceptor reads offered ALPNs. pub fn offered_len<'a>(alpns: impl Iterator) -> usize { alpns.map(<[u8]>::len).sum() diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 8d5357c97..b6cfddeb0 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -39,6 +39,7 @@ fixtures/reject/src/lib.rs:1208:1: rust2-ffi: cannot export fn `unpin_resolver`: fixtures/reject/src/lib.rs:1213:1: rust2-ffi: cannot export fn `borrowed_resolver`: returned object that borrows `std::sync::Arc<(dyn tls::held::Resolver + 'a)>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1228:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1233:1: rust2-ffi: cannot export fn `pump_sink`: generic parameter `tls::held::Sink`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1238:1: rust2-ffi: cannot export fn `widen`: generic parameter `tls::held::Width`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:123: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:137: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:154: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 edaef9782..020de32ef 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1233,3 +1233,8 @@ pub fn pump_pipe(mut stream: T) -> u8 { pub fn pump_sink(sink: T) -> u8 { sink.write(1) } + +/// A width only `u32`, which C passes by role, meets: refused, not left out. +pub fn widen(x: T) -> u32 { + x.bits() +} diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index cd12b34f9..415af9925 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -244,4 +244,15 @@ pub mod held { byte } } + + /// A width only `u32` has, a value C passes by role, so a value C holds may meet it. + pub trait Width { + fn bits(&self) -> u32; + } + + impl Width for u32 { + fn bits(&self) -> u32 { + 32 + } + } } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index b4fabe429..aded92a5d 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2938,6 +2938,8 @@ impl<'tcx> Collector<'tcx> { ty::Ref(_, inner, ty::Mutability::Not) => { self.arg(inner).map(|inner| Type::Ref(Mutability::Not, Box::new(inner))) } + // An iterator parameter's instance, the array C passes, as it maps there. + ty::Adt(adt, _) if Some(adt.did()) == self.vec_iter => self.ty(ty, Pos::Param), _ => self.arg(ty), }, GenericArgKind::Lifetime(_) => unreachable!("no lifetime names an instance"), @@ -3634,14 +3636,14 @@ impl<'tcx> Collector<'tcx> { // `impl Into>` takes a `String` too, which maps where `Arc` does not. // Not another crate's type a handle holds: the glue never names it, so nothing would // fix the call's type argument. - let iterated = self.iterated(def_id, param); - candidates.retain(|&(candidate, _)| { - // An array's items are owned, as C lends nothing inside one. - !(iterated && candidate.is_ref()) - && self.at(def_id, param, base, candidate).is_some() + let takes = |candidate: Ty<'tcx>| { + self.at(def_id, param, base, candidate).is_some() && self.maps(candidate, Pos::Param) && !(candidate.walk().filter_map(|arg| arg.as_type())).any(|ty| self.is_opaque(ty)) - }); + }; + let iterated = self.iterated(def_id, param); + // An array's items are owned, as C lends nothing inside one. + candidates.retain(|&(candidate, _)| !(iterated && candidate.is_ref()) && takes(candidate)); // Two sources that C passes as one buffer but that hold different values, as a // `String` and a `Vec` do, leave the caller no say in which conversion runs. Forms // of one value, as `&str` and `String` are, convert alike. @@ -3675,7 +3677,8 @@ impl<'tcx> Collector<'tcx> { // Another crate's trait, which no type the export holds meets, as instantiating found // none, and C cannot implement: no value C holds could be passed. The standard library's // traits are met by values C passes, which the rules may yet take. - // An impl for a type the export names, or for any type at all, may yet meet it. + // An impl for a type the export names, for a value C passes by role that meets every + // bound, or for any type at all, may yet meet it. let unmet = (bounds.iter().map(|b| b.def_id())).any(|tr| { let foreign = !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate); let met = || { @@ -3684,6 +3687,9 @@ impl<'tcx> Collector<'tcx> { // needs that type to meet the bound itself, as tokio's `&mut T` impls do. let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); let inner = ty.peel_refs(); + let role = || { + !ty.has_non_region_param() && takes(ty::fold_regions(tcx, ty, |_, _| tcx.lifetimes.re_erased)) + }; match inner.kind() { ty::Param(_) => { ty == inner @@ -3694,8 +3700,9 @@ impl<'tcx> Collector<'tcx> { ty::Adt(adt, _) => { self.items.iter().any(|(item, _)| *item == adt.did()) || self.foreign.iter().any(|&(f, _)| f == adt.did()) + || role() } - _ => false, + _ => role(), } }) }; @@ -3938,13 +3945,16 @@ impl<'tcx> Collector<'tcx> { // A lifetime bound, such as `'static`, which a reference to a value C passes for the // call cannot meet, though `at` holds modulo regions. let outlives = must_outlive(&self.implied(def_id, base), param); + // An array's items are owned, as C lends nothing inside one. + let iterated = self.iterated(def_id, param); + let owned = outlives || iterated; let mut found: Vec> = Vec::new(); for ty in self.implementors(def_id, param) { - if outlives && ty.is_ref() { + if owned && ty.is_ref() { continue; } // An implementation for `&X` is taken as it is: C passes no reference to one. - let borrowed = (!ty.is_ref() && !outlives).then(|| Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty)); + let borrowed = (!ty.is_ref() && !owned).then(|| Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty)); let ty = match borrowed.filter(|&borrowed| at(borrowed).is_some()) { Some(borrowed) => borrowed, None if at(ty).is_some() => ty, @@ -3966,7 +3976,7 @@ impl<'tcx> Collector<'tcx> { .filter_map(exported) .any(|(_, args)| args.iter().any(|arg| arg.walk().any(|a| a == param.into()))); for site in self.instances.iter().filter(|_| argument) { - for candidate in site.args.types() { + for candidate in site.args.types().filter(|ty| !(iterated && ty.is_ref())) { let erased = tcx.erase_and_anonymize_regions(candidate); if found .iter() diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 7fa2961de..150d7faa2 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1546,6 +1546,10 @@ static int script(void) { /* Iterators, passed as the arrays of their items. */ const uint32_t summed_items[] = {1, 2, 3}; printf("sum_all %u\n", api_sum_all((api_vec_u32){.ptr = summed_items, .len = 3})); + /* Each counter moves in, leaving its handle only to free. */ + api_Counter *weighed = api_Counter_new(str("w"), 3); + printf("weigh_all %llu\n", (unsigned long long)api_weigh_all_Counter((api_vec_Counter){.ptr = &weighed, .len = 1})); + api_Counter_free(weighed); const api_buf alpns[] = {str("h3"), str("moq-00")}; printf("offered_len %zu\n", api_offered_len((api_vec_bytes){.ptr = alpns, .len = 2})); const api_buf joined_words[] = {str("a"), str("b"), str("c")}; @@ -1592,7 +1596,9 @@ static int script(void) { /* An optional field that is not Clone, lent as `Some` of a handle. */ api_Meter *spare = api_Meters_spare_get(lender); printf("spare %s\n", spare != NULL ? "true" : "false"); - api_Meters_spare_set(lender, api_Meter_default()); + api_Meter *fresh = api_Meter_default(); + api_Meters_spare_set(lender, fresh); + api_Meter_free(fresh); spare = api_Meters_spare_get(lender); api_Meter_add(spare, 5); printf("spare lent %llu\n", (unsigned long long)api_Meter_add(spare, 1)); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 0df93cc7f..4a67f50d0 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -977,6 +977,9 @@ int script() { print("", api::failure_kind(std::move(failure)), "\n"); // Iterators, passed as the arrays of their items. std::printf("sum_all %u\n", unsigned(api::sum_all({1, 2, 3}))); + std::vector weighed; + weighed.push_back(api::Counter::new_("w", 3)); + std::printf("weigh_all %llu\n", ull(api::weigh_all_Counter(std::move(weighed)))); std::printf("offered_len %llu\n", ull(api::offered_len({"h3", "moq-00"}))); print("join_words ", api::join_words({"a", "b", "c"}), "\n"); // Bytes that must be `'static`, interned. diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 16cc0a17e..eb178569b 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -608,6 +608,7 @@ Future script() async { print('failure ${api.failureMessage(failure)} ${api.failureKind(failure)}'); // Iterators, passed as the arrays of their items. print('sum_all ${api.sumAll([1, 2, 3])}'); + print('weigh_all ${api.weighAllCounter([api.Counter('w', 3)])}'); print('offered_len ${api.offeredLen([utf8.encode('h3'), utf8.encode('moq-00')])}'); print('join_words ${api.joinWords(['a', 'b', 'c'])}'); // Bytes that must be `'static`, interned. diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 227deaffa..cc5698d77 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -728,6 +728,7 @@ func script() { fmt.Printf("failure %s %s\n", must(api.FailureMessage(failure)), must(api.FailureKind(failure))) // Iterators, passed as the arrays of their items. fmt.Printf("sum_all %d\n", api.SumAll([]uint32{1, 2, 3})) + fmt.Printf("weigh_all %d\n", must(api.WeighAllCounter([]*api.Counter{api.NewCounter("w", 3)}))) fmt.Printf("offered_len %d\n", api.OfferedLen([]rt.Bytes{rt.NewBytes([]byte("h3")), rt.NewBytes([]byte("moq-00"))})) fmt.Printf("join_words %s\n", api.JoinWords([]string{"a", "b", "c"})) // Bytes that must be `'static`, interned. diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 14e114e13..0597f28f5 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -526,6 +526,7 @@ fun script() { println("failure ${failureMessage(failure)} ${failureKind(failure)}") // Iterators, passed as the arrays of their items. println("sum_all ${sumAll(listOf(1u, 2u, 3u))}") + println("weigh_all ${weighAllCounter(listOf(Counter.new("w", 3u)))}") println("offered_len ${offeredLen(listOf(Bytes("h3".encodeToByteArray()), Bytes("moq-00".encodeToByteArray())))}") println("join_words ${joinWords(listOf("a", "b", "c"))}") // Bytes that must be `'static`, interned. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 0b0738108..dd4e96dcc 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -616,6 +616,7 @@ async def polls(): print(f"failure {api.failure_message(failure)} {api.failure_kind(failure)}") # Iterators, passed as the arrays of their items. print(f"sum_all {api.sum_all(iter([1, 2, 3]))}") + print(f"weigh_all {api.weigh_all_counter([api.Counter.new('w', 3)])}") print(f"offered_len {api.offered_len([b'h3', b'moq-00'])}") print(f"join_words {api.join_words(['a', 'b', 'c'])}") # Bytes that must be `'static`, interned. diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 1729f56c5..a3751be9e 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -708,6 +708,9 @@ func script() { print("failure \(message) \(failureKind(failed))") // Iterators, passed as the arrays of their items. print("sum_all \(sumAll([1, 2, 3]))") + var weighed = UniqueArray() + weighed.append(Counter.new("w", 3)) + print("weigh_all \(weighAllCounter(weighed))") print("offered_len \(offeredLen([Bytes("h3".utf8), Bytes("moq-00".utf8)]))") print("join_words \(joinWords(["a", "b", "c"]))") // Bytes that must be `'static`, interned. From 4c68d0f4e6f758814a88c73ce3da13091b4f879c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:10:55 -0800 Subject: [PATCH 09/11] fix(ffi): a borrowed value holding a trait-object handle is refused holds_handle matched only ADTs, so a trait object's handle, keyed by its trait, slipped past the borrowed-container guard: lifting took it out of C's handle on the first read. Record the pick round's follow-up answers. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 8 +++++--- ffi/fixtures/reject/src/lib.rs | 10 ++++++++++ ffi/src/collect.rs | 2 ++ quest/m1/ffi-export/not-send.md | 2 ++ quest/m1/ffi-refusals/ip-addr.md | 1 + 5 files changed, 20 insertions(+), 3 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index b6cfddeb0..be875a34b 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -37,10 +37,12 @@ fixtures/reject/src/lib.rs:11:1: rust2-ffi: cannot export fn `map`: foreign type fixtures/reject/src/lib.rs:1203:1: rust2-ffi: cannot export fn `count_opaques`: generic parameter `std::iter::Iterator`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1208:1: rust2-ffi: cannot export fn `unpin_resolver`: trait object `dyn tls::held::Resolver + std::marker::Unpin`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:1213:1: rust2-ffi: cannot export fn `borrowed_resolver`: returned object that borrows `std::sync::Arc<(dyn tls::held::Resolver + 'a)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1228:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1233:1: rust2-ffi: cannot export fn `pump_sink`: generic parameter `tls::held::Sink`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1238:1: rust2-ffi: cannot export fn `widen`: generic parameter `tls::held::Width`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1218:1: rust2-ffi: cannot export fn `peek_resolver`: reference to a handle inside a value `std::option::Option>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1223:1: rust2-ffi: cannot export fn `peek_codec`: trait object `dyn tls::held::Codec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1238:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:123: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:1243:1: rust2-ffi: cannot export fn `pump_sink`: generic parameter `tls::held::Sink`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1248:1: rust2-ffi: cannot export fn `widen`: generic parameter `tls::held::Width`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:137: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:154: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 fixtures/reject/src/lib.rs:16:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; 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 020de32ef..0775079d0 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1214,6 +1214,16 @@ pub fn borrowed_resolver<'a>(_ids: &'a [u32]) -> std::sync::Arc>) -> bool { + resolver.is_some() +} + +/// A `'static` trait-object handle inside a borrowed value, refused as the `Arc` form is. +pub fn peek_codec(codec: &Option<&'static dyn tls::held::Codec>) -> bool { + codec.is_some() +} + /// A stream an exported type implements, so the bound is met by a value C holds: refused, /// not left out. pub struct Pipe(pub u8); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index aded92a5d..6816490df 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4835,6 +4835,8 @@ impl<'tcx> Collector<'tcx> { fn holds_handle(&self, ty: Ty<'tcx>) -> bool { let tcx = self.tcx; ty.walk().filter_map(|arg| arg.as_type()).any(|ty| match ty.kind() { + // A trait object's handle, named by its trait rather than an ADT. + _ if self.is_opaque(ty) => true, ty::Adt(adt, args) => { // An opaque handle is never copied, even of a `Copy` value: lifting takes it. A // type [`FOREIGN`] maps by its role is an object. diff --git a/quest/m1/ffi-export/not-send.md b/quest/m1/ffi-export/not-send.md index 36b6563af..c6153843c 100644 --- a/quest/m1/ffi-export/not-send.md +++ b/quest/m1/ffi-export/not-send.md @@ -20,6 +20,8 @@ such object, which costs two thread handoffs a call even from a single-threaded such as Python's event loop; keeping the refusal, as the small-shapes quest had it. The maintainer: an assert is fine "where a language has no concept of something being thread local". +On 2026-11-14, at [#802](https://github.com/kixel-ai/rust2/pull/802)'s pick, the maintainer kept +`server::Listener::accept_with` in this quest: ✅ keep (rejected: drop). - The handle records its owner thread, and each call compares it: no atomics, so it costs less than a `Sync` type's borrow. The wrong thread diff --git a/quest/m1/ffi-refusals/ip-addr.md b/quest/m1/ffi-refusals/ip-addr.md index 25a94b0a1..4237d86b0 100644 --- a/quest/m1/ffi-refusals/ip-addr.md +++ b/quest/m1/ffi-refusals/ip-addr.md @@ -14,6 +14,7 @@ Decided with the maintainer on 2026-11-13, in [moq-excluded](https://github.com/kixel-ai/rust2/pull/802)'s Plan: ✅ `IpAddr` crosses as `SocketAddr` already does, by family. #802 split it out, since it is a new IR type through the glue and all seven generators, apart from that quest's collector rules. +The maintainer kept this quest on 2026-11-14, at #802's pick: ✅ keep (rejected: drop). - A new `_ip_addr` C struct of 16 bytes and an `is_v6` flag, `SocketAddr`'s without the port, and each binding's own address type where it is exact, as each maps From e662318157fb0ee33960d11891cf23024891672b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:58:35 -0800 Subject: [PATCH 10/11] fix(ffi): a positional field's accessor is a valid name in Python and Go moq's Controller::0, which this branch newly exports, generated Python's `def 0_get` and Go's `0Get`, so `import moq` failed in CodSpeed. Each now prefixes its positional field's own way (`_0_get`, `V0Get`), and the api fixture's Resolving covers it in every binding. resume's doc comment moves back from resolver. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 13 +++++++++++-- ffi/src/go.rs | 5 +++++ ffi/src/python.rs | 3 +++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index e5ba0a571..cd4c03185 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2511,8 +2511,6 @@ pub fn blame(err: tls::held::Invalid) -> String { err.to_string() } -/// A session of `alpn` lasting `seconds`, from a crate the facade re-exports nothing from: -/// its type exports by its path there, and its error crosses as its message. /// Another crate's trait object behind an `Arc`: an opaque handle, taken back as the `Arc`. pub fn resolver(name: &str) -> Arc { Arc::new(tls::held::Named(name.to_string())) @@ -2523,6 +2521,15 @@ pub fn resolved(resolver: Arc) -> String { resolver.name() } +/// A resolver as a tuple struct's field, whose accessors each binding names as its `_0`. +pub struct Resolving(pub Arc); + +impl Resolving { + pub fn new(name: &str) -> Self { + Self(resolver(name)) + } +} + /// Codecs, each another crate's `&'static dyn Codec`, held by value in an opaque handle. pub struct Codecs { pub list: Vec<&'static dyn tls::held::Codec>, @@ -2631,6 +2638,8 @@ pub fn pump(mut stream: T) -> u8 { stream.read() } +/// A session of `alpn` lasting `seconds`, from a crate the facade re-exports nothing from: +/// its type exports by its path there, and its error crosses as its message. pub fn resume(alpn: &str, seconds: u32) -> Result { tls::resume(alpn, seconds) } diff --git a/ffi/src/go.rs b/ffi/src/go.rs index f8dbc2862..eaeacf583 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2247,6 +2247,11 @@ impl<'a> Gen<'a> { } } }; + // A positional field's accessor, `0Get`, is `V0Get`, as its field is `V0`. + let member = match member.starts_with(|c: char| c.is_ascii_digit()) { + true => format!("V{member}"), + false => member, + }; let classes = self.classes.get(self.pkg); let member = match (receiver.is_some(), member.as_str()) { // What every object or value of the type already has. diff --git a/ffi/src/python.rs b/ffi/src/python.rs index fdb508a9d..5532a75fc 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1985,6 +1985,9 @@ fn kw(name: &str) -> String { /// A member's Python name: its snake-case name, with `_` appended if a keyword, and until /// it is none of `reserved`, such as one Python gives every such class. fn member(snake: &str, reserved: &[&str]) -> String { + // A positional field's accessor, `0_get`, is `_0_get`, as its field is `_0`. + let digit = snake.starts_with(|c: char| c.is_ascii_digit()).then(|| format!("_{snake}")); + let snake = digit.as_deref().unwrap_or(snake); if !reserved.contains(&snake) { return kw(snake); } From 96837c84aedad1d1390fef58a35c9f284bda1edd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:04:53 -0800 Subject: [PATCH 11/11] style(ffi): rustfmt Co-Authored-By: Claude Opus 5.5 --- ffi/src/python.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 5532a75fc..c5621a11f 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1986,7 +1986,9 @@ fn kw(name: &str) -> String { /// it is none of `reserved`, such as one Python gives every such class. fn member(snake: &str, reserved: &[&str]) -> String { // A positional field's accessor, `0_get`, is `_0_get`, as its field is `_0`. - let digit = snake.starts_with(|c: char| c.is_ascii_digit()).then(|| format!("_{snake}")); + let digit = snake + .starts_with(|c: char| c.is_ascii_digit()) + .then(|| format!("_{snake}")); let snake = digit.as_deref().unwrap_or(snake); if !reserved.contains(&snake) { return kw(snake);