diff --git a/ffi/README.md b/ffi/README.md index ed040187d..8e37471a2 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -22,7 +22,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 @@ -69,7 +70,19 @@ 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. 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 | | --- | --- | @@ -108,6 +121,7 @@ re-exports its items instead, which export. A type no path reaches is refused. | `Vec`, `&[T]`, and `Box<[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; a boxed slice of bytes is refused | | `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`, 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/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 3ba07dfce..a9a5fa3fe 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() @@ -583,6 +585,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 d5f7e6f17..42b6c9ab0 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 @@ -2244,8 +2250,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)) } @@ -2260,6 +2266,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/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 223c2e0ff..d6a237a21 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -6,7 +6,10 @@ 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 `boxed_bytes`: boxed slice of bytes `std::boxed::Box<[u8]>`; 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:1046:1: rust2-ffi: cannot export fn `boxed_bytes`: boxed slice of bytes `std::boxed::Box<[u8]>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs: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 4a4042aeb..dfd2b4eaa 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1027,6 +1027,21 @@ 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) +} + /// A boxed slice of bytes, which no buffer form takes. pub fn boxed_bytes(bytes: Box<[u8]>) -> usize { bytes.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/moq/ffi.toml b/ffi/moq/ffi.toml index 235177e03..96a64d9d8 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -9,9 +9,28 @@ exclude = [ "clock::Entered", "clock::Rng", "clock::rng", - "frame::Buffer::drain", "hang::moq_net", "kio", + "moq_quic::VarInt::from_u64_unchecked", + "moq_sock::demux::Discard::ALL", + "moq_tokio::accept::Failure::classify", + "moq_tokio::accept::Health::failed", + "moq_tokio::quic::Controller::0", + "moq_tokio::quic::demux::Datagram::local", + "moq_tokio::quic::driver::connection::Connection::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", @@ -40,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/cli.rs b/ffi/src/cli.rs index c8da50144..e8ae97eb0 100644 --- a/ffi/src/cli.rs +++ b/ffi/src/cli.rs @@ -82,6 +82,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. @@ -105,6 +106,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::BASELINE, baseline.as_os_str()), (config::env::ROOTS, roots.as_ref()), @@ -314,6 +316,102 @@ 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)) + } + // 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 = 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} = {:?}", decode(value)?), + Some(_) => return None, + None => String::new(), + }; + Some(format!("package = {name:?}, git = {url:?}{reference}")) + } + Some(_) => None, + } +} + +/// `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 { diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index e4af454c9..53749b7f8 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -146,6 +146,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, /// Paths from its root a census checks, without leaving out what they name: each /// path one names is recorded in [`Report::audited`], as the exclude would have checked it. pub audit: &'a [String], @@ -239,6 +241,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, @@ -264,6 +268,21 @@ 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, + /// 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>, + /// 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, } @@ -340,7 +359,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], barred: &[DefId]| { let mut c = Collector { tcx, items: Vec::new(), @@ -348,6 +367,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(), @@ -375,6 +395,12 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { bound, range_bounds, orphans: orphans.clone(), + 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(), @@ -383,6 +409,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()], }, }; @@ -395,7 +422,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, @@ -411,18 +438,42 @@ 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(); + let mut barred = Vec::new(); loop { - let c = pass(&orphans); + 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(); - if more.is_empty() { + 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, report: c.report, }; } - orphans.extend(more); + // 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(); + } } } @@ -585,6 +636,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 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) + } + /// Whether the config excludes `path`, counting the exclusion, or else recording it under /// each audited path that names it. A member of an instance is left out by its instance's /// path or its type's, which leaves it out of each. @@ -837,7 +895,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) } @@ -1218,6 +1276,117 @@ 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; + self.walked = self.crates.len(); + 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; + } + // 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); + } + self.outside.insert(def_id, outside); + self.items.push((def_id, path)); + } + } + + /// 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; + } + 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() + && !root.iter().any(|child| child.ident.name == name) + && 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> { + 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 + || (kind == DefKind::Mod && tcx.is_doc_hidden(id)) + { + 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. @@ -2673,7 +2842,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))) @@ -2694,8 +2863,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) => @@ -2712,6 +2885,41 @@ 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 are taken apart instead, so it is what their output or items + // name that crosses. + let unrevealed = sig.output(); + 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(_))) && !self.is_clone(ok_ty.peel_refs()); let ok = ok.map_err(|why| errs.push(why)).ok(); @@ -2960,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))); @@ -3380,7 +3591,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. @@ -3971,7 +4190,42 @@ 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` 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 { + // 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 + // 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(args.iter().flat_map(|arg| arg.walk()).filter_map(|arg| arg.as_region())); + } + } + for &(clause, _) in bounds { let term = clause .as_projection_clause() .and_then(|p| p.skip_binder().term.as_type()); @@ -4394,9 +4648,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())?, @@ -4531,7 +4784,17 @@ 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: 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))); } else { let key = self.key(did, *args); @@ -4571,6 +4834,10 @@ 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.reachable(did) { + self.reached(did); + } return Err(why("type not reachable from the crate root", name)); } } diff --git a/ffi/src/config.rs b/ffi/src/config.rs index 0363f3452..d20674467 100644 --- a/ffi/src/config.rs +++ b/ffi/src/config.rs @@ -94,4 +94,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 3deb4d693..e32e5d3c7 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -47,6 +47,8 @@ pub const API_FILE: &str = "api.json"; /// 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. @@ -117,10 +119,21 @@ 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::>()?; let baseline = std::env::var_os(config::env::BASELINE) .filter(|p| !p.is_empty()) .map(PathBuf::from); Ok(Some(Self { + crates, config, output, facade, @@ -140,6 +153,7 @@ impl Callbacks for Export { let facade = collect::Facade { root: self.facade.root(), package: &self.facade.name, + crates: &self.crates, // A census counts the whole API, whatever the config leaves out. exclude: match self.output { Output::Census(_) => &[], @@ -462,6 +476,7 @@ impl Export { abi: &abi, facade: &self.facade, patch: &self.patch, + crates: &self.crates, }; let generated = glue.generate(out)?; if let Some(path) = &self.baseline { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index c307d3368..77952a49e 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 { @@ -115,6 +121,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, } /// Generated files and the names checked before any file is written. @@ -203,7 +212,28 @@ 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. + // 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}{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") { @@ -245,6 +275,7 @@ impl Crate<'_> { # What dart/{lib}.dart calls that `dart:ffi` lacks.\n\ dart = []\n\ \n\ + {targeted}\ [workspace]\n\ {patch}", patch = self.patch, @@ -474,9 +505,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/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/ir.rs b/ffi/src/ir.rs index 5dff83ad4..27a100195 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -17,10 +17,23 @@ 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. 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, } +/// 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, + /// The targets whose API names its types, sorted. + pub targets: Vec, +} + impl Api { /// Whether a value of `ty` holds a float anywhere, its records' and enums' included, so a /// language comparing it itself must use IEEE `==`, as Rust does: NaN unequal even to 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(), } } diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 79e38a779..7dc494547 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -269,6 +269,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); @@ -291,6 +338,7 @@ impl Merged { } } } + self.collisions(); match order_crates(&self.api) { Ok(crates) => self.api.crates = crates, Err(cycle) => { @@ -348,6 +396,16 @@ impl Merged { .unwrap_or(self.api.crates.len()); self.api.crates.insert(at, krate.clone()); } + for reached in api.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) { let Some(ours) = self.api.records.get(at) else { self.api.records.push(record); @@ -748,6 +806,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 { @@ -755,4 +814,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()); + } } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index c074f03b3..1c9632dce 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -700,6 +700,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. */ @@ -1409,6 +1413,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 f98224fe8..aa1b518de 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -345,6 +345,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, @@ -892,6 +895,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 570e28ae9..d81077978 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -189,6 +189,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. @@ -562,6 +565,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 b7d0ee8a6..5194cc030 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -244,6 +244,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. @@ -662,6 +665,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 df8431d7e..817d41479 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -118,6 +118,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. @@ -478,6 +479,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 e73aeb8df..d76582b4b 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -189,6 +189,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]) @@ -569,6 +571,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 07a855151..ae6108a2a 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]) @@ -650,6 +652,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) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 751095fe0..56f255714 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1389,6 +1389,208 @@ 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, 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"); + 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\ + net = { package = \"unreached-net\", path = \"net\" }\n\ + conv = { package = \"unreached-conv\", path = \"conv\" }\n\n[workspace]\nexclude = [\"kio\", \"net\", \"conv\"]\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\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\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\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\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", + "[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\ + 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\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", + ), + ( + "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", + ), + ( + "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", + ), + ], + ); + // 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\", \"own\", \"Buffer::first\"]\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(); + // 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. + assert!( + glue.contains("::net_reached::Link") && !glue.contains("Fault") && !glue.contains("net_reached::Handle"), + "{glue}" + ); + run(cargo() + .arg("build") + .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", "net", "conv"] { + 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(); + } + 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")) + .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().to_string())) + && !manifest.contains(&format!("{:?}", 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")) + .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`, `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. + 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}"); + } + // `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; 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}"); + // 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}"); + assert!( + 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}"); +} + /// `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 20a5a6082..24432e481 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 [kixel-ai/rust2#683](https://github.com/kixel-ai/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/kixel-ai/rust2/pull/676). @@ -58,7 +58,33 @@ 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. +[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 +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. + +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 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. + +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