From 4e8a7d647f8120bfb66a122b515fd20121c98c27 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 11:05:23 -0800 Subject: [PATCH 01/26] chore(quest): claim quest/m1/ffi-refusals/moq-pin.md Quest-Claim: 51e7f297c991d9cb From f21ae8728e8beec239d56e166495d537ad64217d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 11:10:27 -0800 Subject: [PATCH 02/26] feat(ffi): export a type the root does not reach by its public path in its crate Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 94 ++++++++++++++++++++++++++++++-- ffi/tests/fixtures.rs | 57 +++++++++++++++++++ quest/m1/ffi-refusals/moq-pin.md | 7 ++- 3 files changed, 153 insertions(+), 5 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 8dcb4e8c5..e9176f3bf 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -208,6 +208,11 @@ struct Collector<'tcx> { range_bounds: Option, /// Objects no export returns, left out. orphans: rustc_data_structures::fx::FxHashSet>, + /// Types a signature names that the root does not reach, each exported by its public + /// path in its own crate. + reach: Vec, + /// Such types this pass met that `reach` lacks. + unreached: std::cell::RefCell>, api: Api, } @@ -284,7 +289,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { }; keys.insert(krate, key); } - let pass = |orphans: &rustc_data_structures::fx::FxHashSet>| { + let pass = |orphans: &rustc_data_structures::fx::FxHashSet>, reach: &[DefId]| { let mut c = Collector { tcx, items: Vec::new(), @@ -318,6 +323,8 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { bound, range_bounds, orphans: orphans.clone(), + reach: reach.to_vec(), + unreached: Default::default(), api: Api { records: Vec::new(), enums: Vec::new(), @@ -354,18 +361,23 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { c }; // Leaving out an object no export returns leaves out what takes it, which may leave another - // object no export returns, so collection repeats until it refuses no more. + // object no export returns, so collection repeats until it refuses no more. A type the + // root does not reach is walked from its defining path in the next pass, whose + // signatures may name more. let mut orphans = rustc_data_structures::fx::FxHashSet::default(); + let mut reach = Vec::new(); loop { - let c = pass(&orphans); + let c = pass(&orphans, &reach); let more = c.orphans(); - if more.is_empty() { + let unreached = c.unreached.take(); + if more.is_empty() && unreached.is_empty() { return Collected { api: c.api, report: c.report, }; } orphans.extend(more); + reach.extend(unreached); } } @@ -1150,6 +1162,73 @@ impl<'tcx> Collector<'tcx> { } } } + self.walk_reach(&seen); + } + + /// Walk each type in `reach` the root did not, by its public path in its own crate, as if + /// a module of the facade re-exported that crate's root. + fn walk_reach(&mut self, seen: &rustc_data_structures::fx::FxHashSet) { + let tcx = self.tcx; + for def_id in self.reach.clone() { + if seen.contains(&def_id) { + continue; + } + let mut path = vec![self.report.root.clone()]; + if !def_id.is_local() { + path.push(tcx.crate_name(def_id.krate).to_string()); + } + let own = self.crate_path(def_id).expect("a reached type has a path in its crate"); + let outside = path.len(); + path.extend(own); + if self.exclude(&path) { + self.left_out.insert(def_id, "excluded type"); + continue; + } + if tcx.is_doc_hidden(def_id) { + let (report, rest) = self.report(&path); + report.hidden.push(rest); + self.left_out.insert(def_id, "doc(hidden) type"); + continue; + } + if !self.crates.contains(&def_id.krate) { + self.crates.push(def_id.krate); + } + self.outside.insert(def_id, outside); + self.items.push((def_id, path)); + } + } + + /// The shortest public path to `def_id` from its own crate's root, through that crate's + /// modules and re-exports, as `kio::Pending` names one defined in a private module. + fn crate_path(&self, def_id: DefId) -> Option> { + let tcx = self.tcx; + let root = def_id.krate.as_def_id(); + let mut seen = rustc_data_structures::fx::FxHashSet::default(); + let mut queue = VecDeque::from([(root, Vec::new())]); + while let Some((module, path)) = queue.pop_front() { + let children = match module.as_local() { + Some(local) => tcx.module_children_local(local), + None => tcx.module_children(module), + }; + for child in children { + let Res::Def(kind, id) = child.res else { + continue; + }; + if !child.vis.is_public() || child.ident.name == rustc_span::kw::Underscore || id.krate != def_id.krate + { + continue; + } + let mut path = path.clone(); + path.push(child.ident.to_string()); + if id == def_id { + return Some(path); + } + if kind == DefKind::Mod && seen.insert(id) { + queue.push_back((id, path)); + } + } + } + None } /// Decide how each type and trait is exported, before any signature names one. @@ -4352,6 +4431,13 @@ impl<'tcx> Collector<'tcx> { why.note = Some((tcx.def_span(did), note)); return Err(why); } + // One public in its own crate exports by that path, in the next pass. + if !self.reach.contains(&did) && self.crate_path(did).is_some() { + let mut unreached = self.unreached.borrow_mut(); + if !unreached.contains(&did) { + unreached.push(did); + } + } return Err(why("type not reachable from the crate root", name)); } } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 96cc7011d..6a4c2fd3f 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1212,6 +1212,63 @@ fn go_package_names() { vet(&go); } +/// A type a signature names that the root does not reach, as moq-net's `kio::Pending`, +/// exports by its public path in its own crate, through a re-export or a module; one no public +/// path names stays refused. +#[test] +fn unreached_types() { + let package = package("unreached_types"); + write_all( + &package, + &[ + ( + "Cargo.toml", + "[package]\nname = \"unreached_types\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"pkg\"\n\n\ + [dependencies]\nkio = { package = \"unreached-kio\", path = \"kio\" }\n\n[workspace]\nexclude = [\"kio\"]\n", + ), + ( + "src/lib.rs", + "pub use kio::Ready;\n\npub fn pending() -> kio::Pending {\n\tkio::Pending(1)\n}\n\n\ + pub fn version() -> kio::version::Version {\n\tkio::version::Version { major: 2 }\n}\n\n\ + pub fn sealed() -> u32 {\n\tkio::sealed().0\n}\n\npub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", + ), + ( + "kio/Cargo.toml", + "[package]\nname = \"unreached-kio\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"kio\"\n", + ), + ( + "kio/src/lib.rs", + "pub struct Ready;\n\nmod pollable {\n\tpub struct Pending(pub u32);\n\n\timpl Pending {\n\t\tpub fn id(&self) -> u32 {\n\t\t\tself.0\n\t\t}\n\t}\n}\n\npub use pollable::Pending;\n\n\ + pub mod version {\n\t#[derive(Clone, Copy)]\n\tpub struct Version {\n\t\tpub major: u32,\n\t}\n}\n\n\ + mod sealed {\n\tpub struct Sealed(pub u32);\n}\n\npub type Sealed = sealed::Sealed;\n\n\ + pub fn sealed() -> sealed::Sealed {\n\tsealed::Sealed(3)\n}\n", + ), + ], + ); + let census = package.join("census"); + let output = Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) + .arg("--config") + .arg(package.join("ffi.toml")) + .arg("--census") + .arg(&census) + .env("CARGO_TARGET_DIR", package.join("build")) + .output() + .unwrap(); + assert!( + output.status.success(), + "the census failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = std::fs::read_to_string(census.join("unreached_types.md")).unwrap(); + // `Pending` and `Version` export; `Sealed` alone is refused, though an alias names it. + assert!(report.contains("| Types | 2 | 0 |"), "{report}"); + assert!( + report.contains("fn `seal` at src/lib.rs:15:1: type not reachable from the crate root `kio::sealed::Sealed`"), + "{report}" + ); + assert_eq!(report.matches("not reachable").count(), 3, "{report}"); +} + /// `go vet` over an export's `go/`, which the header beside it lets cgo check unlinked. fn vet(go: &Path) { run(Command::new("go") diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index 4c8df9538..160968e41 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -58,7 +58,12 @@ moq's `main` fails `just ts moq` and `just ffi moq-cpp`, so the bump waits on Wa Decided 2026-11-11 (maintainer, /quest-unblock): ✅ (a) rust2 exports a type the crate root does not reach by its defining path, such as `kio::Pending` and `lite::version::Version`; a type whose defining path is itself private stays refused (rejected: (b) moq makes both reachable). -This quest makes the exporter change, in `ffi/src/collect.rs`, before the bump. +[moq-dev/rust2#721](https://github.com/moq-dev/rust2/pull/721) made the exporter change: a +type a signature names that the root does not reach exports by its shortest public path in +its own crate, so `kio::Pending` (defined in kio's private `pollable`) and moq-tokio's +`cli::Deprecated` export. At moq `ba47ea3` the census then lists no such refusal; only +`lite::version::Version`, which no public path names, stays out, as an object no export +returns. Measured on 2026-11-12 at moq's `main` `6936f0a`: `just ffi moq-cpp` fails the export with 36 errors, which the bump fixes in `ffi/moq/ffi.toml` or the exporter: 15 on the foreign From 1b0108148c5a62cf9a03345c54e33d1c3c85a9fc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 11:33:00 -0800 Subject: [PATCH 03/26] fix(ffi): name a reached crate's types through the glue's own dependency on it Co-Authored-By: Claude Opus 5.5 --- ffi/src/cli.rs | 62 ++++++++++++++++++++++++++++++++ ffi/src/collect.rs | 52 ++++++++++++++++++++++++--- ffi/src/config.rs | 3 ++ ffi/src/driver.rs | 14 ++++++++ ffi/src/glue.rs | 29 +++++++++++++-- ffi/src/ir.rs | 12 +++++++ ffi/src/merge.rs | 6 ++++ ffi/tests/fixtures.rs | 21 +++++++++-- quest/m1/ffi-refusals/moq-pin.md | 12 ++++--- 9 files changed, 197 insertions(+), 14 deletions(-) diff --git a/ffi/src/cli.rs b/ffi/src/cli.rs index 36b119d12..7ddad1964 100644 --- a/ffi/src/cli.rs +++ b/ffi/src/cli.rs @@ -63,6 +63,7 @@ fn try_run(args: &[String]) -> Result { let dir = args.manifest.parent().expect("a manifest path has a parent"); let picks = Picks::parse(&args.cargo, dir)?; let (facade, patch, checked) = facade(&args.manifest, &targets[0], &picks)?; + let crates = crates(&checked.metadata, &checked.top)?; let line = facade.line(); // A staged API's spans are relative to the workspace and cargo's home, which hold the // same files at other paths on another host. @@ -85,6 +86,7 @@ fn try_run(args: &[String]) -> Result { (config::env::CONFIG, args.config.as_os_str()), (config::env::PACKAGE, line.as_ref()), (config::env::PATCH, patch.as_ref()), + (config::env::CRATES, crates.as_ref()), (config::env::MERGE, merge), (config::env::ROOTS, roots.as_ref()), output, @@ -286,6 +288,66 @@ fn facade(manifest: &Path, target: &str, picks: &Picks<'_>) -> Result<(config::P Ok((facade, patch, checked)) } +/// Each crate the facade builds with, by its library's crate name, as the glue would depend +/// on the very package: by its directory, its exact crates.io version, or its git commit. +/// A name two packages share, or one from another registry, is left out, so a type of its +/// crate the facade does not re-export stays refused. +fn crates(metadata: &Metadata, top: &str) -> Result { + let packages: BTreeMap<&str, &Package> = metadata.packages.iter().map(|p| (p.id.as_str(), p)).collect(); + let nodes: BTreeMap<&str, &Node> = metadata.resolve.nodes.iter().map(|n| (n.id.as_str(), n)).collect(); + let mut named: BTreeMap> = BTreeMap::new(); + let mut seen = BTreeSet::new(); + let mut queue = vec![top]; + while let Some(id) = queue.pop() { + let (true, Some(package), Some(node)) = (seen.insert(id), packages.get(id), nodes.get(id)) else { + continue; + }; + if id != top + && let Some(lib) = (package.targets.iter()).find(|t| t.kind.iter().any(|k| k.contains("lib"))) + { + let keys = dependency(package); + let lib = lib.name.replace('-', "_"); + match named.get(&lib) { + Some(other) if *other != keys => { + named.insert(lib, None); + } + Some(_) => {} + None => { + named.insert(lib, keys); + } + } + } + let built = |kind: &Option| kind.as_deref() != Some("dev"); + for dep in node.deps.iter().filter(|d| d.dep_kinds.iter().any(|k| built(&k.kind))) { + queue.push(&dep.pkg); + } + } + let table: toml::Table = (named.into_iter()) + .filter_map(|(lib, keys)| Some((lib, toml::Value::String(keys?)))) + .collect(); + toml::to_string(&table).map_err(|err| format!("writing the crates: {err}")) +} + +/// The TOML keys of a dependency on exactly `package`, if the glue can name it. +fn dependency(package: &Package) -> Option { + let name = &package.name; + match package.source.as_deref() { + None => { + let dir = package.manifest_path.parent().expect("a manifest path has a parent"); + Some(format!("package = {name:?}, path = {:?}", dir.display().to_string())) + } + Some("registry+https://github.com/rust-lang/crates.io-index" | "sparse+https://index.crates.io/") => { + Some(format!("package = {name:?}, version = \"={}\"", package.version)) + } + Some(git) if git.starts_with("git+") => { + let (url, rev) = git["git+".len()..].split_once('#')?; + let url = url.split('?').next().unwrap_or(url); + Some(format!("package = {name:?}, git = {url:?}, rev = {rev:?}")) + } + Some(_) => None, + } +} + /// The `[patch]` the glue's workspace resolves the exports by as the check did, wherever /// it builds, as TOML with each path absolute. fn overrides(metadata: &Metadata, top: &Package) -> Result { diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index e9176f3bf..89e107e74 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -95,6 +95,8 @@ pub struct Facade<'a> { pub package: &'a str, /// Paths from its root the config leaves out. pub exclude: &'a [String], + /// The dependency the glue names each crate it builds with by, by its crate name. + pub crates: &'a std::collections::BTreeMap, } /// What collection found in the facade, by paths from its root. @@ -211,6 +213,8 @@ struct Collector<'tcx> { /// Types a signature names that the root does not reach, each exported by its public /// path in its own crate. reach: Vec, + /// The glue's dependency on each crate, as [`Facade::crates`]. + dependencies: std::collections::BTreeMap, /// Such types this pass met that `reach` lacks. unreached: std::cell::RefCell>, api: Api, @@ -324,6 +328,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { range_bounds, orphans: orphans.clone(), reach: reach.to_vec(), + dependencies: facade.crates.clone(), unreached: Default::default(), api: Api { records: Vec::new(), @@ -333,6 +338,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { functions: Vec::new(), constants: Vec::new(), crates: Vec::new(), + reached: Vec::new(), targets: vec![tcx.sess.opts.target_triple.tuple().to_string()], }, }; @@ -376,8 +382,13 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { report: c.report, }; } - orphans.extend(more); - reach.extend(unreached); + // A newly reached type may return an object marked an orphan, so those start over. + if unreached.is_empty() { + orphans.extend(more); + } else { + reach.extend(unreached); + orphans.clear(); + } } } @@ -1179,6 +1190,13 @@ impl<'tcx> Collector<'tcx> { } let own = self.crate_path(def_id).expect("a reached type has a path in its crate"); let outside = path.len(); + if !def_id.is_local() && !self.api.reached.iter().any(|r| r.krate == path[1]) { + let dependency = self.dependency(def_id.krate).expect("a reached crate has a dependency"); + self.api.reached.push(crate::ir::Reached { + krate: path[1].clone(), + dependency, + }); + } path.extend(own); if self.exclude(&path) { self.left_out.insert(def_id, "excluded type"); @@ -1198,6 +1216,29 @@ impl<'tcx> Collector<'tcx> { } } + /// Whether `def_id` exports by its public path in its own crate. Another crate's must be + /// the only crate of its name, named by none of the facade's root items, and one the glue + /// can depend on, so its path names it there. + fn reachable(&self, def_id: DefId) -> bool { + let tcx = self.tcx; + if self.crate_path(def_id).is_none() { + return false; + } + if def_id.is_local() { + return true; + } + let name = tcx.crate_name(def_id.krate); + let root = tcx.module_children_local(LOCAL_CRATE.as_def_id().expect_local()); + self.keys[&def_id.krate] == name.as_str() + && !root.iter().any(|child| child.ident.name == name) + && self.dependency(def_id.krate).is_some() + } + + /// The TOML keys of the glue's dependency on `krate`, as the facade resolves it. + fn dependency(&self, krate: CrateNum) -> Option { + self.dependencies.get(self.tcx.crate_name(krate).as_str()).cloned() + } + /// The shortest public path to `def_id` from its own crate's root, through that crate's /// modules and re-exports, as `kio::Pending` names one defined in a private module. fn crate_path(&self, def_id: DefId) -> Option> { @@ -1214,7 +1255,10 @@ impl<'tcx> Collector<'tcx> { let Res::Def(kind, id) = child.res else { continue; }; - if !child.vis.is_public() || child.ident.name == rustc_span::kw::Underscore || id.krate != def_id.krate + if !child.vis.is_public() + || child.ident.name == rustc_span::kw::Underscore + || id.krate != def_id.krate + || (kind == DefKind::Mod && tcx.is_doc_hidden(id)) { continue; } @@ -4432,7 +4476,7 @@ impl<'tcx> Collector<'tcx> { return Err(why); } // One public in its own crate exports by that path, in the next pass. - if !self.reach.contains(&did) && self.crate_path(did).is_some() { + if !self.reach.contains(&did) && self.reachable(did) { let mut unreached = self.unreached.borrow_mut(); if !unreached.contains(&did) { unreached.push(did); diff --git a/ffi/src/config.rs b/ffi/src/config.rs index bc274c43a..a7e70e9c9 100644 --- a/ffi/src/config.rs +++ b/ffi/src/config.rs @@ -92,4 +92,7 @@ pub mod env { pub const PACKAGE: &str = "RUST2_FFI_PACKAGE"; /// The `[patch]` resolving the facade as cargo did, as TOML with each path absolute. pub const PATCH: &str = "RUST2_FFI_PATCH"; + /// The dependency the glue would name each crate the facade builds with by, as a TOML + /// table from its library's crate name to its keys. + pub const CRATES: &str = "RUST2_FFI_CRATES"; } diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index 27c89442d..acbff2a7d 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -44,6 +44,8 @@ pub fn run(args: Vec) -> ExitCode { /// Compiles the facade, exporting its API after analysis. struct Export { + /// Each crate the facade builds with, as [`config::env::CRATES`] has them. + crates: std::collections::BTreeMap, config: Config, output: Output, /// The facade's package, with the features rustc compiles it with. @@ -112,7 +114,18 @@ impl Export { .map(str::to_string) .collect(); let patch = std::env::var(config::env::PATCH).map_err(|_| format!("{} is unset", config::env::PATCH))?; + let crates = std::env::var(config::env::CRATES).map_err(|_| format!("{} is unset", config::env::CRATES))?; + let crates: toml::Table = crates + .parse() + .map_err(|err| format!("{} is malformed: {err}", config::env::CRATES))?; + let crates = (crates.into_iter()) + .map(|(lib, keys)| match keys { + toml::Value::String(keys) => Ok((lib, keys)), + _ => Err(format!("{} is malformed: {lib}", config::env::CRATES)), + }) + .collect::>()?; Ok(Some(Self { + crates, config, output, facade, @@ -132,6 +145,7 @@ impl Callbacks for Export { root: self.facade.root(), package: &self.facade.name, // A census counts the whole API, whatever the config leaves out. + crates: &self.crates, exclude: match self.output { Output::Census(_) => &[], Output::Dir(_) | Output::Api(_) => &self.config.exclude, diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 974cff9d7..9f72bbe09 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -46,6 +46,12 @@ fn dependency(krate: &str) -> String { format!("{krate}_export") } +/// The name the crate depends on a crate the facade does not re-export by, apart from the +/// facade's even when they share a name. +fn reached(krate: &str) -> String { + format!("{krate}_reached") +} + /// The name the crate depends on a foreign type's crate by, apart from the facade's even /// when the facade shares that crate's name. fn foreign(krate: &str) -> String { @@ -158,7 +164,18 @@ impl Crate<'_> { ) }) .collect(); - let dependencies = format!("{dependencies}{foreign}"); + // A crate the facade does not re-export, whose types an export names, as the facade + // resolves it, so they are the facade's types. + let reached: String = (api.reached.iter()) + .map(|r| { + format!( + "{} = {{ {}, default-features = false }}\n", + reached(&r.krate), + r.dependency + ) + }) + .collect(); + let dependencies = format!("{dependencies}{foreign}{reached}"); // The facade's oldest toolchain is the crate's, which cargo sets as rustc compiles it, // though no older than the crate's edition needs; cargo checks the value's form. let rust_version = match std::env::var("CARGO_PKG_RUST_VERSION") { @@ -394,9 +411,15 @@ impl Gen<'_> { .unwrap_or_default() } - /// A Rust path of the facade's, through the crate's dependency on it. + /// A Rust path of the facade's, through the crate's dependency on it, or on the crate + /// its second segment names, where the facade does not re-export that crate. fn path(&self, path: &[String]) -> String { - format!("::{}", self.dependency) + &path[1..].iter().map(|s| format!("::{s}")).collect::() + match self.abi.api.reached.iter().find(|r| path.get(1) == Some(&r.krate)) { + Some(r) => { + format!("::{}", reached(&r.krate)) + &path[2..].iter().map(|s| format!("::{s}")).collect::() + } + None => format!("::{}", self.dependency) + &path[1..].iter().map(|s| format!("::{s}")).collect::(), + } } /// An object's Rust type: its lifetimes `'static`, as the handle holds it. diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index cfb83ff32..2b6ac4df7 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -17,10 +17,22 @@ pub struct Api { pub constants: Vec, /// The crates items belong to, each after every crate it depends on. pub crates: Vec, + /// The crates the facade does not re-export whose types an export names, which the + /// glue depends on directly. + pub reached: Vec, /// The targets it serves, sorted: one for a single target's, several merged. pub targets: Vec, } +/// A crate the glue depends on beside the facade, as the facade resolves it. +#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Reached { + /// Its crate name, its items' second path segment. + pub krate: String, + /// Its dependency's TOML keys, which name the facade's package of it. + pub dependency: String, +} + impl Api { /// Whether an item on `on` is on every target the API serves. pub fn everywhere(&self, on: On) -> bool { diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 0905cec95..3ee4b0f03 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -342,6 +342,11 @@ impl Merged { .unwrap_or(self.api.crates.len()); self.api.crates.insert(at, krate.clone()); } + for reached in api.reached { + if !self.api.reached.iter().any(|r| r.krate == reached.krate) { + self.api.reached.push(reached); + } + } for (record, at) in api.records.into_iter().zip(maps.records) { let Some(ours) = self.api.records.get(at) else { self.api.records.push(record); @@ -738,6 +743,7 @@ mod tests { functions: Vec::new(), constants: Vec::new(), crates: ["a", "c"].map(String::from).to_vec(), + reached: Vec::new(), targets: ["x", "y"].map(String::from).to_vec(), }; let Err(cycle) = order_crates(&api) else { diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 6a4c2fd3f..dc9b1affc 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1230,7 +1230,7 @@ fn unreached_types() { "src/lib.rs", "pub use kio::Ready;\n\npub fn pending() -> kio::Pending {\n\tkio::Pending(1)\n}\n\n\ pub fn version() -> kio::version::Version {\n\tkio::version::Version { major: 2 }\n}\n\n\ - pub fn sealed() -> u32 {\n\tkio::sealed().0\n}\n\npub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", + pub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", ), ( "kio/Cargo.toml", @@ -1245,6 +1245,23 @@ fn unreached_types() { ), ], ); + // The export builds, naming `kio`'s types through its own dependency on `kio`. + std::fs::write(package.join("ffi.toml"), "exclude = [\"seal\"]\n").unwrap(); + let out = package.join("out"); + run(Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) + .arg("--config") + .arg(package.join("ffi.toml")) + .arg("--out") + .arg(&out) + .env("CARGO_TARGET_DIR", package.join("build"))); + let glue = std::fs::read_to_string(out.join("src/lib.rs")).unwrap(); + assert!(glue.contains("::kio_reached::Pending"), "{glue}"); + run(cargo() + .arg("build") + .arg("--manifest-path") + .arg(out.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", package.join("build"))); + std::fs::write(package.join("ffi.toml"), "").unwrap(); let census = package.join("census"); let output = Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) .arg("--config") @@ -1263,7 +1280,7 @@ fn unreached_types() { // `Pending` and `Version` export; `Sealed` alone is refused, though an alias names it. assert!(report.contains("| Types | 2 | 0 |"), "{report}"); assert!( - report.contains("fn `seal` at src/lib.rs:15:1: type not reachable from the crate root `kio::sealed::Sealed`"), + report.contains("fn `seal` at src/lib.rs:11:1: type not reachable from the crate root `kio::sealed::Sealed`"), "{report}" ); assert_eq!(report.matches("not reachable").count(), 3, "{report}"); diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index 160968e41..afe1dfba9 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -4,8 +4,8 @@ The moq pin moves to moq's current `main`, whose crates re-export no whole crate, moq's own included. `just ffi census` there lists no whole-crate re-export refusal. Its "type not -reachable from the crate root" refusals are `kio::Pending` and `lite::version::Version`, -which the exporter change below exports, and moq-quic's stats and varint types under moq-tokio's `quic::driver`, +reachable from the crate root" refusals were `kio::Pending` and moq-tokio's `cli::Deprecated`, +which the exporter change below exports, `lite::version::Version`, which no public path names, and moq-quic's stats and varint types under moq-tokio's `quic::driver`, which [moq-dev/rust2#683](https://github.com/moq-dev/rust2/pull/683) drops. At `ffcb7cd9` there were 20 such refusals (18 Guard and Side, and `Version`), and 9 at moq's head on 2026-11-09, measured in [#676](https://github.com/moq-dev/rust2/pull/676). @@ -61,9 +61,11 @@ whose defining path is itself private stays refused (rejected: (b) moq makes bot [moq-dev/rust2#721](https://github.com/moq-dev/rust2/pull/721) made the exporter change: a type a signature names that the root does not reach exports by its shortest public path in its own crate, so `kio::Pending` (defined in kio's private `pollable`) and moq-tokio's -`cli::Deprecated` export. At moq `ba47ea3` the census then lists no such refusal; only -`lite::version::Version`, which no public path names, stays out, as an object no export -returns. +`cli::Deprecated` export, the glue naming them through its own dependency on their crate's +package. At moq `ba47ea3` the census, which ignores `ffi/moq/ffi.toml`'s excludes, then lists +no such refusal; only `lite::version::Version`, which no public path names, stays out, as an +object no export returns. The bump drops the stale `kio` exclude, which would otherwise leave +`kio::Pending` out of the export. Measured on 2026-11-12 at moq's `main` `6936f0a`: `just ffi moq-cpp` fails the export with 36 errors, which the bump fixes in `ffi/moq/ffi.toml` or the exporter: 15 on the foreign From 11d8c73e71d2fd7ee045031752be41af3b94d5d7 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 11:46:02 -0800 Subject: [PATCH 04/26] fix(ffi): keep a reached git dependency's reference, its targets, and this host's keys Co-Authored-By: Claude Opus 5.5 --- ffi/src/cli.rs | 14 +++++++++++--- ffi/src/collect.rs | 10 ++-------- ffi/src/driver.rs | 1 + ffi/src/glue.rs | 32 +++++++++++++++++++++++--------- ffi/src/ir.rs | 4 ++-- ffi/src/merge.rs | 9 +++++++-- 6 files changed, 46 insertions(+), 24 deletions(-) diff --git a/ffi/src/cli.rs b/ffi/src/cli.rs index 7ddad1964..7761d6afe 100644 --- a/ffi/src/cli.rs +++ b/ffi/src/cli.rs @@ -339,10 +339,18 @@ fn dependency(package: &Package) -> Option { Some("registry+https://github.com/rust-lang/crates.io-index" | "sparse+https://index.crates.io/") => { Some(format!("package = {name:?}, version = \"={}\"", package.version)) } + // By the reference the facade names it by, which is part of its source's identity: + // `?branch=`, `?tag=`, or `?rev=`, or none for the default branch. The lockfile + // pins the commit as the facade's does. Some(git) if git.starts_with("git+") => { - let (url, rev) = git["git+".len()..].split_once('#')?; - let url = url.split('?').next().unwrap_or(url); - Some(format!("package = {name:?}, git = {url:?}, rev = {rev:?}")) + let url = git["git+".len()..].split('#').next().unwrap_or(git); + let (url, reference) = url.split_once('?').unwrap_or((url, "")); + let reference = match reference.split_once('=') { + Some((key @ ("branch" | "tag" | "rev"), value)) => format!(", {key} = {value:?}"), + Some(_) => return None, + None => String::new(), + }; + Some(format!("package = {name:?}, git = {url:?}{reference}")) } Some(_) => None, } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 89e107e74..e5ad8a9d1 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1191,10 +1191,9 @@ impl<'tcx> Collector<'tcx> { let own = self.crate_path(def_id).expect("a reached type has a path in its crate"); let outside = path.len(); if !def_id.is_local() && !self.api.reached.iter().any(|r| r.krate == path[1]) { - let dependency = self.dependency(def_id.krate).expect("a reached crate has a dependency"); self.api.reached.push(crate::ir::Reached { krate: path[1].clone(), - dependency, + targets: self.api.targets.clone(), }); } path.extend(own); @@ -1231,12 +1230,7 @@ impl<'tcx> Collector<'tcx> { let root = tcx.module_children_local(LOCAL_CRATE.as_def_id().expect_local()); self.keys[&def_id.krate] == name.as_str() && !root.iter().any(|child| child.ident.name == name) - && self.dependency(def_id.krate).is_some() - } - - /// The TOML keys of the glue's dependency on `krate`, as the facade resolves it. - fn dependency(&self, krate: CrateNum) -> Option { - self.dependencies.get(self.tcx.crate_name(krate).as_str()).cloned() + && self.dependencies.contains_key(name.as_str()) } /// The shortest public path to `def_id` from its own crate's root, through that crate's diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index acbff2a7d..93c8f5149 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -302,6 +302,7 @@ impl Export { abi: &abi, facade: &self.facade, patch: &self.patch, + crates: &self.crates, }; glue.write(out) } diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 9f72bbe09..1319afaca 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -118,6 +118,9 @@ pub struct Crate<'a> { /// The `[patch]` table the crate's own workspace resolves the exports with, as the /// check did. pub patch: &'a str, + /// The dependency on each crate the facade builds with, by its crate name, as this + /// host resolves it, which a staged API's crates are named by too. + pub crates: &'a std::collections::BTreeMap, } impl Crate<'_> { @@ -166,16 +169,26 @@ impl Crate<'_> { .collect(); // A crate the facade does not re-export, whose types an export names, as the facade // resolves it, so they are the facade's types. - let reached: String = (api.reached.iter()) - .map(|r| { - format!( - "{} = {{ {}, default-features = false }}\n", - reached(&r.krate), - r.dependency - ) - }) + // One only some targets' APIs name builds on those alone, as the facade's does. + let mut every = String::new(); + let mut targeted: std::collections::BTreeMap<&str, String> = Default::default(); + for r in &api.reached { + let Some(keys) = self.crates.get(&r.krate) else { + return Err(format!( + "the facade builds with no crate `{}` here, which the API names", + r.krate + )); + }; + let line = format!("{} = {{ {keys}, default-features = false }}\n", reached(&r.krate)); + match r.targets == api.targets { + true => every.push_str(&line), + false => (r.targets.iter()).for_each(|t| targeted.entry(t).or_default().push_str(&line)), + } + } + let targeted: String = (targeted.into_iter()) + .map(|(target, lines)| format!("[target.{target:?}.dependencies]\n{lines}\n")) .collect(); - let dependencies = format!("{dependencies}{foreign}{reached}"); + let dependencies = format!("{dependencies}{foreign}{every}"); // The facade's oldest toolchain is the crate's, which cargo sets as rustc compiles it, // though no older than the crate's edition needs; cargo checks the value's form. let rust_version = match std::env::var("CARGO_PKG_RUST_VERSION") { @@ -217,6 +230,7 @@ impl Crate<'_> { # What dart/{lib}.dart calls that `dart:ffi` lacks.\n\ dart = []\n\ \n\ + {targeted}\ [workspace]\n\ {patch}", patch = self.patch, diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 2b6ac4df7..e9ab45453 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -29,8 +29,8 @@ pub struct Api { pub struct Reached { /// Its crate name, its items' second path segment. pub krate: String, - /// Its dependency's TOML keys, which name the facade's package of it. - pub dependency: String, + /// The targets whose API names its types, sorted. + pub targets: Vec, } impl Api { diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 3ee4b0f03..e484262d3 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -343,8 +343,13 @@ impl Merged { self.api.crates.insert(at, krate.clone()); } for reached in api.reached { - if !self.api.reached.iter().any(|r| r.krate == reached.krate) { - self.api.reached.push(reached); + match self.api.reached.iter_mut().find(|r| r.krate == reached.krate) { + Some(ours) => { + ours.targets.extend(reached.targets); + ours.targets.sort(); + ours.targets.dedup(); + } + None => self.api.reached.push(reached), } } for (record, at) in api.records.into_iter().zip(maps.records) { From ab877c5c89d77df88b60081ce462436c0b20c27d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 15:07:37 -0800 Subject: [PATCH 05/26] test(ffi): merge a staged API whose reached crate only the exporting host resolves Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index dc9b1affc..948ced829 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1261,6 +1261,41 @@ fn unreached_types() { .arg("--manifest-path") .arg(out.join("Cargo.toml")) .env("CARGO_TARGET_DIR", package.join("build"))); + // Staged on another host, with the checkout elsewhere, the merged export depends on the + // exporting host's `kio`, not the staging host's, though only the staged target reaches it. + let staged = package.join("wasm.json"); + run(Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) + .arg("--config") + .arg(package.join("ffi.toml")) + .args(["--api", staged.to_str().unwrap(), "--target", WASM]) + .env("CARGO_TARGET_DIR", package.join("build"))); + let moved = scratch().join("unreached_types-moved"); + let _ = std::fs::remove_dir_all(&moved); + for dir in ["src", "kio"] { + copy_dir(&package.join(dir), &moved.join(dir)); + } + for file in ["Cargo.toml", "ffi.toml"] { + std::fs::copy(package.join(file), moved.join(file)).unwrap(); + } + std::fs::write( + moved.join("src/lib.rs"), + "pub use kio::Ready;\n\npub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", + ) + .unwrap(); + run(Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) + .arg("--config") + .arg(moved.join("ffi.toml")) + .arg("--out") + .arg(moved.join("out")) + .arg("--with") + .arg(&staged) + .env("CARGO_TARGET_DIR", moved.join("build"))); + let manifest = std::fs::read_to_string(moved.join("out/Cargo.toml")).unwrap(); + assert!( + manifest.contains(&format!("path = \"{}\"", moved.join("kio").display())) + && !manifest.contains(&package.join("kio").display().to_string()), + "{manifest}" + ); std::fs::write(package.join("ffi.toml"), "").unwrap(); let census = package.join("census"); let output = Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) From 9f78c9bfa99c5d6040dc13d49b97daf60cc14570 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 12 Nov 2026 15:54:56 -0800 Subject: [PATCH 06/26] test(ffi): compare the reached path as the manifest escapes it Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 948ced829..24c0d46e5 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1292,8 +1292,8 @@ fn unreached_types() { .env("CARGO_TARGET_DIR", moved.join("build"))); let manifest = std::fs::read_to_string(moved.join("out/Cargo.toml")).unwrap(); assert!( - manifest.contains(&format!("path = \"{}\"", moved.join("kio").display())) - && !manifest.contains(&package.join("kio").display().to_string()), + manifest.contains(&format!("path = {:?}", moved.join("kio").display().to_string())) + && !manifest.contains(&format!("{:?}", package.join("kio").display().to_string())), "{manifest}" ); std::fs::write(package.join("ffi.toml"), "").unwrap(); From f013ff611680f7aee4b42bf2b9b59e2babdf2a49 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:26:55 -0800 Subject: [PATCH 07/26] Resolve driver.rs merge: keep both crates and baseline Co-Authored-By: Claude Opus 5.5 --- ffi/src/driver.rs | 3 --- quest/m1/ffi-refusals/moq-pin.md | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index 35750e45a..62b5da9c8 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -118,7 +118,6 @@ impl Export { .map(str::to_string) .collect(); let patch = std::env::var(config::env::PATCH).map_err(|_| format!("{} is unset", config::env::PATCH))?; -<<<<<<< HEAD let crates = std::env::var(config::env::CRATES).map_err(|_| format!("{} is unset", config::env::CRATES))?; let crates: toml::Table = crates .parse() @@ -129,11 +128,9 @@ impl Export { _ => Err(format!("{} is malformed: {lib}", config::env::CRATES)), }) .collect::>()?; -======= let baseline = std::env::var_os(config::env::BASELINE) .filter(|p| !p.is_empty()) .map(PathBuf::from); ->>>>>>> origin/main Ok(Some(Self { crates, config, diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index c10c4410d..a56aeed9d 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -58,7 +58,7 @@ moq's `main` fails `just ts moq` and `just ffi moq-cpp`, so the bump waits on Wa Decided 2026-11-11 (maintainer, /quest-unblock): ✅ (a) rust2 exports a type the crate root does not reach by its defining path, such as `kio::Pending` and `lite::version::Version`; a type whose defining path is itself private stays refused (rejected: (b) moq makes both reachable). -[moq-dev/rust2#721](https://github.com/moq-dev/rust2/pull/721) made the exporter change: a +[kixel-ai/rust2#721](https://github.com/kixel-ai/rust2/pull/721) made the exporter change: a type a signature names that the root does not reach exports by its shortest public path in its own crate, so `kio::Pending` (defined in kio's private `pollable`) and moq-tokio's `cli::Deprecated` export, the glue naming them through its own dependency on their crate's From 41e26914d2119a0d5d025bda392a42ff4f2454b6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:17:56 -0800 Subject: [PATCH 08/26] fix(ffi): refuse a facade module named as another target's reached crate, and read an API without reached Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 29 ++++++----------- ffi/src/dart.rs | 6 ++-- ffi/src/ir.rs | 3 +- ffi/src/merge.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 24 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 22c13e57a..2c4fc42aa 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2037,8 +2037,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(); @@ -2062,9 +2061,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; @@ -2617,8 +2615,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 @@ -3545,8 +3542,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()))); } @@ -3890,16 +3886,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), diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 0318d9dc4..5f3876264 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -590,12 +590,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/ir.rs b/ffi/src/ir.rs index 47d996353..3c7d66359 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -18,7 +18,8 @@ pub struct Api { /// The crates items belong to, each after every crate it depends on. pub crates: Vec, /// The crates the facade does not re-export whose types an export names, which the - /// glue depends on directly. + /// glue depends on directly. An API from before it reached none. + #[serde(default)] pub reached: Vec, /// The targets it serves, sorted: one for a single target's, several merged. pub targets: Vec, diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index f804140bf..891ba6690 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -266,6 +266,53 @@ impl Merged { Differs { what, first, second } } + /// Refuse each item whose path's second segment names a reached crate on a target that + /// does not reach it: there it is a facade module of the same name, which the glue + /// would route to the reached crate, a dependency of the other targets only. + fn collisions(&mut self) { + let api = &self.api; + let mut items: Vec<(&Vec, On, Span)> = Vec::new(); + fn functions<'a>(fs: &'a [Function], items: &mut Vec<(&'a Vec, On, Span)>) { + fs.iter().for_each(|f| items.push((&f.path, f.on, f.span))) + } + for r in &api.records { + items.push((&r.path, r.on, r.span)); + functions(&r.methods, &mut items); + } + for e in &api.enums { + items.push((&e.path, e.on, e.span)); + functions(&e.methods, &mut items); + } + for o in &api.objects { + items.push((&o.path, o.on, o.span)); + functions(&o.methods, &mut items); + } + for c in &api.callbacks { + items.push((&c.path, c.on, c.span)); + functions(&c.methods, &mut items); + } + functions(&api.functions, &mut items); + api.constants.iter().for_each(|c| items.push((&c.path, c.on, c.span))); + let mut differs = Vec::new(); + for r in &api.reached { + let reaches = On((api.targets.iter().enumerate()) + .filter(|(_, t)| r.targets.contains(t)) + .fold(0, |on, (i, _)| on | 1 << i)); + for &(path, on, span) in &items { + let elsewhere = On(on.0 & !reaches.0); + if path.get(1) == Some(&r.krate) && elsewhere.0 != 0 { + let what = format!( + "`{}`, whose `{}` is a crate on one and a module on the other", + path.join("::"), + r.krate + ); + differs.push(self.differs(what, (reaches, span), (elsewhere, span))); + } + } + } + self.differs.extend(differs); + } + /// The merged API, and what differs between its targets, once every target is added. fn finish(mut self) -> (Api, Vec) { let renumbered = std::mem::take(&mut self.renumbered); @@ -288,6 +335,7 @@ impl Merged { } } } + self.collisions(); match order_crates(&self.api) { Ok(crates) => self.api.crates = crates, Err(cycle) => { @@ -763,4 +811,37 @@ mod tests { }; assert_eq!((cycle.first.0.0, cycle.second.0.0), (2, 1)); } + + #[test] + fn refuses_a_facade_module_named_as_another_targets_reached_crate() { + // On `x`, `f::kio` is the reached crate `kio`; on `y`, a module of the facade. + let api = |target: &str, reached: bool| Api { + records: Vec::new(), + enums: Vec::new(), + objects: Vec::new(), + callbacks: Vec::new(), + functions: Vec::new(), + constants: vec![crate::ir::Constant { + path: ["f", "kio", "N"].map(String::from).to_vec(), + home: Home::default(), + span: DUMMY_SP, + on: On::ALL, + docs: String::new(), + value: crate::ir::Literal::Bool(true), + }], + crates: vec!["f".into()], + reached: (reached.then(|| crate::ir::Reached { + krate: "kio".into(), + targets: vec![target.into()], + })) + .into_iter() + .collect(), + targets: vec![target.into()], + }; + let (_, differs) = super::merge(vec![api("x", true), api("y", false)]); + assert_eq!(differs.len(), 1); + assert_eq!((differs[0].first.0.as_str(), differs[0].second.0.as_str()), ("x", "y")); + let (_, differs) = super::merge(vec![api("x", true), api("y", true)]); + assert!(differs.is_empty()); + } } From 6f12f5132e99c7c6afa428f96271eafc70a37c59 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:21:27 -0800 Subject: [PATCH 09/26] style: restore unrelated formatting Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 29 +++++++++++++++++++---------- ffi/src/dart.rs | 6 ++++-- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 2c4fc42aa..22c13e57a 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2037,7 +2037,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(); @@ -2061,8 +2062,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; @@ -2615,7 +2617,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 @@ -3542,7 +3545,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()))); } @@ -3886,11 +3890,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), diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 5f3876264..0318d9dc4 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -590,10 +590,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 ) } From 8fc9dee6a0198d9f15cd3e72140f3ad327957e0f Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:40:11 -0800 Subject: [PATCH 10/26] fix(ffi): decode a git source's percent-encoded reference --- ffi/src/cli.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/ffi/src/cli.rs b/ffi/src/cli.rs index ea73b95bc..e8ae97eb0 100644 --- a/ffi/src/cli.rs +++ b/ffi/src/cli.rs @@ -374,7 +374,7 @@ fn dependency(package: &Package) -> Option { let url = git["git+".len()..].split('#').next().unwrap_or(git); let (url, reference) = url.split_once('?').unwrap_or((url, "")); let reference = match reference.split_once('=') { - Some((key @ ("branch" | "tag" | "rev"), value)) => format!(", {key} = {value:?}"), + Some((key @ ("branch" | "tag" | "rev"), value)) => format!(", {key} = {:?}", decode(value)?), Some(_) => return None, None => String::new(), }; @@ -384,6 +384,34 @@ fn dependency(package: &Package) -> Option { } } +/// `value` with each `%XX` cargo's source id escapes, as in `?branch=feature%2Fpending`, +/// decoded, or `None` if it is malformed. +fn decode(value: &str) -> Option { + let mut bytes = Vec::with_capacity(value.len()); + let mut rest = value.as_bytes(); + while let [first, tail @ ..] = rest { + if *first == b'%' { + let hex = std::str::from_utf8(tail.get(..2)?).ok()?; + bytes.push(u8::from_str_radix(hex, 16).ok()?); + rest = &tail[2..]; + } else { + bytes.push(*first); + rest = tail; + } + } + String::from_utf8(bytes).ok() +} + +#[cfg(test)] +mod decode_tests { + #[test] + fn decodes_a_branch() { + assert_eq!(super::decode("feature%2Fpending").as_deref(), Some("feature/pending")); + assert_eq!(super::decode("main").as_deref(), Some("main")); + assert_eq!(super::decode("bad%2"), None); + } +} + /// The `[patch]` the glue's workspace resolves the exports by as the check did, wherever /// it builds, as TOML with each path absolute. fn overrides(metadata: &Metadata, top: &Package) -> Result { From 71c81964a9dfb030fb5d30a4745e1e433ff52362 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:02:49 -0800 Subject: [PATCH 11/26] feat(ffi): reach a type from a crate the facade exports nothing else from Discovery now runs ahead of the foreign-type refusal. A crate reached only through signatures keeps its error crossing as its message and its Arc'd types as opaque handles; a probe of a mapping reaches nothing. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 15 +++- ffi/fixtures/api/examples/transcript.rs | 3 + ffi/fixtures/api/src/lib.rs | 10 ++- ffi/fixtures/tls/src/lib.rs | 58 ++++++++++++++- ffi/src/collect.rs | 98 ++++++++++++++++++++----- ffi/tests/fixtures.rs | 65 ++++++++++++---- 6 files changed, 213 insertions(+), 36 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 07563cb96..da2a82fb1 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -18,7 +18,8 @@ is a nightly. The package is the facade: once rustc has checked its library, it reachable from the crate root, following `pub use` re-exports of other crates' items and modules, and exports it by fixed rules, or refuses it with a compile error at its span. So a facade such as moq-ffi exports several crates into one library by re-exporting what -it ships, and a type no path from its root reaches is refused. The prefix of every C name +it ships; a type a signature names that no path from its root reaches exports by its +public path in its own crate ([Rules](#rules)). The prefix of every C name is the library's crate name, Cargo's `[lib] name`, which defaults to the package's name in snake case. `--out` writes a crate of `extern "C"` functions over the facade, its runtime beside it, and the header in `include/.h`; `cargo build` on that crate makes a @@ -65,7 +66,17 @@ export nothing of their own. A re-export of the standard library's item is refus its types map by role. A `pub use` of a whole crate, as in `pub use rustls;` or `pub use web_transport_proto as proto;`, is refused once at that `pub use`, since it puts every release of that crate in the facade's API; a glob of its root, `pub use dep::*;`, -re-exports its items instead, which export. A type no path reaches is refused. +re-exports its items instead, which export. + +A type an export's signature names that no path from the root reaches, as moq-net's +`dial_tcp` returns kio's `Pending`, exports by its shortest public path in its own crate, +`::::`, through that crate's modules and re-exports, with what its own +signatures name in turn. This holds whether or not the facade re-exports anything else of +that crate. The glue depends on that crate directly, as the facade resolves it; a crate +another of its name shares, the facade's root names, or another registry serves is not +reached. A crate only signatures reach keeps the roles of one no export is: its error in a +`Result` crosses as its message, and its type behind an `Arc` as an opaque handle, refused +bare. A type no public path names stays refused. | Rust | C | | --- | --- | diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 1edb74dd6..c2bc3587c 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -583,6 +583,9 @@ fn main() { println!("nudge {} {}", point.x, point.y); let config = api::secure("h3"); println!("secure {} {}", api::alpn_lent(&config), api::alpn(config.clone())); + let session = api::resume("h3", 60).unwrap(); + println!("resume {} {}", session.alpn(), session.lifetime().seconds); + println!("resume err {}", api::resume("", 60).err().unwrap()); let mut meters = api::Meters::new(); let first = meters.first(); first.add(2); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 5faf446d3..e90897c8f 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2154,8 +2154,8 @@ pub fn nudge(point: &mut Point, by: i32) { point.y += by; } -/// A config of a crate no export is, behind an `Arc`, as moq-tokio's listener returns -/// rustls's: an opaque handle, which Rust takes back. +/// A config of a crate the facade re-exports nothing from, behind an `Arc`, as moq-tokio's +/// listener returns rustls's: an opaque handle, which Rust takes back. pub fn secure(alpn: &str) -> Arc { Arc::new(tls::Config::new(alpn)) } @@ -2170,6 +2170,12 @@ pub fn alpn_lent(config: &Arc) -> String { config.alpn().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. +pub fn resume(alpn: &str, seconds: u32) -> Result { + tls::resume(alpn, seconds) +} + /// `text`'s length, or 0 for none: an optional borrow, lent as the borrow alone is. pub fn either(text: Option<&str>) -> usize { text.map_or(0, str::len) diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index a951ec613..a083fcd6b 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -1,5 +1,5 @@ -//! A crate the api fixture names behind an `Arc` but does not re-export, as moq-tokio's -//! listener names rustls's server config. +//! A crate the api fixture names in signatures but re-exports nothing from, as moq-tokio's +//! listener names rustls's server config and moq-net's `dial_tcp` names kio's `Pending`. /// A config: an opaque handle wherever the api fixture returns or takes an `Arc` of it. #[derive(Debug)] @@ -16,3 +16,57 @@ impl Config { &self.alpn } } + +mod session { + use crate::policy::Lifetime; + + /// A session: an object of a private module, which the api fixture returns bare and no + /// re-export names, so it exports by its path in this crate. + pub struct Session { + alpn: String, + lifetime: Lifetime, + } + + impl Session { + pub fn alpn(&self) -> String { + self.alpn.clone() + } + + /// A record only this method names, which exports once the session does. + pub fn lifetime(&self) -> Lifetime { + self.lifetime + } + } + + /// A session of `alpn` lasting `seconds`, or an error when `alpn` is empty. + pub fn resume(alpn: &str, seconds: u32) -> Result { + if alpn.is_empty() { + return Err(crate::Error("no protocol to resume".to_string())); + } + Ok(Session { + alpn: alpn.to_string(), + lifetime: Lifetime { seconds }, + }) + } +} + +pub use session::{Session, resume}; + +pub mod policy { + /// How long a session lasts. + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Lifetime { + pub seconds: u32, + } +} + +/// An error, which the api fixture returns only as a `Result`'s, so it crosses as its +/// message. +#[derive(Debug)] +pub struct Error(String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 22c13e57a..8d69912b2 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -235,6 +235,8 @@ struct Collector<'tcx> { inferring: bool, /// The crates of the items the walk reached, the facade's first. crates: Vec, + /// How many of `crates` the walk from the root reached, before any reached type's. + walked: usize, report: Report, /// Items the walk left out, and why: `excluded` or `doc(hidden)`. left_out: rustc_data_structures::fx::FxHashMap, @@ -267,6 +269,14 @@ struct Collector<'tcx> { dependencies: std::collections::BTreeMap, /// Such types this pass met that `reach` lacks. unreached: std::cell::RefCell>, + /// Types an opaque `Arc` holds that a signature also names bare, which stay refused + /// rather than export twice. + barred: Vec, + /// Whether the type being mapped is a `Result`'s error, which never reaches a type. + erring: std::cell::Cell, + /// Whether the type being mapped is only tried, as a candidate or before another rule, + /// whose failure reaches no type. + probing: std::cell::Cell, api: Api, } @@ -343,7 +353,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { }; keys.insert(krate, key); } - let pass = |orphans: &rustc_data_structures::fx::FxHashSet>, reach: &[DefId]| { + let pass = |orphans: &rustc_data_structures::fx::FxHashSet>, reach: &[DefId], barred: &[DefId]| { let mut c = Collector { tcx, items: Vec::new(), @@ -351,6 +361,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { keys: keys.clone(), decls: Default::default(), crates: vec![LOCAL_CRATE], + walked: 1, report: Report { package: facade.package.to_string(), root: facade.root.clone(), @@ -380,6 +391,9 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { reach: reach.to_vec(), dependencies: facade.crates.clone(), unreached: Default::default(), + barred: barred.to_vec(), + erring: Default::default(), + probing: Default::default(), api: Api { records: Vec::new(), enums: Vec::new(), @@ -401,7 +415,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { .collect(); c.level = level .filter(|&(level, filter)| { - !c.exported(level.krate) && !c.items.iter().any(|(item, _)| *item == level || *item == filter) + !c.walked(level.krate) && !c.items.iter().any(|(item, _)| *item == level || *item == filter) }) .map(|(level, filter)| Level { level, @@ -422,10 +436,24 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { // signatures may name more. let mut orphans = rustc_data_structures::fx::FxHashSet::default(); let mut reach = Vec::new(); + let mut barred = Vec::new(); loop { - let c = pass(&orphans, &reach); + let c = pass(&orphans, &reach, &barred); + // A reached type an opaque `Arc` also holds would export twice, so it stays refused, + // as it was before its crate was reached. + let held: Vec = (reach.iter().copied()) + .filter(|&did| c.foreign.iter().any(|&(other, _)| other == did)) + .collect(); + if !held.is_empty() { + reach.retain(|did| !held.contains(did)); + barred.extend(held); + orphans.clear(); + continue; + } let more = c.orphans(); - let unreached = c.unreached.take(); + let unreached: Vec = (c.unreached.take().into_iter()) + .filter(|&did| !c.foreign.iter().any(|&(other, _)| other == did)) + .collect(); if more.is_empty() && unreached.is_empty() { return Collected { api: c.api, @@ -601,6 +629,13 @@ impl<'tcx> Collector<'tcx> { self.crates.contains(&krate) } + /// Whether the walk from the root reached an item of `krate`. A crate only signatures + /// reach keeps the roles of one no export is: its error crosses as its message, and an + /// `Arc` of its type as an opaque handle. + fn walked(&self, krate: CrateNum) -> bool { + self.crates[..self.walked].contains(&krate) + } + /// Whether the config excludes `path`, counting the exclusion. A member of an instance /// is left out by its instance's path or its type's, which leaves it out of each. fn exclude(&mut self, path: &[String]) -> bool { @@ -846,7 +881,7 @@ impl<'tcx> Collector<'tcx> { }; let did = adt.did(); let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); - let held = !self.exported(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; + 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) } @@ -1234,6 +1269,7 @@ impl<'tcx> Collector<'tcx> { /// a module of the facade re-exported that crate's root. fn walk_reach(&mut self, seen: &rustc_data_structures::fx::FxHashSet) { let tcx = self.tcx; + self.walked = self.crates.len(); for def_id in self.reach.clone() { if seen.contains(&def_id) { continue; @@ -1280,6 +1316,9 @@ impl<'tcx> Collector<'tcx> { if def_id.is_local() { return true; } + if self.barred.contains(&def_id) || self.sysroot.contains(&def_id.krate) { + return false; + } let name = tcx.crate_name(def_id.krate); let root = tcx.module_children_local(LOCAL_CRATE.as_def_id().expect_local()); self.keys[&def_id.krate] == name.as_str() @@ -1287,6 +1326,18 @@ impl<'tcx> Collector<'tcx> { && self.dependencies.contains_key(name.as_str()) } + /// Walk `def_id` by its public path in its own crate in the next pass, unless the type + /// being mapped is only tried. + fn reached(&self, def_id: DefId) { + if self.probing.get() { + return; + } + let mut unreached = self.unreached.borrow_mut(); + if !unreached.contains(&def_id) { + unreached.push(def_id); + } + } + /// The shortest public path to `def_id` from its own crate's root, through that crate's /// modules and re-exports, as `kio::Pending` names one defined in a private module. fn crate_path(&self, def_id: DefId) -> Option> { @@ -2776,7 +2827,7 @@ impl<'tcx> Collector<'tcx> { // refused. let mut collect = false; if !future - && self.ret(output).is_err() + && self.probe(|| self.ret(output)).is_err() && let Some(items) = self .collected(output, env) .and_then(|item| self.vec_of(normalize(item))) @@ -2797,8 +2848,12 @@ impl<'tcx> Collector<'tcx> { ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => { let error = args.type_at(1); // Another crate's error, such as `anyhow::Error` or `io::Error`, crosses as - // its message, as an exported error's `Display` already reads. - let err = match self.ty(error, Pos::Return) { + // its message, as an exported error's `Display` already reads, even where a + // signature reaches its crate. + self.erring.set(true); + let err = self.ty(error, Pos::Return); + self.erring.set(false); + let err = match err { Err(why) if why.construct == "foreign type" && implements(tcx, error, def_id, rustc_span::sym::Display) => @@ -3483,7 +3538,15 @@ impl<'tcx> Collector<'tcx> { /// Whether `ty` maps where `pos` puts it. While inferring, before any type is declared, /// one naming an export's type does. fn maps(&self, ty: Ty<'tcx>, pos: Pos) -> bool { - (self.inferring && self.names_export(ty)) || self.ty(ty, pos).is_ok() + (self.inferring && self.names_export(ty)) || self.probe(|| self.ty(ty, pos)).is_ok() + } + + /// `map`, reaching no type a refusal names. + fn probe(&self, map: impl FnOnce() -> T) -> T { + let was = self.probing.replace(true); + let mapped = map(); + self.probing.set(was); + mapped } /// Whether `ty` names an export's type, which maps only once declared. @@ -4502,9 +4565,8 @@ impl<'tcx> Collector<'tcx> { .then_some(Collection::BTreeMap) }) // serde_json's own, unless serde_json is an export. - .or_else(|| { - (Some(did) == self.json_map && !self.exported(did.krate)).then_some(Collection::JsonMap) - }) { + .or_else(|| (Some(did) == self.json_map && !self.walked(did.krate)).then_some(Collection::JsonMap)) + { // A set crosses as its items, and a map as its pairs, in order. let inner = match c { Collection::BTreeSet => self.ty(args.type_at(0), pos.inner())?, @@ -4627,7 +4689,12 @@ impl<'tcx> Collector<'tcx> { None => return Err(why("Arc", strip_args(tcx, did))), }, } - } else if !self.exported(did.krate) { + } else if !self.walked(did.krate) && (self.erring.get() || !self.reach.contains(&did)) { + // One public in its own crate exports by that path, in the next pass, unless + // it is an error, which crosses as its message. + if !self.erring.get() && !self.reach.contains(&did) && self.reachable(did) { + self.reached(did); + } return Err(why("foreign type", strip_args(tcx, did))); } else { let key = self.key(did, args); @@ -4669,10 +4736,7 @@ impl<'tcx> Collector<'tcx> { } // One public in its own crate exports by that path, in the next pass. if !self.reach.contains(&did) && self.reachable(did) { - let mut unreached = self.unreached.borrow_mut(); - if !unreached.contains(&did) { - unreached.push(did); - } + self.reached(did); } return Err(why("type not reachable from the crate root", name)); } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 959d61ad5..77af43903 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1242,8 +1242,10 @@ fn go_package_names() { } /// A type a signature names that the root does not reach, as moq-net's `kio::Pending`, -/// exports by its public path in its own crate, through a re-export or a module; one no public -/// path names stays refused. +/// exports by its public path in its own crate, through a re-export or a module, even from a +/// crate the facade re-exports nothing from; one no public path names stays refused. Such a +/// crate's error still crosses as its message, and its type an `Arc` holds stays an opaque +/// handle, refused bare. #[test] fn unreached_types() { let package = package("unreached_types"); @@ -1253,13 +1255,32 @@ fn unreached_types() { ( "Cargo.toml", "[package]\nname = \"unreached_types\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"pkg\"\n\n\ - [dependencies]\nkio = { package = \"unreached-kio\", path = \"kio\" }\n\n[workspace]\nexclude = [\"kio\"]\n", + [dependencies]\nkio = { package = \"unreached-kio\", path = \"kio\" }\n\ + net = { package = \"unreached-net\", path = \"net\" }\n\n[workspace]\nexclude = [\"kio\", \"net\"]\n", ), ( "src/lib.rs", "pub use kio::Ready;\n\npub fn pending() -> kio::Pending {\n\tkio::Pending(1)\n}\n\n\ pub fn version() -> kio::version::Version {\n\tkio::version::Version { major: 2 }\n}\n\n\ - pub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", + pub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n\n\ + pub fn connect() -> Result {\n\tnet::connect()\n}\n\n\ + pub fn handle() -> std::sync::Arc {\n\tstd::sync::Arc::new(net::Handle(4))\n}\n\n\ + pub fn bare(handle: &net::Handle) -> u32 {\n\thandle.0\n}\n\n\ + pub fn opaque() -> Result<(), net::Opaque> {\n\tErr(net::Opaque)\n}\n\n\ + pub fn closed() -> net::Closed {\n\tnet::closed()\n}\n", + ), + ( + "net/Cargo.toml", + "[package]\nname = \"unreached-net\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"net\"\n", + ), + ( + "net/src/lib.rs", + "mod link {\n\tpub struct Link(pub u32);\n\n\timpl Link {\n\t\tpub fn id(&self) -> u32 {\n\t\t\tself.0\n\t\t}\n\t}\n}\n\n\ + pub use link::Link;\n\npub struct Handle(pub u32);\n\n#[derive(Debug)]\npub struct Fault;\n\n\ + impl std::fmt::Display for Fault {\n\tfn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\t\tf.write_str(\"fault\")\n\t}\n}\n\n\ + pub struct Opaque;\n\nmod closed {\n\tpub struct Closed;\n}\n\npub type Closed = closed::Closed;\n\n\ + pub fn closed() -> closed::Closed {\n\tclosed::Closed\n}\n\n\ + pub fn connect() -> Result {\n\tOk(Link(1))\n}\n", ), ( "kio/Cargo.toml", @@ -1275,7 +1296,11 @@ fn unreached_types() { ], ); // The export builds, naming `kio`'s types through its own dependency on `kio`. - std::fs::write(package.join("ffi.toml"), "exclude = [\"seal\"]\n").unwrap(); + std::fs::write( + package.join("ffi.toml"), + "exclude = [\"seal\", \"bare\", \"opaque\", \"closed\"]\n", + ) + .unwrap(); let out = package.join("out"); run(Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) .arg("--config") @@ -1285,6 +1310,11 @@ fn unreached_types() { .env("CARGO_TARGET_DIR", package.join("build"))); let glue = std::fs::read_to_string(out.join("src/lib.rs")).unwrap(); assert!(glue.contains("::kio_reached::Pending"), "{glue}"); + // `net`'s error crosses as its message, and its `Arc` as an opaque handle. + assert!( + glue.contains("::net_reached::Link") && !glue.contains("Fault") && !glue.contains("net_reached::Handle"), + "{glue}" + ); run(cargo() .arg("build") .arg("--manifest-path") @@ -1300,17 +1330,16 @@ fn unreached_types() { .env("CARGO_TARGET_DIR", package.join("build"))); let moved = scratch().join("unreached_types-moved"); let _ = std::fs::remove_dir_all(&moved); - for dir in ["src", "kio"] { + for dir in ["src", "kio", "net"] { copy_dir(&package.join(dir), &moved.join(dir)); } for file in ["Cargo.toml", "ffi.toml"] { std::fs::copy(package.join(file), moved.join(file)).unwrap(); } - std::fs::write( - moved.join("src/lib.rs"), - "pub use kio::Ready;\n\npub fn seal() -> kio::Sealed {\n\tkio::sealed()\n}\n", - ) - .unwrap(); + let lib = std::fs::read_to_string(package.join("src/lib.rs")).unwrap(); + let (head, rest) = lib.split_once("pub fn pending").unwrap(); + let rest = &rest[rest.find("pub fn seal").unwrap()..]; + std::fs::write(moved.join("src/lib.rs"), format!("{head}{rest}")).unwrap(); run(Command::new(env!("CARGO_BIN_EXE_rust2-ffi")) .arg("--config") .arg(moved.join("ffi.toml")) @@ -1341,8 +1370,18 @@ fn unreached_types() { String::from_utf8_lossy(&output.stderr) ); let report = std::fs::read_to_string(census.join("unreached_types.md")).unwrap(); - // `Pending` and `Version` export; `Sealed` alone is refused, though an alias names it. - assert!(report.contains("| Types | 2 | 0 |"), "{report}"); + // `Pending`, `Version`, and `Link` export; `Sealed` alone is refused as unreached, though + // an alias names it. + assert!(report.contains("| Types | 3 | 0 |"), "{report}"); + // A type an `Arc` holds, a `Result`'s error without `Display`, and one no public path + // names stay refused as foreign. + for refused in [ + "fn `bare` at src/lib.rs:23:1: foreign type `net::Handle`", + "fn `opaque` at src/lib.rs:27:1: foreign type `net::Opaque`", + "fn `closed` at src/lib.rs:31:1: foreign type `net::closed::Closed`", + ] { + assert!(report.contains(refused), "{report}"); + } assert!( report.contains("fn `seal` at src/lib.rs:11:1: type not reachable from the crate root `kio::sealed::Sealed`"), "{report}" From 5ec628d709544b4ace19cd1cd1f40e0e744fb420 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:12:20 -0800 Subject: [PATCH 12/26] test(ffi): drive the reached tls session from every binding Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.c | 14 ++++++++++++++ ffi/tests/api.cpp | 4 ++++ ffi/tests/api.dart | 8 ++++++++ ffi/tests/api.go | 6 ++++++ ffi/tests/api.kt | 6 ++++++ ffi/tests/api.py | 6 ++++++ ffi/tests/api.swift | 9 +++++++++ 7 files changed, 53 insertions(+) diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 0991381bc..7b76659f2 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1302,6 +1302,20 @@ static int script(void) { print("", api_alpn(config_copy), "\n"); api_tls_Config_free(config_copy); api_tls_Config_free(config); + /* Another crate's type only signatures name, exported by its path there, and its error, + * which crosses as its message. */ + api_tls_Session *session; + api_buf session_err; + if (!api_resume(str("h3"), 60, &session, &session_err)) { + return 1; + } + print("resume ", api_tls_Session_alpn(session), " "); + printf("%u\n", api_tls_Session_lifetime(session).seconds); + api_tls_Session_free(session); + if (api_resume(str(""), 60, &session, &session_err)) { + return 1; + } + print("resume err ", session_err, "\n"); /* A borrow of a meter that is not Clone, lent from its owner's handle. */ { api_Meters *lender = api_Meters_new(); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 84c3f8f34..b6fd47889 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -838,6 +838,10 @@ int script() { auto config = api::secure("h3"); print("secure ", api::alpn_lent(config), " "); print("", api::alpn(config), "\n"); + auto session = api::resume("h3", 60); + print("resume ", session.value().alpn(), " "); + std::printf("%u\n", unsigned(session.value().lifetime().seconds)); + print("resume err ", api::resume("", 60).error(), "\n"); auto meters = api::Meters::new_(); auto first = meters.first(); first.add(2); diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 0368de51b..e42486706 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -536,6 +536,14 @@ Future script() async { final config = api.secure('h3'); print('secure ${api.alpnLent(config)} ${api.alpn(config.clone())}'); config.close(); + final session = api.resume('h3', 60); + print('resume ${session.alpn()} ${session.lifetime().seconds}'); + session.close(); + try { + api.resume('', 60); + } on api.StringException catch (e) { + print('resume err ${e.error}'); + } final meters = api.Meters(); final lentMeter = meters.first(); lentMeter.add(2); diff --git a/ffi/tests/api.go b/ffi/tests/api.go index d185b44e0..15db6b233 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -631,6 +631,12 @@ func script() { fmt.Printf("nudge %d %d\n", nudged.X, nudged.Y) config := api.Secure("h3") fmt.Printf("secure %s %s\n", must(api.AlpnLent(config)), must(api.Alpn(must(config.Clone())))) + session := must(api.Resume("h3", 60)) + fmt.Printf("resume %s %d\n", must(session.Alpn()), must(session.Lifetime()).Seconds) + session.Close() + if _, err := api.Resume("", 60); err != nil { + fmt.Printf("resume err %s\n", err) + } meters := api.NewMeters() meter := must(meters.First()) _ = must(meter.Add(2)) diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 7ca61d341..ff0fb01d9 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -462,6 +462,12 @@ fun script() { nudge(nudged, 3) println("nudge ${nudged.value.x} ${nudged.value.y}") secure("h3").use { config -> println("secure ${alpnLent(config)} ${alpn(config.clone())}") } + resume("h3", 60u).use { session -> println("resume ${session.alpn()} ${session.lifetime().seconds}") } + try { + resume("", 60u) + } catch (e: StringException) { + println("resume err ${e.error}") + } Meters.new().use { meters -> meters.first().use { first -> first.add(2uL) diff --git a/ffi/tests/api.py b/ffi/tests/api.py index c41763bc0..b12e356d5 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -544,6 +544,12 @@ async def polls(): print(f"nudge {nudged.value.x} {nudged.value.y}") config = api.secure("h3") print(f"secure {api.alpn_lent(config)} {api.alpn(config.clone())}") + session = api.resume("h3", 60) + print(f"resume {session.alpn()} {session.lifetime().seconds}") + try: + api.resume("", 60) + except api.StringException as e: + print(f"resume err {e.error}") meters = api.Meters.new() first = meters.first() first.add(2) diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index b218f56c7..5e9c54197 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -634,6 +634,15 @@ func script() { do { let config = secure("h3") print("secure \(alpnLent(config)) \(alpn(config.clone()))") + let session = try! resume("h3", 60) + print("resume \(session.alpn()) \(session.lifetime().seconds)") + do { + _ = try resume("", 60) + } catch let e as StringError { + print("resume err \(e.error)") + } catch { + check(false, "resume throws its message") + } var meters = Meters.new() let first = meters.first() _ = first.add(2) From 5f6fb5e51368dbb12e8928399a3b345f3767be5b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:22:33 -0800 Subject: [PATCH 13/26] fix(ffi): never reach another crate's error, and depend on a reached crate only once walked A field of an exported error, such as moq-mux's fmp4::Error holding mp4_atom::Codec or moq_mux::Error holding moq_json::Error, reached those types, turning foreign errors into exported objects. The stand-in config leaves out mp4_atom, which only an error variant reaches. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 4 +++- ffi/moq/ffi.toml | 1 + ffi/src/collect.rs | 26 ++++++++++++++++---------- ffi/tests/fixtures.rs | 15 ++++++++++----- 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index da2a82fb1..5ce615cdb 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -76,7 +76,9 @@ that crate. The glue depends on that crate directly, as the facade resolves it; another of its name shares, the facade's root names, or another registry serves is not reached. A crate only signatures reach keeps the roles of one no export is: its error in a `Result` crosses as its message, and its type behind an `Arc` as an opaque handle, refused -bare. A type no public path names stays refused. +bare. Its errors, the types implementing `std::error::Error`, are never reached, so an +exported error holding one is an object, as it was. A type no public path names stays +refused. | Rust | C | | --- | --- | diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index 495076140..389e7af81 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -15,6 +15,7 @@ exclude = [ "hang::container::Frame::encode", "hang::moq_net", "kio", + "mp4_atom", "mux::catalog::Guard", "mux::catalog::Producer::modify", "mux::catalog::Producer::modify", diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 8d69912b2..e039eaf88 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -630,8 +630,8 @@ impl<'tcx> Collector<'tcx> { } /// Whether the walk from the root reached an item of `krate`. A crate only signatures - /// reach keeps the roles of one no export is: its error crosses as its message, and an - /// `Arc` of its type as an opaque handle. + /// reach keeps the roles of one no export is: its errors are never reached, one in a + /// `Result` crossing as its message, and an `Arc` of its type crosses as an opaque handle. fn walked(&self, krate: CrateNum) -> bool { self.crates[..self.walked].contains(&krate) } @@ -1280,12 +1280,6 @@ impl<'tcx> Collector<'tcx> { } let own = self.crate_path(def_id).expect("a reached type has a path in its crate"); let outside = path.len(); - if !def_id.is_local() && !self.api.reached.iter().any(|r| r.krate == path[1]) { - self.api.reached.push(crate::ir::Reached { - krate: path[1].clone(), - targets: self.api.targets.clone(), - }); - } path.extend(own); if self.exclude(&path) { self.left_out.insert(def_id, "excluded type"); @@ -1297,6 +1291,13 @@ impl<'tcx> Collector<'tcx> { self.left_out.insert(def_id, "doc(hidden) type"); continue; } + // The glue depends on its crate only once a type of it is walked. + if !def_id.is_local() && !self.api.reached.iter().any(|r| r.krate == path[1]) { + self.api.reached.push(crate::ir::Reached { + krate: path[1].clone(), + targets: self.api.targets.clone(), + }); + } if !self.crates.contains(&def_id.krate) { self.crates.push(def_id.krate); } @@ -4691,8 +4692,13 @@ impl<'tcx> Collector<'tcx> { } } else if !self.walked(did.krate) && (self.erring.get() || !self.reach.contains(&did)) { // One public in its own crate exports by that path, in the next pass, unless - // it is an error, which crosses as its message. - if !self.erring.get() && !self.reach.contains(&did) && self.reachable(did) { + // it is an error: one in a `Result` crosses as its message, and one elsewhere, + // such as in an exported error's variant, stays refused. + if !self.erring.get() + && !self.reach.contains(&did) + && self.reachable(did) + && !implements(tcx, ty, did, rustc_span::Symbol::intern("Error")) + { self.reached(did); } return Err(why("foreign type", strip_args(tcx, did))); diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 77af43903..5ea3836f0 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1267,7 +1267,8 @@ fn unreached_types() { pub fn handle() -> std::sync::Arc {\n\tstd::sync::Arc::new(net::Handle(4))\n}\n\n\ pub fn bare(handle: &net::Handle) -> u32 {\n\thandle.0\n}\n\n\ pub fn opaque() -> Result<(), net::Opaque> {\n\tErr(net::Opaque)\n}\n\n\ - pub fn closed() -> net::Closed {\n\tnet::closed()\n}\n", + pub fn closed() -> net::Closed {\n\tnet::closed()\n}\n\n\ + pub enum Failure {\n\tNet(net::Fault),\n}\n\npub fn fail() -> Failure {\n\tFailure::Net(net::Fault)\n}\n", ), ( "net/Cargo.toml", @@ -1278,6 +1279,7 @@ fn unreached_types() { "mod link {\n\tpub struct Link(pub u32);\n\n\timpl Link {\n\t\tpub fn id(&self) -> u32 {\n\t\t\tself.0\n\t\t}\n\t}\n}\n\n\ pub use link::Link;\n\npub struct Handle(pub u32);\n\n#[derive(Debug)]\npub struct Fault;\n\n\ impl std::fmt::Display for Fault {\n\tfn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\t\tf.write_str(\"fault\")\n\t}\n}\n\n\ + impl std::error::Error for Fault {}\n\n\ pub struct Opaque;\n\nmod closed {\n\tpub struct Closed;\n}\n\npub type Closed = closed::Closed;\n\n\ pub fn closed() -> closed::Closed {\n\tclosed::Closed\n}\n\n\ pub fn connect() -> Result {\n\tOk(Link(1))\n}\n", @@ -1310,7 +1312,8 @@ fn unreached_types() { .env("CARGO_TARGET_DIR", package.join("build"))); let glue = std::fs::read_to_string(out.join("src/lib.rs")).unwrap(); assert!(glue.contains("::kio_reached::Pending"), "{glue}"); - // `net`'s error crosses as its message, and its `Arc` as an opaque handle. + // `net`'s error crosses as its message, or holds `Failure`, which holds it, an object, and + // its `Arc` crosses as an opaque handle. assert!( glue.contains("::net_reached::Link") && !glue.contains("Fault") && !glue.contains("net_reached::Handle"), "{glue}" @@ -1370,9 +1373,11 @@ fn unreached_types() { String::from_utf8_lossy(&output.stderr) ); let report = std::fs::read_to_string(census.join("unreached_types.md")).unwrap(); - // `Pending`, `Version`, and `Link` export; `Sealed` alone is refused as unreached, though - // an alias names it. - assert!(report.contains("| Types | 3 | 0 |"), "{report}"); + // `Pending`, `Version`, `Link`, and `Failure` export; `Sealed` alone is refused as + // unreached, though an alias names it. `net`'s error in `Failure` is never reached, so + // `Failure` is an object. + assert!(report.contains("| Types | 4 | 0 |"), "{report}"); + assert!(report.contains("- `Failure`: foreign type `net::Fault`"), "{report}"); // A type an `Arc` holds, a `Result`'s error without `Display`, and one no public path // names stay refused as foreign. for refused in [ From 10490878abc3b5b6c9d6ef6903504114171b1fd2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:22:40 -0800 Subject: [PATCH 14/26] docs(ffi): say why the stand-in leaves out mp4_atom Co-Authored-By: Claude Opus 5.5 --- ffi/moq/ffi.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index 389e7af81..157044998 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -1,7 +1,8 @@ # What the export refuses at the pinned revision, by paths from the stand-in facade that # `just ffi standin` writes, as `just ffi census` lists it: the API a hand-written wrapper # still has to cover. `kio` is moq-net's re-export of all of kio, of which moq-ffi ships -# only what the facade re-exports. +# only what the facade re-exports. `mp4_atom` is the crate mux's `container::fmp4::Error` +# names in a variant, which reaches its every box. exclude = [ "bytes", "Client::connect", From 9be1612edde45992680500baa9b3dd337d2b9603 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:42:41 -0800 Subject: [PATCH 15/26] quest(moq-pin): record the decision to reach signature-only crates Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-refusals/moq-pin.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index a56aeed9d..3ba0b9919 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -67,6 +67,15 @@ no such refusal; only `lite::version::Version`, which no public path names, stay object no export returns. The bump drops the stale `kio` exclude, which would otherwise leave `kio::Pending` out of the export. +Decided 2026-11-13 (maintainer): ✅ widen #721 to a type a signature names from a dependency +the facade exports nothing else from, such as `pub fn pending() -> kio::Pending` with no +`pub use kio::…` (rejected: land as is with a follow-up quest; land with no follow-up). Such +a crate keeps the roles of one no export is: an error of it never exports (one in a `Result` +crosses as its message, one in an exported error's variant leaves that error an object), and +its type behind an `Arc` stays an opaque handle, refused bare. At the pin, `moq_mux`'s +`container::fmp4::Error` names `mp4_atom::Codec` in a variant, which reaches every box, so +`ffi/moq/ffi.toml` leaves out `mp4_atom`. + Measured on 2026-11-12 at moq's `main` `6936f0a`: `just ffi moq-cpp` fails the export with 36 errors, which the bump fixes in `ffi/moq/ffi.toml` or the exporter: 15 on the foreign type `std::num::NonZero` (such as `Client::with_peer_hop`), 11 stale excludes naming nothing From fb1dc1a91f5adee00a552ff89546616dca0ee72b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:34:21 -0800 Subject: [PATCH 16/26] fix(ffi): an impl Trait + '_ return holds its lifetime, and the stand-in excludes only refusals frame::Buffer::drain returns impl ExactSizeIterator + '_ over arrayvec's Drain, which the glue now names and which borrows the receiver: without the outlives bound the borrow went unseen and the glue did not build. Merged main's census audit fails on excludes of items that export, so the stand-in config now lists exactly what the reach still refuses. Co-Authored-By: Claude Opus 5.5 --- ffi/moq/ffi.toml | 64 ++++++++++++++++++++----------------------- ffi/src/collect.rs | 19 ++++++++++++- ffi/tests/fixtures.rs | 18 ++++++++---- 3 files changed, 61 insertions(+), 40 deletions(-) diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index ad7dafa32..96a64d9d8 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -1,8 +1,7 @@ # What the export refuses at the pinned revision, by paths from the stand-in facade that # `just ffi standin` writes, as `just ffi census` lists it: the API a hand-written wrapper # still has to cover. `kio` is moq-net's re-export of all of kio, of which moq-ffi ships -# only what the facade re-exports. `mp4_atom` is the crate mux's `container::fmp4::Error` -# names in a variant, which reaches its every box. +# only what the facade re-exports. exclude = [ "Client::connect", "bytes", @@ -10,10 +9,28 @@ exclude = [ "clock::Entered", "clock::Rng", "clock::rng", - "frame::Buffer::drain", "hang::moq_net", "kio", - "mp4_atom", + "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::close_reason", + "moq_tokio::quic::driver::connection::Connection::closed", + "moq_tokio::quic::driver::connection::Connection::congestion_state", + "moq_tokio::quic::driver::connection::Connection::poll_closed", + "moq_tokio::quic::driver::connection::Connection::read_datagram", + "moq_tokio::quic::driver::recv::Stream::read", + "moq_tokio::quic::driver::recv::Stream::read_exact", + "moq_tokio::quic::driver::send::Options::group", + "moq_tokio::quic::driver::send::Stream::stopped", + "moq_tokio::quic::driver::send::Stream::write", + "moq_tokio::tcp::TlsAcceptor::accept", + "moq_tokio::tcp::TlsAcceptor::offered", + "mp4_atom::TrunSamples::iter", + "mp4_atom::Tx3g::box_record", "mux::catalog::Guard", "mux::catalog::Producer::modify", "mux::catalog::Producer::modify", @@ -42,39 +59,18 @@ exclude = [ "mux::container::Producer::modify", "mux::container::Producer::modify", "mux::container::Producer::modify", - "mux::container::fmp4::Wire::new", - "mux::container::fmp4::Wire::trak", "mux::container::fmp4::mp4_atom", - "tokio::Server::accept_health", - "tokio::Server::tls_acceptor", - "tokio::connect::Config::deprecated", - "tokio::connect::Config::goaway", - "tokio::connect::Config::resolve", - "tokio::connect::Config::websocket", - "tokio::connection::Monitor::snapshot", - "tokio::connection::Monitor::state", - "tokio::connection::Monitor::state_changed", - "tokio::listen::Config::deprecated", - "tokio::listen::Config::lb", - "tokio::listen::Config::reset", - "tokio::listen::Config::resolve", - "tokio::listen::Config::tcp", - "tokio::listen::Config::unix", - "tokio::quic::Config::congestion_control", - "tokio::quic::Config::controller", - "tokio::quic::Config::deprecated", - "tokio::quic::Config::resolve", - "tokio::server::Config::demux", + "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", "tokio::server::Config::websocket", - "tokio::server::Listener::accept_health", - "tokio::server::Request::quic", - "tokio::server::Request::with_quic_limits", "tokio::server::Request::within", - "tokio::tls::Connect::build", - "tokio::tls::Connect::deprecated", - "tokio::tls::Listen::deprecated", "tokio::tls::Listen::load_roots", - "tokio::tls::PeerIdentity::chain", - "tokio::tls::PeerIdentity::from_chain", "tokio::tls::Serve::resolver", ] diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index b461e9430..32c7d544d 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4152,7 +4152,24 @@ impl<'tcx> Collector<'tcx> { }, ) => { let tcx = self.tcx; - for &(clause, _) in tcx.explicit_item_bounds(*def_id).skip_binder() { + let bounds = tcx.explicit_item_bounds(*def_id).skip_binder(); + // Any other `impl Trait + 'a` holds `'a`, as `impl Iterator + '_` over a + // borrow of its receiver does; a future's borrows are checked apart. + let future = (bounds.iter()).any(|&(clause, _)| { + clause + .as_trait_clause() + .is_some_and(|tr| tcx.is_lang_item(tr.def_id(), LangItem::Future)) + }); + if !future { + for &(clause, _) in bounds { + if let Some(outlives) = clause.as_type_outlives_clause() { + let region = + ty::EarlyBinder::bind(tcx, outlives.skip_binder().1).instantiate(tcx, args); + held.push(region.skip_norm_wip()); + } + } + } + for &(clause, _) in bounds { let term = clause .as_projection_clause() .and_then(|p| p.skip_binder().term.as_type()); diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 74df839c3..3e3c07ca9 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1416,7 +1416,9 @@ fn unreached_types() { pub fn bare(handle: &net::Handle) -> u32 {\n\thandle.0\n}\n\n\ pub fn opaque() -> Result<(), net::Opaque> {\n\tErr(net::Opaque)\n}\n\n\ pub fn closed() -> net::Closed {\n\tnet::closed()\n}\n\n\ - pub enum Failure {\n\tNet(net::Fault),\n}\n\npub fn fail() -> Failure {\n\tFailure::Net(net::Fault)\n}\n", + pub enum Failure {\n\tNet(net::Fault),\n}\n\npub fn fail() -> Failure {\n\tFailure::Net(net::Fault)\n}\n\n\ + pub struct Buffer(Vec);\n\nimpl Buffer {\n\tpub fn new() -> Self {\n\t\tSelf(vec![1])\n\t}\n\n\ + \tpub fn drain(&mut self) -> impl Iterator + '_ {\n\t\tnet::drain(&mut self.0)\n\t}\n}\n", ), ( "net/Cargo.toml", @@ -1430,7 +1432,10 @@ fn unreached_types() { impl std::error::Error for Fault {}\n\n\ pub struct Opaque;\n\nmod closed {\n\tpub struct Closed;\n}\n\npub type Closed = closed::Closed;\n\n\ pub fn closed() -> closed::Closed {\n\tclosed::Closed\n}\n\n\ - pub fn connect() -> Result {\n\tOk(Link(1))\n}\n", + pub fn connect() -> Result {\n\tOk(Link(1))\n}\n\n\ + pub struct Drain<'a>(&'a mut Vec);\n\n\ + pub fn drain(items: &mut Vec) -> Drain<'_> {\n\tDrain(items)\n}\n\n\ + impl Iterator for Drain<'_> {\n\ttype Item = u32;\n\n\tfn next(&mut self) -> Option {\n\t\tself.0.pop()\n\t}\n}\n", ), ( "kio/Cargo.toml", @@ -1521,10 +1526,10 @@ fn unreached_types() { String::from_utf8_lossy(&output.stderr) ); let report = std::fs::read_to_string(census.join("unreached_types.md")).unwrap(); - // `Pending`, `Version`, `Link`, and `Failure` export; `Sealed` alone is refused as - // unreached, though an alias names it. `net`'s error in `Failure` is never reached, so + // `Pending`, `Version`, `Link`, `Failure`, and `Buffer` export; `Sealed` alone is refused + // as unreached, though an alias names it. `net`'s error in `Failure` is never reached, so // `Failure` is an object. - assert!(report.contains("| Types | 4 | 0 |"), "{report}"); + assert!(report.contains("| Types | 5 | 0 |"), "{report}"); assert!(report.contains("- `Failure`: foreign type `net::Fault`"), "{report}"); // A type an `Arc` holds, a `Result`'s error without `Display`, and one no public path // names stay refused as foreign. @@ -1535,6 +1540,9 @@ fn unreached_types() { ] { assert!(report.contains(refused), "{report}"); } + // `impl Iterator + '_` lends a borrow of the receiver, so `drain` is refused and `Drain` + // left out with it, rather than glue that does not build. + assert!(report.contains("- `Buffer::drain`: type C never holds `net::Drain`"), "{report}"); assert!( report.contains("fn `seal` at src/lib.rs:11:1: type not reachable from the crate root `kio::sealed::Sealed`"), "{report}" From f4a361804145bed13ee99c743fbb57a398fd24dd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:34:22 -0800 Subject: [PATCH 17/26] quest(moq-pin): what the reach exports at the pin Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-refusals/moq-pin.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index 3ba0b9919..07af3cc0e 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -72,9 +72,10 @@ the facade exports nothing else from, such as `pub fn pending() -> kio::Pending` `pub use kio::…` (rejected: land as is with a follow-up quest; land with no follow-up). Such a crate keeps the roles of one no export is: an error of it never exports (one in a `Result` crosses as its message, one in an exported error's variant leaves that error an object), and -its type behind an `Arc` stays an opaque handle, refused bare. At the pin, `moq_mux`'s -`container::fmp4::Error` names `mp4_atom::Codec` in a variant, which reaches every box, so -`ffi/moq/ffi.toml` leaves out `mp4_atom`. +its type behind an `Arc` stays an opaque handle, refused bare. At the pin this reaches +mp4_atom's boxes (through moq-mux's `container::fmp4::Wire::new`, `Wire::trak`, and +`fmp4::Error`), moq-quic, moq-sock, and rustls, so `ffi/moq/ffi.toml` excludes only what +they still refuse. Measured on 2026-11-12 at moq's `main` `6936f0a`: `just ffi moq-cpp` fails the export with 36 errors, which the bump fixes in `ffi/moq/ffi.toml` or the exporter: 15 on the foreign From e7a89b4aecd201861554dcc9a2ddbe70a06233a9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:35:00 -0800 Subject: [PATCH 18/26] style(ffi): format the fixture Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 3e3c07ca9..14eb0cb79 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1542,7 +1542,10 @@ fn unreached_types() { } // `impl Iterator + '_` lends a borrow of the receiver, so `drain` is refused and `Drain` // left out with it, rather than glue that does not build. - assert!(report.contains("- `Buffer::drain`: type C never holds `net::Drain`"), "{report}"); + assert!( + report.contains("- `Buffer::drain`: type C never holds `net::Drain`"), + "{report}" + ); assert!( report.contains("fn `seal` at src/lib.rs:11:1: type not reachable from the crate root `kio::sealed::Sealed`"), "{report}" From 3a86970d5527e64f7c365c0938153450907ec712 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:39:40 -0800 Subject: [PATCH 19/26] fix(ffi): an impl Trait return holds what its hidden type holds, not its outlives bound An iterator collected at the call holds no borrow past it, as Codex found. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 14 +++++--------- ffi/tests/fixtures.rs | 5 ++++- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 32c7d544d..da3bdb6c5 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4153,21 +4153,17 @@ impl<'tcx> Collector<'tcx> { ) => { let tcx = self.tcx; let bounds = tcx.explicit_item_bounds(*def_id).skip_binder(); - // Any other `impl Trait + 'a` holds `'a`, as `impl Iterator + '_` over a - // borrow of its receiver does; a future's borrows are checked apart. + // Any other `impl Trait` holds what its hidden type holds, as `impl Iterator + '_` + // over an object borrowing the receiver does; one collected at the call, or a + // future, whose borrows are checked apart, holds nothing past it. let future = (bounds.iter()).any(|&(clause, _)| { clause .as_trait_clause() .is_some_and(|tr| tcx.is_lang_item(tr.def_id(), LangItem::Future)) }); if !future { - for &(clause, _) in bounds { - if let Some(outlives) = clause.as_type_outlives_clause() { - let region = - ty::EarlyBinder::bind(tcx, outlives.skip_binder().1).instantiate(tcx, args); - held.push(region.skip_norm_wip()); - } - } + let hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); + held.extend(self.lifetimes(hidden).0); } for &(clause, _) in bounds { let term = clause diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 14eb0cb79..5eba619b2 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1418,7 +1418,8 @@ fn unreached_types() { pub fn closed() -> net::Closed {\n\tnet::closed()\n}\n\n\ pub enum Failure {\n\tNet(net::Fault),\n}\n\npub fn fail() -> Failure {\n\tFailure::Net(net::Fault)\n}\n\n\ pub struct Buffer(Vec);\n\nimpl Buffer {\n\tpub fn new() -> Self {\n\t\tSelf(vec![1])\n\t}\n\n\ - \tpub fn drain(&mut self) -> impl Iterator + '_ {\n\t\tnet::drain(&mut self.0)\n\t}\n}\n", + \tpub fn drain(&mut self) -> impl Iterator + '_ {\n\t\tnet::drain(&mut self.0)\n\t}\n}\n\n\ + pub fn copied(items: &[u32]) -> impl Iterator + '_ {\n\titems.iter().copied()\n}\n", ), ( "net/Cargo.toml", @@ -1464,6 +1465,8 @@ fn unreached_types() { .arg(&out) .env("CARGO_TARGET_DIR", package.join("build"))); let glue = std::fs::read_to_string(out.join("src/lib.rs")).unwrap(); + // An `impl Iterator + '_` collected at the call holds no borrow past it. + assert!(glue.contains("fn pkg_copied("), "{glue}"); assert!(glue.contains("::kio_reached::Pending"), "{glue}"); // `net`'s error crosses as its message, or holds `Failure`, which holds it, an object, and // its `Arc` crosses as an opaque handle. From e629898284fd5363d0697e64fe2a09d153b05014 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:57:36 -0800 Subject: [PATCH 20/26] fix(ffi): hold an impl Trait's lifetimes only when its hidden type is itself an object The hidden type's regions are the signature's bound ones, so its key is looked up with them erased; an iterator of objects is collected instead. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index da3bdb6c5..b52374b2d 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4163,7 +4163,15 @@ impl<'tcx> Collector<'tcx> { }); if !future { let hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); - held.extend(self.lifetimes(hidden).0); + // Its regions may be the signature's bound ones, which a key never names. + // Only the hidden type itself crosses as a handle; an iterator of objects + // is collected at the call. + let erased = ty::fold_regions(tcx, hidden, |_, _| tcx.lifetimes.re_erased); + let object = matches!(erased.kind(), ty::Adt(adt, args) + if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); + if object { + held.extend(hidden.walk().filter_map(|arg| arg.as_region())); + } } for &(clause, _) in bounds { let term = clause From f61f40fd291c7a9732b4fac99ad492565a05c8bd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:28:36 -0800 Subject: [PATCH 21/26] fix(ffi): an impl Trait return crosses only as an object, holding every lifetime it captures Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 2 ++ ffi/fixtures/api/src/lib.rs | 6 +++++ ffi/src/collect.rs | 36 ++++++++++++++++++++++--- ffi/tests/api.c | 4 +++ ffi/tests/api.cpp | 3 +++ ffi/tests/api.dart | 3 +++ ffi/tests/api.go | 3 +++ ffi/tests/api.kt | 1 + ffi/tests/api.py | 2 ++ ffi/tests/api.swift | 2 ++ ffi/tests/fixtures.rs | 14 +++++++--- 11 files changed, 69 insertions(+), 7 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index c2bc3587c..f731bbbc0 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -120,6 +120,8 @@ fn main() { .map(|(name, counter)| format!("{name} {} {}", counter.name(), counter.get())) .collect(); println!("ranked {}", ranked.join(", ")); + let best: Counter = board.best().into(); + println!("best {} {}", best.name(), best.get()); let atlas = api::Atlas { points: [("b", 1, 1), ("ab", 2, 3), ("b", 4, 4)] .into_iter() diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 2cf21187e..fe4925211 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -350,6 +350,12 @@ impl Board { ranked.sort_by_key(|(_, counter)| std::cmp::Reverse(counter.get())); ranked.into_iter() } + + /// Its highest counter, through an `impl Trait` that captures no borrow of the board, so + /// it crosses as the counter's handle. + pub fn best(&self) -> impl Into + use<> { + (self.counters.values().max_by_key(|counter| counter.get()).cloned()).unwrap_or_default() + } } /// Points by name and the ids in use, as hang's renditions and moq-mux's selections: a map diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index b52374b2d..21f311b5f 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2885,6 +2885,32 @@ impl<'tcx> Collector<'tcx> { ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => args.type_at(0), _ => output, }; + // The glue cannot name an `impl Trait`'s hidden type, so one in a return that maps + // crosses only as what the glue passes on whole, an object's handle; a future and a + // collected iterator map apart. + let unrevealed = sig.output(); + let opaques = (unrevealed.walk().filter_map(|arg| arg.as_type())) + .filter(|ty| { + matches!( + ty.kind(), + ty::Alias( + _, + ty::AliasTy { + kind: ty::AliasTyKind::Opaque { .. }, + .. + } + ) + ) + }) + .filter(|&ty| ok.is_ok() && !(ty == unrevealed && (future || collect))); + for ty in opaques { + let hidden = normalize(ty); + if !matches!(hidden.kind(), ty::Adt(adt, args) + if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))) + { + errs.push(why("opaque type", ty.to_string())); + } + } let lends = matches!(ok, Ok(Type::Ref(Mutability::Not, ref inner)) if matches!(**inner, Type::Object(_))) && !self.is_clone(ok_ty.peel_refs()); let ok = ok.map_err(|why| errs.push(why)).ok(); @@ -4163,14 +4189,16 @@ impl<'tcx> Collector<'tcx> { }); if !future { let hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); - // Its regions may be the signature's bound ones, which a key never names. - // Only the hidden type itself crosses as a handle; an iterator of objects - // is collected at the call. + // One whose hidden type is an object crosses as its handle, which the glue + // keeps as the opaque type itself, so it holds every lifetime it captures, + // even one its hidden type does not borrow; one collected at the call holds + // nothing past it, and any other is refused. Looked up with regions erased, + // since they may be the signature's bound ones, which a key never names. let erased = ty::fold_regions(tcx, hidden, |_, _| tcx.lifetimes.re_erased); let object = matches!(erased.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); if object { - held.extend(hidden.walk().filter_map(|arg| arg.as_region())); + held.extend(args.iter().flat_map(|arg| arg.walk()).filter_map(|arg| arg.as_region())); } } for &(clause, _) in bounds { diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 16ccf9ce5..06bab57fc 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -640,6 +640,10 @@ static int script(void) { } printf("\n"); api_vec_tuple_string_Counter_free(ranked); + api_Counter *best = api_Board_best(board); + print("best ", api_Counter_name(best), " "); + printf("%llu\n", (unsigned long long)api_Counter_get(best)); + api_Counter_free(best); api_Board_free(board); /* A map crosses as its pairs and a set as its items, which Rust collects in order, each * key once, the last kept. */ diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index a5634956b..516bacb8d 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -291,6 +291,9 @@ int script() { std::printf("%llu", ull(counter.get())); } std::printf("\n"); + auto best = board.best(); + print("best ", best.name(), " "); + std::printf("%llu\n", ull(best.get())); } { // A map crosses as its pairs and a set as its items, which Rust collects in order, diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index e42486706..f12719e93 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -163,6 +163,9 @@ Future script() async { final board = api.Board([('low', api.Counter('l', 1)), ('high', api.Counter('h', 9))]); final ranked = board.ranked(); print('ranked ${ranked.map((r) => '${r.$1} ${r.$2.name()} ${r.$2.get()}').join(', ')}'); + final best = board.best(); + print('best ${best.name()} ${best.get()}'); + best.close(); board.close(); // A map crosses as its pairs and a set as its items, which Rust collects in order, each // key once, the last kept. diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 119cb69d8..9b22f1f8f 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -222,6 +222,9 @@ func script() { fmt.Printf("ranked %s\n", strings.Trim(list(must(board.Ranked()), func(r rt.Tuple2[string, *api.Counter]) string { return fmt.Sprintf("%s %s %d", r.V0, must(r.V1.Name()), must(r.V1.Get())) }), "[]")) + best := must(board.Best()) + fmt.Printf("best %s %d\n", must(best.Name()), must(best.Get())) + best.Close() board.Close() // A map crosses as its pairs and a set as its items, which Rust collects in order, each // key once, the last kept. diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index c0d26182d..1b6ee498a 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -102,6 +102,7 @@ fun script() { val ranked = board.ranked() println("ranked ${ranked.joinToString(", ") { (name, counter) -> "$name ${counter.name()} ${counter.get()}" }}") ranked.forEach { it.second.close() } + board.best().use { println("best ${it.name()} ${it.get()}") } } // A map crosses as its pairs and a set as its items, which Rust collects in order, each // key once, the last kept. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index b12e356d5..84139d1f4 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -164,6 +164,8 @@ def script(): board = api.Board.new([("low", api.Counter.new("l", 1)), ("high", api.Counter.new("h", 9))]) ranked = board.ranked() print("ranked " + ", ".join(f"{name} {counter.name()} {counter.get()}" for name, counter in ranked)) + best = board.best() + print(f"best {best.name()} {best.get()}") # A map crosses as its pairs and a set as its items, which Rust collects in order, each # key once, the last kept. atlas = api.Atlas([("b", api.Point(1, 1)), ("ab", api.Point(2, 3)), ("b", api.Point(4, 4))], [3, 1, 3]) diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 03fb0aa85..31581f0c3 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -253,6 +253,8 @@ func script() { let board = Board.new(ranks) let ranked = board.ranked() print("ranked \(listed(ranked) { "\($0._0) \($0._1.name()) \($0._1.get())" })") + let best = board.best() + print("best \(best.name()) \(best.get())") // A map crosses as its pairs and a set as its items, which Rust collects in order, each // key once, the last kept. let atlas = Atlas(points: [("b", Point(x: 1, y: 1)), ("ab", Point(x: 2, y: 3)), ("b", Point(x: 4, y: 4))], ids: [3, 1, 3]) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 5eba619b2..ba810616e 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1419,7 +1419,10 @@ fn unreached_types() { pub enum Failure {\n\tNet(net::Fault),\n}\n\npub fn fail() -> Failure {\n\tFailure::Net(net::Fault)\n}\n\n\ pub struct Buffer(Vec);\n\nimpl Buffer {\n\tpub fn new() -> Self {\n\t\tSelf(vec![1])\n\t}\n\n\ \tpub fn drain(&mut self) -> impl Iterator + '_ {\n\t\tnet::drain(&mut self.0)\n\t}\n}\n\n\ - pub fn copied(items: &[u32]) -> impl Iterator + '_ {\n\titems.iter().copied()\n}\n", + pub fn copied(items: &[u32]) -> impl Iterator + '_ {\n\titems.iter().copied()\n}\n\n\ + #[derive(Clone)]\npub struct Held<'a>(&'a u32);\n\nimpl Held<'_> {\n\tpub fn get(&self) -> u32 {\n\t\t*self.0\n\t}\n}\n\n\ + pub fn wrap(x: &u32) -> impl Clone + '_ {\n\tSome(Held(x))\n}\n\n#[derive(Clone)]\npub struct Own(u32);\n\nimpl Own {\n\tpub fn get(&self) -> u32 {\n\t\tself.0\n\t}\n}\n\npub fn own() -> impl Clone {\n\tSome(Own(1))\n}\n\n\ + impl Buffer {\n\tpub fn first(&self) -> impl Clone + '_ {\n\t\tOwn(self.0[0])\n\t}\n}\n", ), ( "net/Cargo.toml", @@ -1454,7 +1457,7 @@ fn unreached_types() { // The export builds, naming `kio`'s types through its own dependency on `kio`. std::fs::write( package.join("ffi.toml"), - "exclude = [\"seal\", \"bare\", \"opaque\", \"closed\"]\n", + "exclude = [\"seal\", \"bare\", \"opaque\", \"closed\", \"own\", \"Buffer::first\"]\n", ) .unwrap(); let out = package.join("out"); @@ -1544,11 +1547,16 @@ fn unreached_types() { assert!(report.contains(refused), "{report}"); } // `impl Iterator + '_` lends a borrow of the receiver, so `drain` is refused and `Drain` - // left out with it, rather than glue that does not build. + // left out with it, rather than glue that does not build; so is `wrap`, whose hidden + // `Option` holds a borrowing `Held`. assert!( report.contains("- `Buffer::drain`: type C never holds `net::Drain`"), "{report}" ); + assert!(report.contains("- `wrap`: type C never holds `Held`"), "{report}"); + // The glue cannot destructure a hidden type it cannot name, so only an object crosses + // through an `impl Trait`: `own`'s `Option` is refused, and `Own` left out with it. + assert!(report.contains("- `own`: type C never holds `Own`"), "{report}"); assert!( report.contains("fn `seal` at src/lib.rs:11:1: type not reachable from the crate root `kio::sealed::Sealed`"), "{report}" From 00f6758c5da6889c024f2a0442a1a4dc02d3c60b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:40:32 -0800 Subject: [PATCH 22/26] docs(ffi): an impl Trait return crosses only as an object; record the checkpoint Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 1 + quest/m1/ffi-refusals/moq-pin.md | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/ffi/README.md b/ffi/README.md index cc8078ac7..e201446bd 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -121,6 +121,7 @@ refused. | `Vec` and `&[T]` of any other `T` | `_vec_`: an array of `T`'s C values, viewed passed in and owned returned, a slice as a clone; of references only returned | | `BTreeSet`, `BTreeMap`, and `serde_json::Map` | as `Vec`, `Vec<(K, V)>`, and `Vec<(String, serde_json::Value)>`: its items in order, from which Rust builds it, keeping the last of a key | | a returned iterator, such as `slice::Iter` or an `impl Iterator`, that no other rule maps, outside a future, made of core's and alloc's iterators over a slice, string, `Option`, `Result`, or collection, or serde_json's `map::Iter`, `IntoIter`, `Keys`, or `Values`, through `rev`, `chain`, `flatten`, `fuse`, `enumerate`, `peekable`, `copied`, `cloned`, or `filter`, with no trait object inside; a closure or function inside, such as `filter`'s predicate or `split`'s pattern, must drop nothing, and a `filter` only items whose drop runs nothing | what `collect::>()` makes of it: every item, taken at the call, so a closure inside runs on every item, not only those a caller stopping early would reach | +| a returned `impl Trait` other than a future or a collected iterator, whose hidden type is an object | that object's handle, which keeps the `impl Trait` itself, so every lifetime it captures must be `'static`: one capturing a borrow, as `impl Clone + '_` does, is refused, and `+ use<>` captures none; one hiding any other type, such as an `Option`, is refused, since the glue cannot name it | | `Waker`, taken by value | `_waker`, as a future's poll takes it | | a returned `Waker` or `&Waker`, or a returned `Context`, which is only a waker lent for a call | `_waker` of a clone of the waker, or the context's: the caller's, to wake through Rust and drop once | | `&Context` or `&mut Context` of a function returning no `Poll` and no future | `_waker`, which the context is made of for the call | diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index 07af3cc0e..24432e481 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -77,6 +77,15 @@ mp4_atom's boxes (through moq-mux's `container::fmp4::Wire::new`, `Wire::trak`, `fmp4::Error`), moq-quic, moq-sock, and rustls, so `ffi/moq/ffi.toml` excludes only what they still refuse. +Decided 2026-11-13 (maintainer, #721's design checkpoint): ✅ an `impl Trait` return holds +what its hidden type holds, as a named return does, so `fn wrap(x: &u32) -> impl Clone + '_ { +Some(Held(x)) }` is refused instead of producing glue that does not build, while an iterator +collected at the call still exports (rejected: map every `impl Trait` return as its hidden +type everywhere; land as is with a follow-up quest). Implementing it showed the glue keeps the +`impl Trait` itself, never its hidden type, so #721 lets one cross only when its hidden type is +an object, holding every lifetime it captures, and refuses any other. moq's census at the pin +is unchanged by it. + Measured on 2026-11-12 at moq's `main` `6936f0a`: `just ffi moq-cpp` fails the export with 36 errors, which the bump fixes in `ffi/moq/ffi.toml` or the exporter: 15 on the foreign type `std::num::NonZero` (such as `Client::with_peer_hop`), 11 stale excludes naming nothing From 17fed2bd750836fd7fc36839ba20fddd4047a164 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:45:57 -0800 Subject: [PATCH 23/26] fix(ffi): check an impl Trait a future outputs or a collected iterator yields Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 2 +- ffi/fixtures/reject/expected.txt | 3 ++ ffi/fixtures/reject/src/lib.rs | 15 +++++++++ ffi/src/collect.rs | 53 +++++++++++++++++++------------- 4 files changed, 50 insertions(+), 23 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index e201446bd..e13e6663f 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -121,7 +121,7 @@ refused. | `Vec` and `&[T]` of any other `T` | `_vec_`: an array of `T`'s C values, viewed passed in and owned returned, a slice as a clone; of references only returned | | `BTreeSet`, `BTreeMap`, and `serde_json::Map` | as `Vec`, `Vec<(K, V)>`, and `Vec<(String, serde_json::Value)>`: its items in order, from which Rust builds it, keeping the last of a key | | a returned iterator, such as `slice::Iter` or an `impl Iterator`, that no other rule maps, outside a future, made of core's and alloc's iterators over a slice, string, `Option`, `Result`, or collection, or serde_json's `map::Iter`, `IntoIter`, `Keys`, or `Values`, through `rev`, `chain`, `flatten`, `fuse`, `enumerate`, `peekable`, `copied`, `cloned`, or `filter`, with no trait object inside; a closure or function inside, such as `filter`'s predicate or `split`'s pattern, must drop nothing, and a `filter` only items whose drop runs nothing | what `collect::>()` makes of it: every item, taken at the call, so a closure inside runs on every item, not only those a caller stopping early would reach | -| a returned `impl Trait` other than a future or a collected iterator, whose hidden type is an object | that object's handle, which keeps the `impl Trait` itself, so every lifetime it captures must be `'static`: one capturing a borrow, as `impl Clone + '_` does, is refused, and `+ use<>` captures none; one hiding any other type, such as an `Option`, is refused, since the glue cannot name it | +| a returned `impl Trait`, or one a returned future outputs or a collected iterator yields, other than that future or iterator itself, whose hidden type is an object | that object's handle, which keeps the `impl Trait` itself, so every lifetime it captures must be `'static`: one capturing a borrow, as `impl Clone + '_` does, is refused, and `+ use<>` captures none; one hiding any other type, such as an `Option`, is refused, since the glue cannot name it | | `Waker`, taken by value | `_waker`, as a future's poll takes it | | a returned `Waker` or `&Waker`, or a returned `Context`, which is only a waker lent for a call | `_waker` of a clone of the waker, or the context's: the caller's, to wake through Rust and drop once | | `&Context` or `&mut Context` of a function returning no `Poll` and no future | `_waker`, which the context is made of for the call | diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index bd611ea1e..dfed3ae8c 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -6,6 +6,9 @@ fixtures/reject/src/lib.rs:1016:1: rust2-ffi: cannot export fn `trust`: trait ob fixtures/reject/src/lib.rs:1021: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:1011:1: note: C cannot implement `Hazard`: unsafe fn `risk` fixtures/reject/src/lib.rs:1026: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:1031: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:1036: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:1041: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:106: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 fixtures/reject/src/lib.rs:112: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:118:1: rust2-ffi: cannot export fn `boxed`: reference inside a parameter `std::boxed::Box<&str>`; 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 ced883e7f..851a53913 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1026,3 +1026,18 @@ pub fn hazard(hazard: Box) -> u32 { pub fn wide_non_zero(n: std::num::NonZero) -> u128 { n.get() } + +/// A future whose output is an `impl Trait` hiding no object, which the glue cannot name. +pub async fn hidden_answer() -> impl Copy { + 1_u32 +} + +/// A collected iterator whose items are an `impl Trait` hiding no object. +pub fn hidden_items() -> impl Iterator { + [1_u32].into_iter() +} + +/// An `impl Trait` hiding an `Option`, which the glue cannot take apart. +pub fn hidden_option() -> impl Clone { + Some(1_u32) +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 21f311b5f..20a1f5641 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2886,29 +2886,38 @@ impl<'tcx> Collector<'tcx> { _ => output, }; // The glue cannot name an `impl Trait`'s hidden type, so one in a return that maps - // crosses only as what the glue passes on whole, an object's handle; a future and a - // collected iterator map apart. + // crosses only as what the glue passes on whole, an object's handle. A future and a + // collected iterator are taken apart instead, so it is what their output or items + // name that crosses. let unrevealed = sig.output(); - let opaques = (unrevealed.walk().filter_map(|arg| arg.as_type())) - .filter(|ty| { - matches!( - ty.kind(), - ty::Alias( - _, - ty::AliasTy { - kind: ty::AliasTyKind::Opaque { .. }, - .. - } - ) - ) - }) - .filter(|&ty| ok.is_ok() && !(ty == unrevealed && (future || collect))); - for ty in opaques { - let hidden = normalize(ty); - if !matches!(hidden.kind(), ty::Adt(adt, args) - if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))) - { - errs.push(why("opaque type", ty.to_string())); + let mut named = if ok.is_ok() { vec![unrevealed] } else { Vec::new() }; + while let Some(ty) = named.pop() { + for ty in ty.walk().filter_map(|arg| arg.as_type()) { + let ty::Alias( + _, + ty::AliasTy { + kind: ty::AliasTyKind::Opaque { def_id }, + args, + .. + }, + ) = ty.kind() + else { + continue; + }; + if ty == unrevealed && (future || collect) { + let bounds = tcx.explicit_item_bounds(*def_id).skip_binder(); + named.extend(bounds.iter().filter_map(|&(clause, _)| { + let term = clause.as_projection_clause()?.skip_binder().term.as_type()?; + Some(ty::EarlyBinder::bind(tcx, term).instantiate(tcx, args).skip_norm_wip()) + })); + continue; + } + let hidden = normalize(ty); + if !matches!(hidden.kind(), ty::Adt(adt, args) + if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))) + { + errs.push(why("opaque type", ty.to_string())); + } } } let lends = matches!(ok, Ok(Type::Ref(Mutability::Not, ref inner)) if matches!(**inner, Type::Object(_))) From 983c3fb8967034d925ccb95e83800f1c25fe1949 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:59:05 -0800 Subject: [PATCH 24/26] fix(ffi): give main's new test Apis the reached field --- ffi/src/go.rs | 1 + ffi/src/lock.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/ffi/src/go.rs b/ffi/src/go.rs index eaf691c4d..10e1f421d 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2945,6 +2945,7 @@ fn package_names_are_locked() { constants: vec![], crates: vec!["lock_foobar".into()], targets: vec!["host".into()], + reached: Vec::new(), }; let base = api.clone(); let old = generate(&Abi::new(&api, "lock"), "lock", 0, "lock").unwrap(); diff --git a/ffi/src/lock.rs b/ffi/src/lock.rs index 36e17dddc..e234276fa 100644 --- a/ffi/src/lock.rs +++ b/ffi/src/lock.rs @@ -818,6 +818,7 @@ mod tests { constants: vec![], crates: vec!["lock_a".into(), "lock_b".into()], targets: vec!["host".into()], + reached: Vec::new(), } } From bb2af3db90b703ef0184d0f52d679f6f9d58b110 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:11:39 -0800 Subject: [PATCH 25/26] fix(ffi): reveal a delegated impl Trait in full, and reach an Into target An impl Trait returning another fn's impl Trait now holds what its fully revealed object holds, as function() reveals it, so Buffer::best is left out instead of producing glue that fails with E0597. A conversion target only an impl Into or AsRef bound names is reached by its public path, so the function takes it in the next pass instead of being refused. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 21 ++++++++++++++++++--- ffi/tests/fixtures.rs | 35 ++++++++++++++++++++++++++++------- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 96c0ccacf..53749b7f8 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3168,8 +3168,11 @@ impl<'tcx> Collector<'tcx> { let tr = bound.def_id(); let target = || bound.skip_binder().trait_ref.args.type_at(1); if tcx.is_diagnostic_item(sym::Into, tr) || tcx.is_diagnostic_item(sym::AsRef, tr) { - // An `Into` target that does not map takes what converts into it instead. - let sources = (tcx.is_diagnostic_item(sym::Into, tr) && !self.maps(target(), Pos::Param)) + // An `Into` target that does not map takes what converts into it instead. The + // signature names the target, so unlike a candidate only tried, mapping it reaches + // it by its public path in its own crate. + let maps = (self.inferring && self.names_export(target())) || self.ty(target(), Pos::Param).is_ok(); + let sources = (tcx.is_diagnostic_item(sym::Into, tr) && !maps) .then(|| self.sources(def_id, target(), outlives)) .transpose()?; let sources = (sources.into_iter().flatten()).map(|(x, outlives, imp)| (x, outlives, Some(imp))); @@ -4197,7 +4200,19 @@ impl<'tcx> Collector<'tcx> { .is_some_and(|tr| tcx.is_lang_item(tr.def_id(), LangItem::Future)) }); if !future { - let hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); + // Revealed through each `impl Trait` it returns in turn, as `function` reveals it. + let mut hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); + while let ty::Alias( + _, + ty::AliasTy { + kind: ty::AliasTyKind::Opaque { def_id }, + args, + .. + }, + ) = hidden.kind() + { + hidden = tcx.type_of(*def_id).instantiate(tcx, args).skip_norm_wip(); + } // One whose hidden type is an object crosses as its handle, which the glue // keeps as the opaque type itself, so it holds every lifetime it captures, // even one its hidden type does not borrow; one collected at the call holds diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 73da47c0d..a30ae470e 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1404,7 +1404,8 @@ fn unreached_types() { "Cargo.toml", "[package]\nname = \"unreached_types\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"pkg\"\n\n\ [dependencies]\nkio = { package = \"unreached-kio\", path = \"kio\" }\n\ - net = { package = \"unreached-net\", path = \"net\" }\n\n[workspace]\nexclude = [\"kio\", \"net\"]\n", + net = { package = \"unreached-net\", path = \"net\" }\n\ + conv = { package = \"unreached-conv\", path = \"conv\" }\n\n[workspace]\nexclude = [\"kio\", \"net\", \"conv\"]\n", ), ( "src/lib.rs", @@ -1422,7 +1423,12 @@ fn unreached_types() { pub fn copied(items: &[u32]) -> impl Iterator + '_ {\n\titems.iter().copied()\n}\n\n\ #[derive(Clone)]\npub struct Held<'a>(&'a u32);\n\nimpl Held<'_> {\n\tpub fn get(&self) -> u32 {\n\t\t*self.0\n\t}\n}\n\n\ pub fn wrap(x: &u32) -> impl Clone + '_ {\n\tSome(Held(x))\n}\n\n#[derive(Clone)]\npub struct Own(u32);\n\nimpl Own {\n\tpub fn get(&self) -> u32 {\n\t\tself.0\n\t}\n}\n\npub fn own() -> impl Clone {\n\tSome(Own(1))\n}\n\n\ - impl Buffer {\n\tpub fn first(&self) -> impl Clone + '_ {\n\t\tOwn(self.0[0])\n\t}\n}\n", + impl Buffer {\n\tpub fn first(&self) -> impl Clone + '_ {\n\t\tOwn(self.0[0])\n\t}\n}\n\n\ + pub struct Counter(u32);\n\nimpl Counter {\n\tpub fn get(&self) -> u32 {\n\t\tself.0\n\t}\n}\n\n\ + impl Buffer {\n\tfn counter(&self) -> impl Into + '_ {\n\t\tCounter(self.0[0])\n\t}\n\n\ + \tpub fn best(&self) -> impl Into + '_ {\n\t\tself.counter()\n\t}\n}\n\n\ + pub fn copied_again(items: &[u32]) -> impl Iterator + '_ {\n\tcopied(items)\n}\n\n\ + pub fn take(value: impl Into) -> u32 {\n\tvalue.into().get()\n}\n", ), ( "net/Cargo.toml", @@ -1441,6 +1447,14 @@ fn unreached_types() { pub fn drain(items: &mut Vec) -> Drain<'_> {\n\tDrain(items)\n}\n\n\ impl Iterator for Drain<'_> {\n\ttype Item = u32;\n\n\tfn next(&mut self) -> Option {\n\t\tself.0.pop()\n\t}\n}\n", ), + ( + "conv/Cargo.toml", + "[package]\nname = \"unreached-conv\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"conv\"\n", + ), + ( + "conv/src/lib.rs", + "pub struct Value(u32);\n\nimpl Value {\n\tpub fn new(n: u32) -> Self {\n\t\tSelf(n)\n\t}\n\n\tpub fn get(&self) -> u32 {\n\t\tself.0\n\t}\n}\n", + ), ( "kio/Cargo.toml", "[package]\nname = \"unreached-kio\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[lib]\nname = \"kio\"\n", @@ -1470,6 +1484,10 @@ fn unreached_types() { let glue = std::fs::read_to_string(out.join("src/lib.rs")).unwrap(); // An `impl Iterator + '_` collected at the call holds no borrow past it. assert!(glue.contains("fn pkg_copied("), "{glue}"); + // So does one returning another's, whose hidden type is revealed in full. + assert!(glue.contains("fn pkg_copied_again("), "{glue}"); + // A conversion target only an `impl Into` names is reached, and taken. + assert!(glue.contains("rt::Object::<::conv_reached::Value>::take(p0, w)"), "{glue}"); assert!(glue.contains("::kio_reached::Pending"), "{glue}"); // `net`'s error crosses as its message, or holds `Failure`, which holds it, an object, and // its `Arc` crosses as an opaque handle. @@ -1492,7 +1510,7 @@ fn unreached_types() { .env("CARGO_TARGET_DIR", package.join("build"))); let moved = scratch().join("unreached_types-moved"); let _ = std::fs::remove_dir_all(&moved); - for dir in ["src", "kio", "net"] { + for dir in ["src", "kio", "net", "conv"] { copy_dir(&package.join(dir), &moved.join(dir)); } for file in ["Cargo.toml", "ffi.toml"] { @@ -1532,10 +1550,10 @@ fn unreached_types() { String::from_utf8_lossy(&output.stderr) ); let report = std::fs::read_to_string(census.join("unreached_types.md")).unwrap(); - // `Pending`, `Version`, `Link`, `Failure`, and `Buffer` export; `Sealed` alone is refused - // as unreached, though an alias names it. `net`'s error in `Failure` is never reached, so - // `Failure` is an object. - assert!(report.contains("| Types | 5 | 0 |"), "{report}"); + // `Pending`, `Version`, `Link`, `Failure`, `Buffer`, and `conv::Value` export; `Sealed` + // alone is refused as unreached, though an alias names it. `net`'s error in `Failure` is + // never reached, so `Failure` is an object. + assert!(report.contains("| Types | 6 | 0 |"), "{report}"); assert!(report.contains("- `Failure`: foreign type `net::Fault`"), "{report}"); // A type an `Arc` holds, a `Result`'s error without `Display`, and one no public path // names stay refused as foreign. @@ -1554,6 +1572,9 @@ fn unreached_types() { "{report}" ); assert!(report.contains("- `wrap`: type C never holds `Held`"), "{report}"); + // So is `best`, whose `impl Into + '_` hides another `impl Trait` hiding a + // `Counter`, an object its handle would hold the receiver's borrow for. + assert!(report.contains("- `Buffer::best`: type C never holds `Counter`"), "{report}"); // The glue cannot destructure a hidden type it cannot name, so only an object crosses // through an `impl Trait`: `own`'s `Option` is refused, and `Own` left out with it. assert!(report.contains("- `own`: type C never holds `Own`"), "{report}"); From d1fd86f6cf67c30fbea5b8edffcd101549e306a3 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:13:38 -0800 Subject: [PATCH 26/26] style(ffi): rustfmt the fixture Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index a30ae470e..56f255714 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1487,7 +1487,10 @@ fn unreached_types() { // So does one returning another's, whose hidden type is revealed in full. assert!(glue.contains("fn pkg_copied_again("), "{glue}"); // A conversion target only an `impl Into` names is reached, and taken. - assert!(glue.contains("rt::Object::<::conv_reached::Value>::take(p0, w)"), "{glue}"); + assert!( + glue.contains("rt::Object::<::conv_reached::Value>::take(p0, w)"), + "{glue}" + ); assert!(glue.contains("::kio_reached::Pending"), "{glue}"); // `net`'s error crosses as its message, or holds `Failure`, which holds it, an object, and // its `Arc` crosses as an opaque handle. @@ -1574,7 +1577,10 @@ fn unreached_types() { assert!(report.contains("- `wrap`: type C never holds `Held`"), "{report}"); // So is `best`, whose `impl Into + '_` hides another `impl Trait` hiding a // `Counter`, an object its handle would hold the receiver's borrow for. - assert!(report.contains("- `Buffer::best`: type C never holds `Counter`"), "{report}"); + assert!( + report.contains("- `Buffer::best`: type C never holds `Counter`"), + "{report}" + ); // The glue cannot destructure a hidden type it cannot name, so only an object crosses // through an `impl Trait`: `own`'s `Option` is refused, and `Own` left out with it. assert!(report.contains("- `own`: type C never holds `Own`"), "{report}");