diff --git a/ffi/Cargo.lock b/ffi/Cargo.lock index 170a465d9..45dce64d2 100644 --- a/ffi/Cargo.lock +++ b/ffi/Cargo.lock @@ -243,6 +243,7 @@ name = "reject-fixture" version = "0.0.0" dependencies = [ "dep-fixture", + "tls-fixture", ] [[package]] diff --git a/ffi/README.md b/ffi/README.md index 5dc7eb733..041f10992 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -85,8 +85,8 @@ another of its name shares, the facade's root names, or another registry serves 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. +exported error holding one is an object, as it was. A type it cannot reach, such as one no +public path names, or an error taken by value, is held by value as an opaque handle instead. | Rust | C | | --- | --- | @@ -105,7 +105,7 @@ refused. | `Result` | `bool f(..., T *out, E *err)`; an `E` of another crate that implements `Display`, such as `anyhow::Error` or `io::Error`, is `String`, its message | | a returned tuple `(A, B)` | one out pointer each: `void f(..., A *out0, B *out1)` | | a tuple inside another type, or as a field or parameter | `_tuple__`: a struct of fields `_0`, `_1`, and so on; of references only returned | -| `async fn`, or a return that implements `Future` | a future: `f` makes it, `f_poll` polls it, `f_future_free` drops it, and `f_start` makes it and polls it once, returning a handle only if it pends; a function that is not `async` runs at the call, as in Rust | +| `async fn`, or a return that implements `Future` | a future: `f` makes it, `f_poll` polls it, `f_future_free` drops it, and `f_start` makes it and polls it once, returning a handle only if it pends; a function that is not `async` runs at the call, as in Rust, and when its future borrows the arguments, the future owns them as an `async fn`'s does, holding each in place until it drops | | a function returning `Poll` that polls through a `&Context`, a `&mut Context`, or a reference to an object exactly one associated function makes from a `Waker` alone, of a type with no generic parameters, such as kio's `Waiter`, which may be the method's own `&self`, as `Waiter::poll_future`'s is | a future of `T`, as an `async fn`'s: each poll calls the function again with the poll's context, or with an object made from its waker and kept until the next poll, so what it registers stays registered; each other parameter taken by value must be `Copy`; a method polling through its own `&self` is a function without one | | `poll_x`, when `x` exports as a future | left out: the future is its poll | | `bool`, integers but 128-bit, floats, `char` | `bool`, `` types, `float`, `double`, a `uint32_t` code point | @@ -118,6 +118,7 @@ refused. | `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` | `_socket_addr`: its IP's bytes, port, and whether it is IPv6; one of the other family passed to `V4` or `V6` aborts | | `url::Url` | an object `_Url`, made by `_Url_parse`, which fails with the parse error's message, and printed by `_to_string` | | `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | +| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | | `std::time::Instant` | an object `_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq`, with none of its methods | | `tracing::Level` | `_Level`: a C enum of its five levels, `TRACE` to `ERROR` | | `tracing::level_filters::LevelFilter` | `Option`, whose `None` is `OFF` | @@ -156,7 +157,7 @@ A record or enum holds only values and `Copy` handles: one with a field that doe or that holds itself, is an object instead, and the census lists it. A borrowed return is returned as a clone, so it must be `Clone`, and a handle in it is a new handle to the clone, but for an object a `&self` method of an object returns borrowed from its receiver -alone: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it +alone, or an object's `pub` field holds: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it on each use, on one thread at a time where the receiver is not `Sync`. A handle outlives every call, so every lifetime an object takes is `'static`, as is every lifetime that must outlive one; any other lifetime is the call's. A signature may not lend C's borrow for one that is `'static`, but for a diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index a9a5fa3fe..c10132fd2 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -362,6 +362,22 @@ fn main() { if let Poll::Ready(payload) = recv.as_mut().poll(&mut cx) { println!("recv {}", String::from_utf8_lossy(&payload)); } + // The send happens at the call, and the future borrows the channel and the tag. + let mut tagged = pin!(channel.tagged("tag")); + if let Poll::Ready(text) = tagged.as_mut().poll(&mut cx) { + println!("tagged {text}"); + } + // So does a future borrowing an optional slice, which the export owns while it is pending. + let items = [1u32, 2, 3]; + let mut itemized = pin!(channel.itemized(Some(&items))); + if let Poll::Ready(count) = itemized.as_mut().poll(&mut cx) { + println!("itemized {count}"); + } + // Another crate's future borrowing its bytes, which the export owns while it is pending. + let bytes = *b"abc"; + if let Poll::Ready(len) = pin!(api::byte_len(&bytes)).poll(&mut cx) { + println!("byte_len {len}"); + } channel.send(Bytes::from_static(b"sized")); let mut sized = pin!(channel.recv_sized()); if let Poll::Ready((payload, len)) = sized.as_mut().poll(&mut cx) { @@ -585,6 +601,14 @@ fn main() { println!("nudge {} {}", point.x, point.y); let config = api::secure("h3"); println!("secure {} {}", api::alpn_lent(&config), api::alpn(config.clone())); + let cert = api::certify(b"der"); + let chain = vec![api::certify(b"a"), api::certify(b"bc")]; + println!( + "cert {} {} {}", + api::cert_len(&cert), + String::from_utf8_lossy(&api::cert_der(cert)), + api::chain_len(chain) + ); let session = api::resume("h3", 60).unwrap(); println!("resume {} {}", session.alpn(), session.lifetime().seconds); println!("resume err {}", api::resume("", 60).err().unwrap()); @@ -594,6 +618,8 @@ fn main() { println!("lent {} {}", first.add(3), meters.first().count()); meters.clear(); println!("cleared {}", meters.first().count()); + meters.last.add(4); + println!("field lent {}", meters.last.add(1)); let tallies = api::Tallies::new(); tallies.first().bump(); println!("tallied {}", tallies.first().bump()); @@ -752,6 +778,12 @@ fn main() { start == api::later(start, std::time::Duration::ZERO), start == end ); + // An instant lent inside an `Option`, which takes no handle. + println!( + "has_instant {} {}", + api::has_instant(&Some(start)), + api::has_instant(&None) + ); let mut verbosity = api::Verbosity::new(tracing::Level::WARN); println!( "verbosity {} {}", diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 88d8f3b93..f7e2ed8a9 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -453,10 +453,11 @@ impl Meter { } } -/// Owns a meter it lends. +/// Owns a meter it lends, and one in a field, lent as the method's is. #[derive(Default)] pub struct Meters { first: Meter, + pub last: Meter, } impl Meters { @@ -871,6 +872,27 @@ impl Channel { std::future::ready(()) } + /// Sends `tag` at once, as a function that is not `async` runs when called, and returns a + /// future that borrows this channel and `tag`: what it next receives, after `tag`. + pub fn tagged<'a>(&'a self, tag: &'a str) -> impl Future + 'a { + self.send(Bytes::copy_from_slice(tag.as_bytes())); + async move { + let payload = self.recv().await; + format!("{tag} {}", String::from_utf8_lossy(&payload)) + } + } + + /// Sends the sum of `items`, if any, at once, and returns a future that borrows them: + /// their count once this channel next receives. + pub fn itemized<'a>(&'a self, items: Option<&'a [u32]>) -> impl Future + 'a { + let sum: u32 = items.unwrap_or_default().iter().sum(); + self.send(Bytes::copy_from_slice(&sum.to_le_bytes())); + async move { + self.recv().await; + items.map_or(0, <[u32]>::len) + } + } + /// `recv`'s poll, which does not map: left out, since `recv` exports as a future. pub fn poll_recv(&self, cx: &mut std::task::Context<'_>) -> Poll { let mut state = self.state.lock().unwrap(); @@ -2266,6 +2288,65 @@ pub fn alpn_lent(config: &Arc) -> String { config.alpn().to_string() } +/// A certificate of a crate the facade re-exports nothing from, by value, with no public +/// path there, as moq-tokio's rustls root certificates: an opaque handle, which Rust takes +/// back or borrows. +pub fn certify(der: &[u8]) -> tls::held::Cert { + tls::held::Cert::new(der) +} + +/// The length of `bytes`, through another crate's future that borrows them but resolves +/// to an owned count: a future, not an opaque handle. +pub fn byte_len(bytes: &[u8]) -> tls::held::Pending<'_> { + tls::held::Pending(bytes) +} + +/// The length of a certificate [`certify`] made, lent. +pub fn cert_len(cert: &tls::held::Cert) -> usize { + cert.der().len() +} + +/// The bytes of a certificate [`certify`] made, taken back by value. +pub fn cert_der(cert: tls::held::Cert) -> Vec { + cert.der().to_vec() +} + +/// The total length of a chain of certificates, each taken back by value. +pub fn chain_len(chain: Vec) -> usize { + chain.iter().map(|cert| cert.der().len()).sum() +} + +/// Another crate's session with no public path there, which no export returns: left out, since C can never +/// hold one. +pub fn handover(session: tls::held::Handoff) -> u32 { + session.id +} + +/// A certificate's length, or why it is refused: another crate's error, which crosses as +/// its message though `blame` names it as a handle no export returns. +pub fn verify(cert: &tls::held::Cert) -> Result { + match cert.der().len() { + 0 => Err(tls::held::Invalid { + reason: "empty".to_string(), + }), + len => Ok(len as u32), + } +} + +/// `text`'s length, or why it is no certificate: another crate's error borrowing `text`, +/// which crosses as its message, so nothing outlives the call. +pub fn parse_cert(text: &str) -> Result> { + match text.is_empty() { + true => Err(tls::held::Malformed(text)), + false => Ok(text.len() as u32), + } +} + +/// Another crate's error taken back by value, which no export returns: left out. +pub fn blame(err: tls::held::Invalid) -> String { + err.to_string() +} + /// A session of `alpn` lasting `seconds`, from a crate the facade re-exports nothing from: /// its type exports by its path there, and its error crosses as its message. pub fn resume(alpn: &str, seconds: u32) -> Result { @@ -2564,6 +2645,12 @@ pub fn since(later: std::time::Instant, earlier: std::time::Instant) -> Duration later.saturating_duration_since(earlier) } +/// Whether `at` holds an instant, lent inside an `Option`: an instant crosses as a `Copy` +/// object, so lending one inside a value takes no handle. +pub fn has_instant(at: &Option) -> bool { + at.is_some() +} + /// How much to log, as moq-tokio's `Log` holds it: a field of a foreign enum, and its filter. #[non_exhaustive] pub struct Verbosity { diff --git a/ffi/fixtures/reject/Cargo.toml b/ffi/fixtures/reject/Cargo.toml index 9a922c57d..5c7b998e0 100644 --- a/ffi/fixtures/reject/Cargo.toml +++ b/ffi/fixtures/reject/Cargo.toml @@ -12,6 +12,7 @@ name = "reject" [dependencies] dep-fixture = { path = "../dep" } +tls-fixture = { path = "../tls" } [lints] workspace = true diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index d6a237a21..9ba588290 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -1,135 +1,147 @@ -fixtures/reject/src/lib.rs:1000:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1006:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1011:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1016:1: rust2-ffi: cannot export fn `trust`: trait object `dyn Trusted`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:1006:1: note: C cannot implement `Trusted`: unsafe trait -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: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 +fixtures/reject/src/lib.rs:1002:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1008:1: rust2-ffi: cannot export fn `poll_risky`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1024:1: rust2-ffi: cannot export fn `poll_loose`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1031:1: rust2-ffi: cannot export fn `among`: 3 optional borrowed objects, past the 2 Swift takes, which overloads each with and without it since its optional holds an object only by consuming it; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1037:1: rust2-ffi: cannot export fn `wrapped`: error holding an object Swift cannot copy, as `Swift.Error` requires; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1042:1: rust2-ffi: cannot export fn `sum_pair`: array of an element other than u8 `[u16; 2]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1047:1: rust2-ffi: cannot export fn `empty`: empty array `[u8; 0]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1053:1: rust2-ffi: cannot export enum `Wide`: discriminant outside `i32` `Large = 1099511627776`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1055:2: note: has this discriminant +fixtures/reject/src/lib.rs:105:1: rust2-ffi: cannot export fn `forever`: 'static borrow `&'static [u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1060:1: rust2-ffi: cannot export enum `Huge`: discriminant outside `i32` `Large = 18446744073709551616`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1062:2: note: has this discriminant +fixtures/reject/src/lib.rs:1067:1: rust2-ffi: cannot export enum `Top`: discriminant outside `i32` `Large = 340282366920938463463374607431768211455`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1069:2: note: has this discriminant +fixtures/reject/src/lib.rs:1073:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1078:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1084:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1098:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1104:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1109:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1114:1: rust2-ffi: cannot export fn `trust`: trait object `dyn Trusted`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1104:1: note: C cannot implement `Trusted`: unsafe trait +fixtures/reject/src/lib.rs:1119:1: rust2-ffi: cannot export fn `hazard`: trait object `dyn Hazard`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:1109:1: note: C cannot implement `Hazard`: unsafe fn `risk` +fixtures/reject/src/lib.rs:111:1: rust2-ffi: cannot export fn `boxed`: reference inside a parameter `std::boxed::Box<&str>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1124:1: rust2-ffi: cannot export fn `wide_non_zero`: NonZero `u128`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1129:1: rust2-ffi: cannot export fn `hidden_answer`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1134:1: rust2-ffi: cannot export fn `hidden_items`: opaque type `impl std::marker::Copy`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1139:1: rust2-ffi: cannot export fn `hidden_option`: opaque type `impl std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1144:1: rust2-ffi: cannot export fn `boxed_bytes`: boxed slice of bytes `std::boxed::Box<[u8]>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:11:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:128:1: rust2-ffi: cannot export fn `measure`: foreign type `dep::Size`; foreign type `dep::Area`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:133:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:143:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:162:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject::Ping>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:122:1: rust2-ffi: cannot export fn `parse_later`: returned object that borrows `impl std::future::Future>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:136:1: rust2-ffi: cannot export fn `poll_ready`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:153:2: rust2-ffi: cannot export method `Link::session`: borrowed return that is not Clone `tls::held::Handoff`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:16:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:173:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:176:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject::Grow<(u32,)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:187:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:196:1: rust2-ffi: cannot export fn `shell`: refused type `reject::Shell<(u32,)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:207:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:217:1: rust2-ffi: cannot export fn `listed`: refused type `reject::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:222:1: rust2-ffi: cannot export instance `Fixed<'a'>`: const argument `'a'`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:225:1: rust2-ffi: cannot export fn `fixed`: refused type `reject::Fixed<'a'>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:230:9: rust2-ffi: cannot export use `HashSet`: re-export of the standard library's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:233:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter or a return; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:23:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:241:2: rust2-ffi: cannot export field `Tag::label`: 'static borrow `&'static str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:251:1: rust2-ffi: cannot export fn `gather`: closure signature `std::vec::Vec`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:256:1: rust2-ffi: cannot export fn `attempt`: closure signature `std::result::Result`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:261:1: rust2-ffi: cannot export fn `consume`: reader not lent as &mut `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:266:1: rust2-ffi: cannot export fn `retain`: reader kept past the call `R`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:271:1: rust2-ffi: cannot export fn `rewrite`: reader bound `std::io::Write`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:276:1: rust2-ffi: cannot export fn `read_later`: reader kept past the call `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:281:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:287:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:28:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:293:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:298:1: rust2-ffi: cannot export fn `count_words`: Vec of references `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:303:1: rust2-ffi: cannot export fn `count_some`: Vec of references `std::option::Option<&str>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:308:1: rust2-ffi: cannot export fn `count_slice`: slice of references `&str`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:313:1: rust2-ffi: cannot export fn `peek_all`: reference to a handle inside a value `[Opaque]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:318:1: rust2-ffi: cannot export fn `none_opaque`: borrowed return that is not Clone `[Opaque]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:330:1: rust2-ffi: cannot export fn `stash`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:345:1: rust2-ffi: cannot export fn `hold`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:350:1: rust2-ffi: cannot export fn `bound`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:355:1: rust2-ffi: cannot export fn `kept`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:369:1: rust2-ffi: cannot export fn `holder`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:37:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:383:1: rust2-ffi: cannot export fn `lender`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:398:1: rust2-ffi: cannot export fn `outlived`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:413:1: rust2-ffi: cannot export fn `paired`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:42:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:436:1: rust2-ffi: cannot export fn `pinner`: generic parameter `std::convert::Into`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:451:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:443:1: note: applies past the recursion limit -fixtures/reject/src/lib.rs:46:1: rust2-ffi: cannot export macro `noop`: macro; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:481:1: rust2-ffi: cannot export fn `call`: ambiguous conversion `std::vec::Vec`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:458:1: note: `std::string::String` converts too, which C passes alike -fixtures/reject/src/lib.rs:486:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:491:1: rust2-ffi: cannot export fn `naturals`: foreign type `std::ops::RangeFrom`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:496:1: rust2-ffi: cannot export fn `opaques`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:501:1: rust2-ffi: cannot export fn `tried`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:506:1: rust2-ffi: cannot export fn `eventually`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:532:1: rust2-ffi: cannot export fn `tallied`: unmet bound `u32: std::convert::From`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:537:1: rust2-ffi: cannot export fn `drain`: trait object `dyn Source`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:511:1: note: C cannot implement `Source`: callback signature `items` -fixtures/reject/src/lib.rs:542:1: rust2-ffi: cannot export fn `summed_forever`: 'static borrow `&'static [u32]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:547:1: rust2-ffi: cannot export fn `retext_last`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:547:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:54:1: rust2-ffi: cannot export fn `excluded`: excluded type `Excluded`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:554:1: rust2-ffi: cannot export fn `outlast`: 'static borrow `&'b [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:554:20: note: `'b` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:561:1: rust2-ffi: cannot export fn `retext_into`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:561:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:570:1: rust2-ffi: cannot export fn `ones`: foreign type `std::iter::Repeat`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:576:1: rust2-ffi: cannot export fn `long_words`: foreign type `std::iter::Filter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:582:1: rust2-ffi: cannot export fn `kept_in`: foreign type `std::iter::Filter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:599:1: rust2-ffi: cannot export fn `launched`: foreign type `std::iter::Chain`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:59:1: rust2-ffi: cannot export fn `letters`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:616:1: rust2-ffi: cannot export fn `launches`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:639:1: rust2-ffi: cannot export fn `pumped`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:653:1: rust2-ffi: cannot export fn `skipped`: foreign type `std::iter::Skip`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:658:1: rust2-ffi: cannot export fn `merged`: foreign type `std::iter::Copied`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:665:1: rust2-ffi: cannot export fn `values`: foreign type `std::collections::btree_map::IntoValues`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:671:1: rust2-ffi: cannot export fn `floats`: collection not built from its items `std::collections::BTreeSet`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:676:1: rust2-ffi: cannot export fn `zeros`: foreign type `std::iter::RepeatN`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:681:1: rust2-ffi: cannot export fn `successes`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `measure`: foreign type `tls::held::Local`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:178:1: rust2-ffi: cannot export fn `sealed`: refused type `reject::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:184:1: rust2-ffi: cannot export fn `echo`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:189:1: rust2-ffi: cannot export fn `blame`: borrowing output of a future from a function that is not async `std::result::Result>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:194:1: rust2-ffi: cannot export fn `relay`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:199:1: rust2-ffi: cannot export fn `resolve`: borrowing output of a future from a function that is not async `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:204:1: rust2-ffi: cannot export fn `spend`: closure signature `tls::held::Token`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:209:1: rust2-ffi: cannot export fn `mint`: closure signature `tls::held::Token`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:219:1: rust2-ffi: cannot export fn `spent`: reference to a handle inside a value `[tls::held::Token]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:21:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `adopt`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:241:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:260:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject::Ping>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:271:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:274:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject::Grow<(u32,)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:285:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:294:1: rust2-ffi: cannot export fn `shell`: refused type `reject::Shell<(u32,)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:305:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:30:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:310:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:315:1: rust2-ffi: cannot export fn `listed`: refused type `reject::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:320:1: rust2-ffi: cannot export instance `Fixed<'a'>`: const argument `'a'`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:323:1: rust2-ffi: cannot export fn `fixed`: refused type `reject::Fixed<'a'>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:328:9: rust2-ffi: cannot export use `HashSet`: re-export of the standard library's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:331:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter or a return; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:339:2: rust2-ffi: cannot export field `Tag::label`: 'static borrow `&'static str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:349:1: rust2-ffi: cannot export fn `gather`: closure signature `std::vec::Vec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:354:1: rust2-ffi: cannot export fn `attempt`: closure signature `std::result::Result`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:359:1: rust2-ffi: cannot export fn `consume`: reader not lent as &mut `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:35:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:364:1: rust2-ffi: cannot export fn `retain`: reader kept past the call `R`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:369:1: rust2-ffi: cannot export fn `rewrite`: reader bound `std::io::Write`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:374:1: rust2-ffi: cannot export fn `read_later`: reader kept past the call `impl std::io::Read + std::io::Seek`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:379:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:385:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:391:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:396:1: rust2-ffi: cannot export fn `count_words`: Vec of references `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:39:1: rust2-ffi: cannot export macro `noop`: macro; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:401:1: rust2-ffi: cannot export fn `count_some`: Vec of references `std::option::Option<&str>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:406:1: rust2-ffi: cannot export fn `count_slice`: slice of references `&str`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:411:1: rust2-ffi: cannot export fn `peek_all`: reference to a handle inside a value `[Opaque]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:416:1: rust2-ffi: cannot export fn `none_opaque`: borrowed return that is not Clone `[Opaque]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:428:1: rust2-ffi: cannot export fn `stash`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:443:1: rust2-ffi: cannot export fn `hold`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:448:1: rust2-ffi: cannot export fn `bound`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:453:1: rust2-ffi: cannot export fn `kept`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:467:1: rust2-ffi: cannot export fn `holder`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:47:1: rust2-ffi: cannot export fn `excluded`: excluded type `Excluded`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:481:1: rust2-ffi: cannot export fn `lender`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:496:1: rust2-ffi: cannot export fn `outlived`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:511:1: rust2-ffi: cannot export fn `paired`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:52:1: rust2-ffi: cannot export fn `letters`: Range `char`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:534:1: rust2-ffi: cannot export fn `pinner`: generic parameter `std::convert::Into`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:549:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:541:1: note: applies past the recursion limit +fixtures/reject/src/lib.rs:579:1: rust2-ffi: cannot export fn `call`: ambiguous conversion `std::vec::Vec`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:556:1: note: `std::string::String` converts too, which C passes alike +fixtures/reject/src/lib.rs:584:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:589:1: rust2-ffi: cannot export fn `naturals`: foreign type `std::ops::RangeFrom`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:594:1: rust2-ffi: cannot export fn `opaques`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:599:1: rust2-ffi: cannot export fn `tried`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:604:1: rust2-ffi: cannot export fn `eventually`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:630:1: rust2-ffi: cannot export fn `tallied`: unmet bound `u32: std::convert::From`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:635:1: rust2-ffi: cannot export fn `drain`: trait object `dyn Source`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:609:1: note: C cannot implement `Source`: callback signature `items` +fixtures/reject/src/lib.rs:640:1: rust2-ffi: cannot export fn `summed_forever`: 'static borrow `&'static [u32]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:645:1: rust2-ffi: cannot export fn `retext_last`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:645:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:652:1: rust2-ffi: cannot export fn `outlast`: 'static borrow `&'b [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:652:20: note: `'b` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:659:1: rust2-ffi: cannot export fn `retext_into`: 'static borrow `&'a [std::string::String]`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:659:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:668:1: rust2-ffi: cannot export fn `ones`: foreign type `std::iter::Repeat`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:66:2: rust2-ffi: cannot export method `Text::view`: returned object that borrows `Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:674:1: rust2-ffi: cannot export fn `long_words`: foreign type `std::iter::Filter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:680:1: rust2-ffi: cannot export fn `kept_in`: foreign type `std::iter::Filter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:697:1: rust2-ffi: cannot export fn `launched`: foreign type `std::iter::Chain`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:6:1: rust2-ffi: cannot export fn `pair`: tuple of references `(&str, u8)`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:701:1: rust2-ffi: cannot export fn `allocated`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:708:1: rust2-ffi: cannot export fn `flattened`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:732:1: rust2-ffi: cannot export fn `lent`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:73:2: rust2-ffi: cannot export method `Text::view`: returned object that borrows `Text<'_>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:750:1: rust2-ffi: cannot export fn `halves`: foreign type `std::str::Split`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:755:1: rust2-ffi: cannot export fn `settled`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:760:1: rust2-ffi: cannot export fn `poll_named`: poll's parameter taken by value that is not Copy `std::string::String`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:766:1: rust2-ffi: cannot export fn `poll_first`: borrowed Poll `&u8`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:772:1: rust2-ffi: cannot export fn `poll_until`: poll's parameter taken by value that is not Copy `impl Fn(u8) -> bool`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:783:1: rust2-ffi: cannot export fn `context_later`: Context of a function returning a future; future not Send; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:802:1: rust2-ffi: cannot export fn `poll_ticket`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:807:1: rust2-ffi: cannot export fn `poll_both`: several task parameters; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:814:1: rust2-ffi: cannot export fn `poll_bump`: &mut of a value in a future; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:821:1: rust2-ffi: cannot export fn `peek_some`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:826:1: rust2-ffi: cannot export fn `bump_some`: &mut of a value inside an Option `std::option::Option<&mut u32>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:833:1: rust2-ffi: cannot export fn `rest`: returned borrow of a value written back `&[u8]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:838:1: rust2-ffi: cannot export fn `fill`: returned borrow of a value written back `impl std::future::Future`; &mut of a value in a future; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:843:1: rust2-ffi: cannot export fn `zero`: &mut of a slice `[u8]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:848:1: rust2-ffi: cannot export fn `reseat`: &mut of another crate's Arc `std::sync::Arc`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:84:1: rust2-ffi: cannot export fn `first`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:861:2: rust2-ffi: cannot export method `Keeper::check`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:872:9: rust2-ffi: cannot export use `dep`: re-export of a whole crate `dep`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:875:9: rust2-ffi: cannot export use `renamed`: re-export of a whole crate `dep`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:886:2: rust2-ffi: cannot export method `Tally::poll_bump`: `&mut self` of a value; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:904:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:910:1: rust2-ffi: cannot export fn `poll_risky`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:926:1: rust2-ffi: cannot export fn `poll_loose`: Poll with no Context or waiter parameter `std::task::Poll<()>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:933:1: rust2-ffi: cannot export fn `among`: 3 optional borrowed objects, past the 2 Swift takes, which overloads each with and without it since its optional holds an object only by consuming it; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:939:1: rust2-ffi: cannot export fn `wrapped`: error holding an object Swift cannot copy, as `Swift.Error` requires; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:944:1: rust2-ffi: cannot export fn `sum_pair`: array of an element other than u8 `[u16; 2]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:949:1: rust2-ffi: cannot export fn `empty`: empty array `[u8; 0]`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:955:1: rust2-ffi: cannot export enum `Wide`: discriminant outside `i32` `Large = 1099511627776`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:957:2: note: has this discriminant -fixtures/reject/src/lib.rs:962:1: rust2-ffi: cannot export enum `Huge`: discriminant outside `i32` `Large = 18446744073709551616`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:964:2: note: has this discriminant -fixtures/reject/src/lib.rs:969:1: rust2-ffi: cannot export enum `Top`: discriminant outside `i32` `Large = 340282366920938463463374607431768211455`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:971:2: note: has this discriminant -fixtures/reject/src/lib.rs:975:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:980:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:986:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:714:1: rust2-ffi: cannot export fn `launches`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:737:1: rust2-ffi: cannot export fn `pumped`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:751:1: rust2-ffi: cannot export fn `skipped`: foreign type `std::iter::Skip`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:756:1: rust2-ffi: cannot export fn `merged`: foreign type `std::iter::Copied`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:763:1: rust2-ffi: cannot export fn `values`: foreign type `std::collections::btree_map::IntoValues`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:769:1: rust2-ffi: cannot export fn `floats`: collection not built from its items `std::collections::BTreeSet`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:774:1: rust2-ffi: cannot export fn `zeros`: foreign type `std::iter::RepeatN`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:779:1: rust2-ffi: cannot export fn `successes`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:77:1: rust2-ffi: cannot export fn `first`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:799:1: rust2-ffi: cannot export fn `allocated`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:806:1: rust2-ffi: cannot export fn `flattened`: foreign type `std::iter::Flatten`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:830:1: rust2-ffi: cannot export fn `lent`: foreign type `std::vec::IntoIter`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:848:1: rust2-ffi: cannot export fn `halves`: foreign type `std::str::Split`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:853:1: rust2-ffi: cannot export fn `settled`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:858:1: rust2-ffi: cannot export fn `poll_named`: poll's parameter taken by value that is not Copy `std::string::String`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:864:1: rust2-ffi: cannot export fn `poll_first`: borrowed Poll `&u8`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:870:1: rust2-ffi: cannot export fn `poll_until`: poll's parameter taken by value that is not Copy `impl Fn(u8) -> bool`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:881:1: rust2-ffi: cannot export fn `context_later`: Context of a function returning a future; future not Send; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:900:1: rust2-ffi: cannot export fn `poll_ticket`: Poll with no Context or waiter parameter `std::task::Poll`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:905:1: rust2-ffi: cannot export fn `poll_both`: several task parameters; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:912:1: rust2-ffi: cannot export fn `poll_bump`: &mut of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:919:1: rust2-ffi: cannot export fn `peek_some`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:924:1: rust2-ffi: cannot export fn `bump_some`: &mut of a value inside an Option `std::option::Option<&mut u32>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:931:1: rust2-ffi: cannot export fn `rest`: returned borrow of a value written back `&[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:936:1: rust2-ffi: cannot export fn `fill`: returned borrow of a value written back `impl std::future::Future`; &mut of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:941:1: rust2-ffi: cannot export fn `zero`: &mut of a slice `[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:946:1: rust2-ffi: cannot export fn `reseat`: &mut of another crate's Arc `std::sync::Arc`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:959:2: rust2-ffi: cannot export method `Keeper::check`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:970:9: rust2-ffi: cannot export use `dep`: re-export of a whole crate `dep`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:973:9: rust2-ffi: cannot export use `renamed`: re-export of a whole crate `dep`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:984:2: rust2-ffi: cannot export method `Tally::poll_bump`: `&mut self` of a value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:99:2: rust2-ffi: cannot export method `Text::later`: returned object that borrows `impl std::future::Future>`; exclude it in the config to leave it out diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index dfd2b4eaa..6e6b20a1b 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -17,13 +17,6 @@ pub fn generic(value: T) -> T { value } -/// A future that borrows its argument, from a function that runs when called: the export -/// would have to keep the argument alive past the call. -#[allow(clippy::manual_async_fn, reason = "the construct under test")] -pub fn borrowing(name: &str) -> impl Future + '_ { - async move { name.len() } -} - /// An option inside an option, through a `Box`: C has one `None` per option. pub fn nested(value: Option>>) -> bool { value.is_some() @@ -124,14 +117,119 @@ pub struct Size { pub bytes: u64, } -/// Another crate's types, which the facade does not re-export. -pub fn measure(size: dep::Size) -> dep::Area { - dep::Area::new(size) +/// Another crate's error borrowing `text`, the output of a future: the glue awaits the +/// future past the call that owns `text`, so the error's borrow would outlive it. +pub async fn parse_later(text: &str) -> Result> { + match text.is_empty() { + true => Err(tls::held::Malformed(text)), + false => Ok(text.len() as u32), + } +} + +/// A waiter of another crate, which a handle holds by value. +pub fn waiter() -> tls::held::Waiter { + tls::held::Waiter::new(std::task::Waker::noop().clone()) +} + +/// Not a poll through [`waiter`]'s: the glue cannot name the type a handle holds to make one +/// from the poll's waker. +pub fn poll_ready(_waiter: &tls::held::Waiter) -> std::task::Poll { + std::task::Poll::Ready(1) +} + +/// An object holding another crate's session, which C holds as a handle. +pub struct Link { + session: tls::held::Handoff, +} + +impl Link { + pub fn new() -> Self { + Self { + session: tls::held::Handoff { id: 1 }, + } + } + + /// Not lent: a handle holds another crate's value only erased, and by value. + pub fn session(&self) -> &tls::held::Handoff { + &self.session + } + + /// What makes the session a value C holds. + pub fn take(self) -> tls::held::Handoff { + self.session + } +} + +impl Default for Link { + fn default() -> Self { + Self::new() + } +} + +/// Another crate's type that is not `Send`, which no handle may hold. +pub fn measure(local: tls::held::Local) -> u32 { + local.get() } /// A generic type, which exports at the instances its exports name. pub struct Cell(T); +/// An instance naming another crate's type that a handle holds by value, erased. +pub fn sealed(cert: tls::held::Cert) -> Cell { + Cell(cert) +} + +/// A future returned by a function that is not async, whose output borrows what the +/// future holds only until it completes. +pub fn echo(tag: &str) -> impl std::future::Future + '_ { + async move { tag } +} + +/// As `echo`, but the output borrows only inside an error that crosses as its message. +pub fn blame(tag: &str) -> impl std::future::Future>> + '_ { + async move { Err(tls::held::Wrapped(tag, 0)) } +} + +/// As `echo`, but its borrowed output named only by a supertrait of the bound. +pub fn relay(tag: &str) -> impl tls::held::Borrowing<'_> { + async move { tag } +} + +/// As `echo`, but through a future that is not an `impl Future`. +pub fn resolve(tag: &str) -> tls::held::Lend<'_, u8> { + tls::held::Lend(tag, std::marker::PhantomData) +} + +/// A closure taking a `Copy` value of another crate's, which a handle holds. +pub fn spend(f: impl FnOnce(tls::held::Token) -> u32) -> u32 { + f(tls::held::Token(1)) +} + +/// A closure returning one. +pub fn mint(f: impl FnOnce() -> tls::held::Token) -> u32 { + f().0 +} + +/// Returns another crate's `Copy` value, which a handle holds. +pub fn token() -> tls::held::Token { + tls::held::Token(2) +} + +/// Borrows a slice of them, whose handles C would have to give up. +pub fn spent(tokens: &[tls::held::Token]) -> u32 { + tokens.iter().map(|t| t.0).sum() +} + +/// Returns another crate's value, which a handle holds. +pub fn issue() -> tls::held::Cert { + tls::held::Cert::new(b"der") +} + +/// Takes what converts into it, which only inference could name in the glue. +pub fn adopt(cert: impl Into) -> usize { + cert.into().der().len() +} + impl Cell { pub fn new(value: T) -> Self { Self(value) diff --git a/ffi/fixtures/tls/Cargo.toml b/ffi/fixtures/tls/Cargo.toml index c9bfe1869..eca5feda2 100644 --- a/ffi/fixtures/tls/Cargo.toml +++ b/ffi/fixtures/tls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tls-fixture" -description = "A crate the api fixture names behind an Arc but does not re-export, as moq-tokio names rustls" +description = "A crate the api fixture names behind an Arc or by value but does not re-export, as moq-tokio names rustls" version = "0.0.0" edition = "2024" license = "MIT OR Apache-2.0" diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index a083fcd6b..5bbd68985 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -70,3 +70,127 @@ impl std::fmt::Display for Error { f.write_str(&self.0) } } + +/// Types with no public path in this crate, as rustls's are where the facade names a +/// module `rustls` of its own: nothing exports them with their API, so an export that +/// names one by value holds it in an opaque handle. +#[doc(hidden)] +pub mod held { + /// A certificate: an opaque handle wherever the api fixture takes or returns one by + /// value, as moq-tokio's TLS listener loads rustls's root certificates. + #[derive(Clone, Debug)] + pub struct Cert { + der: Vec, + } + + impl Cert { + pub fn new(der: &[u8]) -> Self { + Self { der: der.to_vec() } + } + + pub fn der(&self) -> &[u8] { + &self.der + } + } + + /// A session handed over from elsewhere, which no export of the api fixture returns: C + /// can never hold one. + #[derive(Debug)] + pub struct Handoff { + pub id: u32, + } + + /// Why a certificate is refused, which the api fixture's `verify` returns as its message + /// and `blame` takes back, though no export returns one: C never holds one. + #[derive(Debug)] + pub struct Invalid { + pub reason: String, + } + + impl std::fmt::Display for Invalid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "invalid certificate: {}", self.reason) + } + } + + impl std::error::Error for Invalid {} + + /// Why text is not a certificate, borrowing the text: an error that crosses as its + /// message, so the borrow ends with the call. + #[derive(Debug)] + pub struct Malformed<'a>(pub &'a str); + + impl std::fmt::Display for Malformed<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "malformed: {}", self.0) + } + } + + impl std::error::Error for Malformed<'_> {} + + /// What a poll registers its waker with, made from the waker alone, as kio's `Waiter` is. + pub struct Waiter(std::task::Waker); + + impl Waiter { + pub fn new(waker: std::task::Waker) -> Self { + Self(waker) + } + + pub fn wake(&self) { + self.0.wake_by_ref(); + } + } + + /// A count that is not `Send`, which the reject fixture takes by value: no handle may hold it. + pub struct Local(std::rc::Rc); + + impl Local { + pub fn get(&self) -> u32 { + *self.0 + } + } + + /// An error that borrows and takes a type parameter, so no handle holds it: it crosses as + /// its message. + #[derive(Debug)] + pub struct Wrapped<'a, T>(pub &'a str, pub T); + + impl std::fmt::Display for Wrapped<'_, T> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0) + } + } + + /// A future that is not an `impl Future`, resolving to what it borrows; its type + /// parameter keeps any handle from holding it. + pub struct Lend<'a, T>(pub &'a str, pub std::marker::PhantomData); + + impl<'a, T> std::future::Future for Lend<'a, T> { + type Output = &'a str; + + fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll<&'a str> { + std::task::Poll::Ready(self.0) + } + } + + /// A future named by a trait of its own, whose borrowed output only its supertrait names. + pub trait Borrowing<'a>: std::future::Future {} + + impl<'a, F: std::future::Future> Borrowing<'a> for F {} + + /// A future that is not an `impl Future`, borrowing what it reads but resolving to an + /// owned count. + pub struct Pending<'a>(pub &'a [u8]); + + impl std::future::Future for Pending<'_> { + type Output = usize; + + fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll { + std::task::Poll::Ready(self.0.len()) + } + } + + /// A `Copy` token, which an opaque handle holds by value. + #[derive(Clone, Copy, Debug)] + pub struct Token(pub u32); +} diff --git a/ffi/justfile b/ffi/justfile index bd8eeef78..8e31a847a 100644 --- a/ffi/justfile +++ b/ffi/justfile @@ -374,8 +374,11 @@ standin checkout="": src=$(cygpath -m "$src") fi dir=target/moq-ffi - # moq-ffi's dependencies, moq-tokio with its default features as moq-ffi has them. + # moq-ffi's dependencies, each with the features moq-ffi turns on, such as moq-mux's + # async wrappers, read from its manifest. deps=(hang kio moq-mux moq-net moq-pattern moq-tokio) + features=$(cd "$src" && cargo metadata --format-version 1 --no-deps \ + | jq -c '[.packages[] | select(.name == "moq-ffi") | .dependencies[] | select(.kind == null) | {key: .name, value: .features}] | from_entries') mkdir -p "$dir/src" # Replace a file only when its content changes, so an unchanged stand-in, and the # export over it, stay fresh. @@ -392,7 +395,8 @@ standin checkout="": # The prefix of every C name. printf '[lib]\nname = "moq"\n\n[dependencies]\n' for name in "${deps[@]}"; do - printf '%s = { path = "%s/rs/%s" }\n' "$name" "$src" "$name" + on=$(jq -r --arg name "$name" '.[$name] // [] | map(@json) | join(", ")' <<< "$features") + printf '%s = { path = "%s/rs/%s", features = [%s] }\n' "$name" "$src" "$name" "$on" done printf '\n[workspace]\n' # moq's profiles, which the export carries as it would moq-ffi's own; the dev ones diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index 96a64d9d8..4f87d828e 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -3,7 +3,6 @@ # 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. exclude = [ - "Client::connect", "bytes", "clock::Deadlines::enter", "clock::Entered", @@ -17,15 +16,11 @@ exclude = [ "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", @@ -69,8 +64,8 @@ exclude = [ "rustls::ConfigBuilder", "rustls::client::Resumption::store", "rustls_pki_types::CertificateDer::from_slice", + "rustls_pki_types::Der::from_slice", "tokio::server::Config::websocket", "tokio::server::Request::within", - "tokio::tls::Listen::load_roots", "tokio::tls::Serve::resolver", ] diff --git a/ffi/runtime/rt.rs b/ffi/runtime/rt.rs index 7e1da1895..89e8c27a6 100644 --- a/ffi/runtime/rt.rs +++ b/ffi/runtime/rt.rs @@ -81,6 +81,80 @@ impl Opaque { } } +/// An argument a future borrows, kept in place on the heap until the future is dropped. +pub struct Pinned(std::ptr::NonNull); + +// It owns its `T`, as a `Box` does. +unsafe impl Send for Pinned {} +unsafe impl Sync for Pinned {} + +impl Pinned { + pub fn new(value: T) -> Self { + Self(std::ptr::NonNull::from(Box::leak(Box::new(value)))) + } + + /// The value, lent past this borrow of its holder. + /// + /// # Safety + /// + /// Called once, and the borrow ends before the holder drops, as [`Holding`] ensures. + pub unsafe fn get(&self) -> &'static mut T { + unsafe { &mut *self.0.as_ptr() } + } +} + +impl Drop for Pinned { + fn drop(&mut self) { + drop(unsafe { Box::from_raw(self.0.as_ptr()) }); + } +} + +/// A future and the arguments it borrows, which drop after it: fields drop in order. +pub struct Holding { + future: F, + _held: H, +} + +impl Holding { + pub fn new(future: F, held: H) -> Self { + Self { future, _held: held } + } +} + +impl std::future::Future for Holding { + type Output = F::Output; + + fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll { + // The future is pinned with its holder and never moves out; the held values are + // never pinned. + unsafe { self.map_unchecked_mut(|holding| &mut holding.future) }.poll(cx) + } +} + +/// Another crate's value, held erased by its handle, which the glue never names. +pub struct Owned(Box); + +impl Owned { + pub fn new(value: T) -> Self { + Self(Box::new(value)) + } + + /// The value it holds, lent. + pub fn get(&self, what: &str) -> &T { + (self.0.downcast_ref()).unwrap_or_else(|| fail(what, "an opaque handle holds another type")) + } + + /// The value it holds, lent exclusively. + pub fn get_mut(&mut self, what: &str) -> &mut T { + (self.0.downcast_mut()).unwrap_or_else(|| fail(what, "an opaque handle holds another type")) + } + + /// The value it holds, taken back. + pub fn take(self, what: &str) -> T { + *(self.0.downcast()).unwrap_or_else(|_| fail(what, "an opaque handle holds another type")) + } +} + /// Bytes across the ABI. Returned, an owned buffer the caller frees once. Passed in by /// value, one with an owner is Rust's own, which it takes without a copy, and one without /// is a view it copies or borrows for the call; behind a pointer, as an array's items are, diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 53749b7f8..46a9e237f 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -30,7 +30,7 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use crate::config; use crate::ir::{ - Access, Api, Callback, Closure, Collection, Constant, Dyn, Enum, Family, Field, Function, Home, Int, Literal, + Access, Api, Callback, Closure, Collection, Constant, Dyn, Enum, Family, Field, Function, Held, Home, Int, Literal, Mutability, Object, On, Param, Path, Receiver, Record, Task, TaskKind, Traits, Type, Variant, }; @@ -54,6 +54,10 @@ const FOREIGN: [(&str, &str, &str); 3] = [ ("std", "Instant", "Instant"), ]; +/// The construct of another crate's type named both by value and in an `Arc`, whose handle +/// holds the `Arc`. +const BOTH: &str = "another crate's type both by value and in an Arc"; + /// The construct of an instance inference missed: a bug in the exporter, not the crate. pub const NOT_INFERRED: &str = "instance not inferred"; @@ -258,9 +262,15 @@ struct Collector<'tcx> { /// The standard library's crates, `core`, `alloc`, and `std`, known by what each /// defines, since the facade or another crate may share their names. sysroot: Vec, - /// Each type in [`FOREIGN`] that some crate builds with and no export is, and the - /// object it exports as. + /// Each type in [`FOREIGN`] that some crate builds with and no export is, and each other + /// crate's type a signature names behind an `Arc` or by value, and the object it exports as. foreign: Vec<(DefId, usize)>, + /// The types of [`Self::foreign`] signatures name by value, which their handles hold + /// rather than an `Arc` of them. + owned: Vec, + /// Types signatures name both by value and behind an `Arc`: their handles hold the `Arc`, + /// so the value is refused. + both: Vec, /// `tracing::Level`, where some crate builds with it and no export is it. level: Option, /// `std::ops::Bound`, and `std::ops::RangeBounds`, which names it. @@ -391,6 +401,8 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { json_map, sysroot: sysroot.clone(), foreign: Vec::new(), + owned: Vec::new(), + both: Vec::new(), level: None, bound, range_bounds, @@ -856,12 +868,10 @@ impl<'tcx> Collector<'tcx> { .filter_map(|arg| arg.as_type()) .filter(|&ty| seen.insert(ty)) .collect(); + for ty in candidates.iter().chain(&named) { + self.held_forms(*ty); + } for ty in types { - if let Some(inner) = self.opaque_arc(ty) - && !self.foreign.iter().any(|&(other, _)| other == inner) - { - self.foreign.push((inner, 0)); - } match self.admit(ty) { Some((key, Ok(site))) if !self.instances.iter().any(|other| other.key == key) => { self.instances.push(site) @@ -900,6 +910,75 @@ impl<'tcx> Collector<'tcx> { .then_some(did) } + /// The type a handle holds by value, if it exports as an opaque handle: as + /// [`Self::opaque_arc`]'s, a type of a crate the walk from the root does not reach, + /// taking no type parameters, and `Send` and `Sync`, but not an iterator or a future, + /// nor one that exports by its own crate's path. Its lifetimes are `'static`, as an object's are. + fn opaque_value(&self, ty: Ty<'tcx>) -> Option { + let ty::Adt(adt, args) = ty.kind() else { return None }; + let did = adt.did(); + let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); + let held = !self.walked(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; + // Each lifetime is `'static` in the export, as an object's is. + let erasable = args.iter().all(|arg| matches!(arg.kind(), GenericArgKind::Lifetime(_))); + // Asked of a signature's type, whose lifetimes may be bound by it. + let ty = ty::fold_regions(self.tcx, ty, |_, _| self.tcx.lifetimes.re_erased); + // An iterator crosses as the array of its items instead, and a future as a future. + let iterator = implements(self.tcx, ty, did, sym::Iterator); + let future = (self.tcx.lang_items().future_trait()).is_some_and(|tr| { + let (infcx, env) = (self.tcx.infer_ctxt()).build_with_typing_env(TypingEnv::fully_monomorphized()); + infcx.type_implements_trait(tr, [ty], env).must_apply_modulo_regions() + }); + (held + && erasable + && !iterator + && !future + && self.is_send(ty, TypingEnv::fully_monomorphized()) + && self.is_sync(ty) + && !self.reaches(ty, did)) + .then_some(did) + } + + /// Whether `did`, the type of `ty`, exports with its API by its public path in its own + /// crate once a signature names it: an error never does, crossing as its message. + fn reaches(&self, ty: Ty<'tcx>, did: DefId) -> bool { + self.reachable(did) && !implements(self.tcx, ty, did, rustc_span::Symbol::intern("Error")) + } + + /// Whether `ty` is another crate's type that an opaque handle holds, by value or behind + /// an `Arc`. + fn is_opaque(&self, ty: Ty<'tcx>) -> bool { + self.opaque_arc(ty).is_some() || self.opaque_value(ty).is_some() + } + + /// Record each other crate's type `ty` names behind an `Arc` or by value, which an + /// opaque handle holds: an `Arc`'s type is not also by value. + fn held_forms(&mut self, ty: Ty<'tcx>) { + let mut walker = ty.walk(); + while let Some(arg) = walker.next() { + let Some(ty) = arg.as_type() else { continue }; + let (did, owned) = match (self.opaque_arc(ty), self.opaque_value(ty)) { + (Some(did), _) => (did, false), + (None, Some(did)) => (did, true), + (None, None) => continue, + }; + walker.skip_current_subtree(); + match self.foreign.iter().any(|&(other, _)| other == did) { + false => { + self.foreign.push((did, 0)); + if owned { + self.owned.push(did); + } + } + true if self.owned.contains(&did) != owned && !self.both.contains(&did) => { + self.owned.retain(|&other| other != did); + self.both.push(did); + } + true => {} + } + } + } + /// Whether a foreign type exports as an opaque handle rather than by its role in /// [`FOREIGN`]. fn opaque(&self, did: DefId) -> bool { @@ -943,9 +1022,14 @@ impl<'tcx> Collector<'tcx> { ); for site in sites { let adt = tcx.adt_def(site.key.def_id); - // An object's private fields are no part of its API. - let fields = adt.all_fields().filter(|field| field.vis.is_public()); - named.extend(fields.map(|field| field.ty(tcx, site.args).skip_norm_wip())); + // An object's private fields are no part of its API, nor are those the config + // leaves out. + for field in adt.all_fields().filter(|field| field.vis.is_public()) { + let shown = [&site.shown[..], &[field.name.to_string()]].concat(); + if self.field_key(&site, field.name, &shown).is_some() { + named.push(field.ty(tcx, site.args).skip_norm_wip()); + } + } for (item, parent, shown, hidden) in self.members(&site) { match item.kind { _ if hidden => {} @@ -980,11 +1064,13 @@ impl<'tcx> Collector<'tcx> { int(args.type_at(0)).is_none() } ty::Adt(adt, _) => { - tcx.lang_items().string() != Some(adt.did()) - && self.bytes != Some(adt.did()) - && !tcx.is_diagnostic_item(rustc_span::Symbol::intern("Duration"), adt.did()) - && !self.exported(adt.did().krate) - && !self.foreign.iter().any(|&(ty, _)| ty == adt.did()) + let mapped = tcx.lang_items().string() == Some(adt.did()) + || self.bytes == Some(adt.did()) + || tcx.is_diagnostic_item(rustc_span::Symbol::intern("Duration"), adt.did()) + || self.exported(adt.did().krate) + || self.foreign.iter().any(|&(ty, _)| ty == adt.did()); + // A handle holds its value erased, so no instance names its type. + !mapped || self.owned.contains(&adt.did()) } _ => true, }; @@ -1031,8 +1117,8 @@ impl<'tcx> Collector<'tcx> { Some(shown) } - /// Each type a function's signature names at `args`, normalized, with what a returned - /// future resolves to. A type holding a foreign future names no instance: the future + /// Each type a function's signature names at `args`, normalized, a returned future's + /// being what it resolves to. A type holding a foreign future names no instance: the future /// that holds it, as `Timeout` does, is polled, never a handle. fn spelled(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Vec> { let tcx = self.tcx; @@ -1043,8 +1129,10 @@ impl<'tcx> Collector<'tcx> { }; let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(); let sig = tcx.instantiate_bound_regions_with_erased(sig); - let output = self.future_output(normalize(sig.output()), env); - (sig.inputs_and_output.iter().chain(output)) + // A returned future exports as what it resolves to, never as a handle, so the type + // of the future itself, such as a closure's, names nothing. + let output = self.future_output(normalize(sig.output()), env).unwrap_or(sig.output()); + (sig.inputs().iter().copied().chain([output])) .map(normalize) .flat_map(|ty| ty.walk()) .filter_map(|arg| arg.as_type()) @@ -1498,7 +1586,7 @@ impl<'tcx> Collector<'tcx> { methods: Vec::new(), traits: Traits::default(), foreign: false, - opaque: false, + opaque: None, }); } Decl::Callback(i) => { @@ -1575,6 +1663,17 @@ impl<'tcx> Collector<'tcx> { let krate = tcx.crate_name(def_id.krate); let name = tcx.item_name(def_id); if self.opaque(def_id) { + let owned = self.owned.contains(&def_id); + let docs = match owned { + true => format!( + "`{}`: a handle to another crate's value, which Rust takes back or borrows, with none of its API.", + tcx.def_path_str(def_id) + ), + false => format!( + "`Arc<{}>`: a handle to another crate's value, which Rust takes back, with none of its API.", + tcx.def_path_str(def_id) + ), + }; return Object { path: vec![krate.to_string(), name.to_string()], home: Home { @@ -1585,21 +1684,23 @@ impl<'tcx> Collector<'tcx> { args: Vec::new(), span, on: On::ALL, - docs: format!( - "`Arc<{}>`: a handle to another crate's value, which Rust takes back, with none of its API.", - tcx.def_path_str(def_id) - ), + docs, sync: true, copy: false, - shared: true, + // A held value is moved out of its handle, as an object of the crate's is, and + // its clone is no part of the API. + shared: !owned, lifetimes: 0, methods: Vec::new(), traits: Traits { - clone: true, + clone: !owned, ..Traits::default() }, foreign: true, - opaque: true, + opaque: Some(match owned { + true => Held::Value, + false => Held::Arc, + }), }; } let role = (FOREIGN.iter()) @@ -1634,6 +1735,7 @@ impl<'tcx> Collector<'tcx> { err: Some(Type::String), future: false, eager: false, + holds: false, task: None, collect: false, lends: false, @@ -1682,6 +1784,7 @@ impl<'tcx> Collector<'tcx> { err: None, future: false, eager: false, + holds: false, task: None, collect: false, lends: false, @@ -1717,7 +1820,7 @@ impl<'tcx> Collector<'tcx> { methods, traits, foreign: true, - opaque: false, + opaque: None, } } @@ -1857,12 +1960,16 @@ impl<'tcx> Collector<'tcx> { held[i] = true; } } - self.decls - .iter() + // Another crate's type an opaque handle holds, as each object of the crate's. + let opaque = (self.foreign.iter()) + .filter(|&&(_, i)| api.objects[i].opaque.is_some() && !held[i]) + .map(|&(def_id, _)| Key { def_id, args: None }); + (self.decls.iter()) .filter_map(|(&key, decl)| match decl { Decl::Object(i) if !held[*i] => Some(key), _ => None, }) + .chain(opaque) .collect() } @@ -2174,35 +2281,47 @@ impl<'tcx> Collector<'tcx> { } } + /// The `field@` key of the field `name` of `site`, shown as `shown`, and whether a method + /// or constant shares its name, or `None` if the config excludes it. As in rustdoc, + /// `field@` and the path name the field, and the path alone does unless a method or + /// constant of this instance takes the name, which it then names. + fn field_key( + &mut self, + site: &Site<'tcx>, + name: rustc_span::Symbol, + shown: &[String], + ) -> Option<(Vec, bool)> { + let tcx = self.tcx; + let self_ty = self.site_ty(site); + let shared = (tcx.inherent_impls(site.key.def_id).iter()) + .filter_map(|&imp| Some((imp, self.impl_args(imp, self_ty)?))) + .flat_map(|(imp, parent)| { + (tcx.associated_items(imp).filter_by_name_unhygienic(name)).map(move |item| (item, parent)) + }) + .any(|(item, parent)| { + matches!(item.kind, ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. }) + && tcx.visibility(item.def_id).is_public() + && self.applies(item.def_id, parent) + }); + let mut key = shown.to_vec(); + key[1].insert_str(0, "field@"); + (!self.exclude(&key) && (shared || !self.exclude(shown))).then_some((key, shared)) + } + /// A getter and a setter for each `pub` field of a struct exported as an object: the /// getter returns a copy, and the setter assigns in place, as `x.field = value` does. fn accessors(&mut self, site: &Site<'tcx>) -> Vec { let tcx = self.tcx; let mut accessors = Vec::new(); - let self_ty = self.site_ty(site); for field in &tcx.adt_def(site.key.def_id).non_enum_variant().fields { if !field.vis.is_public() { continue; } let name = field.name.to_string(); let shown = [&site.shown[..], std::slice::from_ref(&name)].concat(); - // As in rustdoc, `field@` and the path name the field, and the path alone does - // unless a method or constant of this instance takes the name, which it then names. - let shared = (tcx.inherent_impls(site.key.def_id).iter()) - .filter_map(|&imp| Some((imp, self.impl_args(imp, self_ty)?))) - .flat_map(|(imp, parent)| { - (tcx.associated_items(imp).filter_by_name_unhygienic(field.name)).map(move |item| (item, parent)) - }) - .any(|(item, parent)| { - matches!(item.kind, ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. }) - && tcx.visibility(item.def_id).is_public() - && self.applies(item.def_id, parent) - }); - let mut key = shown.clone(); - key[1].insert_str(0, "field@"); - if self.exclude(&key) || (!shared && self.exclude(&shown)) { + let Some((key, shared)) = self.field_key(site, field.name, &shown) else { continue; - } + }; let span = tcx.def_span(field.did); let ty = field.ty(tcx, site.args).skip_norm_wip(); // An instance's field of `()`, such as a default extension, holds nothing to read. @@ -2212,8 +2331,14 @@ impl<'tcx> Collector<'tcx> { // Read through `&self`, so returned as a copy, as a borrowed return is, and // written with a value C gives up, as an owned parameter is. let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); + // A field that is an object but not `Clone` is lent from the receiver's handle, + // as a method's borrowed return of one is. + let lends = !self.is_clone(ty) + && matches!(ty.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); let mapped = { + self.lending.set(lends); let get = self.ty(read, Pos::Return); + self.lending.set(false); // A handle outlives every call, so a reference it holds is `'static`, which // C's borrow for the call is not. let set = match self.ty(ty, Pos::Param) { @@ -2252,6 +2377,7 @@ impl<'tcx> Collector<'tcx> { err: None, future: false, eager: false, + holds: false, task: None, collect: false, lends: false, @@ -2259,7 +2385,11 @@ impl<'tcx> Collector<'tcx> { instance: None, home: Home::default(), }; - accessors.push(accessor(Receiver::Ref, Vec::new(), get, false)); + let lent = lends + && matches!(&get, Type::Ref(Mutability::Not, inner) if matches!(**inner, Type::Object(_))); + let mut getter = accessor(Receiver::Ref, Vec::new(), get, false); + getter.lends = lent; + accessors.push(getter); let value = Param { name: "value".to_string(), ty: set, @@ -2821,9 +2951,13 @@ impl<'tcx> Collector<'tcx> { if !self.is_send(output, kept) { errs.push(why("future not Send", "")); } - // Called at once, the future must outlive the arguments the call borrowed. - if eager && borrows { - errs.push(why("borrowing future from a function that is not async", "")); + // An eager future holds what it borrows only until it completes, so its output + // may borrow none of it. + if eager && borrows && self.output_borrows(unbound.output(), inner, &statics) { + errs.push(why( + "borrowing output of a future from a function that is not async", + inner.to_string(), + )); } output = normalize(inner); future = true; @@ -2864,15 +2998,17 @@ impl<'tcx> Collector<'tcx> { 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, even where a - // signature reaches its crate. + // signature reaches its crate. One a handle holds by value is its message too, + // held or not. self.erring.set(true); let err = self.ty(error, Pos::Return); self.erring.set(false); + let foreign = |mapped: &Result| { + self.opaque_value(error).is_some() + || matches!(mapped, Err(why) if why.construct == "foreign type" || why.construct == BOTH) + }; let err = match err { - Err(why) - if why.construct == "foreign type" - && implements(tcx, error, def_id, rustc_span::sym::Display) => - { + err if foreign(&err) && implements(tcx, error, def_id, rustc_span::sym::Display) => { Ok(Type::String) } err => err, @@ -2905,8 +3041,8 @@ impl<'tcx> Collector<'tcx> { continue; }; if ty == unrevealed && (future || collect) { - let bounds = tcx.explicit_item_bounds(*def_id).skip_binder(); - named.extend(bounds.iter().filter_map(|&(clause, _)| { + let bounds = tcx.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()) })); @@ -2945,6 +3081,7 @@ impl<'tcx> Collector<'tcx> { err, future, eager: future && eager, + holds: future && eager && borrows, task, collect, lends, @@ -3223,8 +3360,12 @@ impl<'tcx> Collector<'tcx> { } candidates.extend(self.vec_of(tcx.types.u8).map(|ty| (ty, None))); // `impl Into>` takes a `String` too, which maps where `Arc` does not. + // Not another crate's type a handle holds: the glue never names it, so nothing would + // fix the call's type argument. candidates.retain(|&(candidate, _)| { - self.at(def_id, param, base, candidate).is_some() && self.maps(candidate, Pos::Param) + self.at(def_id, param, base, candidate).is_some() + && self.maps(candidate, Pos::Param) + && !(candidate.walk().filter_map(|arg| arg.as_type())).any(|ty| self.is_opaque(ty)) }); // Two sources that C passes as one buffer but that hold different values, as a // `String` and a `Vec` do, leave the caller no say in which conversion runs. Forms @@ -3651,10 +3792,14 @@ impl<'tcx> Collector<'tcx> { let sig = tcx.fn_sig(def_id).instantiate(tcx, tcx.mk_args(base)).skip_norm_wip(); // An `async fn`'s future, or a returned `impl Trait`, captures it. kept |= sig.skip_binder().output().walk().any(|arg| arg == param.into()); - // A `Copy` object, which C lends as its handle and hands back as a new one. + // A `Copy` object, which C lends as its handle and hands back as a new one; not one + // an opaque handle holds, which the closure would take as the handle's `rt::Owned`. let env = TypingEnv::post_analysis(tcx, def_id); - let copied = - |ty: Ty<'tcx>, mapped: &Type| matches!(mapped, Type::Object(_)) && tcx.type_is_copy_modulo_regions(env, ty); + let copied = |ty: Ty<'tcx>, mapped: &Type| { + matches!(mapped, Type::Object(_)) + && self.opaque_value(ty).is_none() + && tcx.type_is_copy_modulo_regions(env, ty) + }; // Each parameter makes its own closure, which one type parameter cannot name twice. if sig .skip_binder() @@ -3682,12 +3827,12 @@ impl<'tcx> Collector<'tcx> { } match self.ty(input, Pos::Param) { // An object is lent as a handle for the call, but an opaque one, whose - // handle holds no `Arc` to lend; so is a `Copy` one taken by value, which C + // handle holds its value erased, has none to lend; so is a `Copy` one taken by value, which C // copies to keep. Ok(ty) if foreign_arg(&ty) || matches!(&ty, Type::Ref(_, inner) if matches!(**inner, Type::Object(_))) - && !matches!(input.kind(), ty::Ref(_, inner, _) if self.opaque_arc(*inner).is_some()) + && !matches!(input.kind(), ty::Ref(_, inner, _) if self.is_opaque(*inner)) || copied(input, &ty) => { params.push(ty) @@ -4143,9 +4288,25 @@ impl<'tcx> Collector<'tcx> { errs.push(why); } } - // A returned object's lifetimes are `'static` too, which no lent borrow may be. + // A returned object's lifetimes are `'static` too, which no lent borrow may be; not a + // `Result`'s error of another crate, which crosses as its message. + let output = match sig.output().kind() { + ty::Adt(adt, args) + if tcx.is_diagnostic_item(sym::Result, adt.did()) + && self.opaque_value(args.type_at(1)).is_some() + && implements( + tcx, + ty::fold_regions(tcx, args.type_at(1), |_, _| tcx.lifetimes.re_erased), + def_id, + rustc_span::sym::Display, + ) => + { + args.type_at(0) + } + _ => sig.output(), + }; let returned = statics.len(); - for region in self.lifetimes(sig.output()).0 { + for region in self.lifetimes(output).0 { if !statics.contains(®ion) { statics.push(region); } @@ -4170,6 +4331,32 @@ impl<'tcx> Collector<'tcx> { } } + /// Whether the output of the future `future` may name a lifetime outside `statics`, + /// whatever type holds it: an `impl Future`'s by what its bounds name; another future's, + /// whose lifetimes `output` has erased, by naming any at all. + fn output_borrows(&self, future: Ty<'tcx>, output: Ty<'tcx>, statics: &[ty::Region<'tcx>]) -> bool { + let tcx = self.tcx; + let ty::Alias( + _, + ty::AliasTy { + kind: ty::AliasTyKind::Opaque { def_id }, + args, + .. + }, + ) = future.kind() + else { + return output.walk().any(|arg| arg.as_region().is_some()); + }; + // Elaborated, as a supertrait may name the output. + (tcx.item_bounds(*def_id).skip_binder().iter()) + .filter_map(|clause| clause.as_projection_clause()?.skip_binder().term.as_type()) + .map(|term| ty::EarlyBinder::bind(tcx, term).instantiate(tcx, args).skip_norm_wip()) + .any(|term| { + term.walk() + .any(|arg| arg.as_region().is_some_and(|r| !statics.contains(&r))) + }) + } + /// The lifetimes in `ty`: those its objects take, then those it borrows with. fn lifetimes(&self, ty: Ty<'tcx>) -> (Vec>, Vec>) { let mut held = Vec::new(); @@ -4177,7 +4364,10 @@ impl<'tcx> Collector<'tcx> { for ty in ty.walk().filter_map(|arg| arg.as_type()) { match ty.kind() { ty::Ref(region, ..) => lent.push(*region), - ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_))) => { + ty::Adt(adt, args) + if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_))) + || self.opaque_value(ty).is_some() => + { held.extend(args.regions()) } // An `impl Future` holds what its bounds name, as an `async fn` its output. @@ -4190,11 +4380,12 @@ impl<'tcx> Collector<'tcx> { }, ) => { let tcx = self.tcx; - let bounds = tcx.explicit_item_bounds(*def_id).skip_binder(); + // Elaborated, as a supertrait may be the future or name its output. + let bounds = tcx.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, _)| { + let future = (bounds.iter()).any(|clause| { clause .as_trait_clause() .is_some_and(|tr| tcx.is_lang_item(tr.def_id(), LangItem::Future)) @@ -4225,7 +4416,7 @@ impl<'tcx> Collector<'tcx> { held.extend(args.iter().flat_map(|arg| arg.walk()).filter_map(|arg| arg.as_region())); } } - for &(clause, _) in bounds { + for clause in bounds { let term = clause .as_projection_clause() .and_then(|p| p.skip_binder().term.as_type()); @@ -4282,14 +4473,17 @@ impl<'tcx> Collector<'tcx> { } } - /// Whether `ty` holds an object that is not `Copy`, which a copy would duplicate. + /// Whether `ty` holds a handle a copy would duplicate: an object that is not `Copy`, or any opaque one. fn holds_handle(&self, ty: Ty<'tcx>) -> bool { let tcx = self.tcx; ty.walk().filter_map(|arg| arg.as_type()).any(|ty| match ty.kind() { ty::Adt(adt, args) => { - let object = matches!(self.decl(adt.did(), *args), Some(Decl::Object(_))) - || self.foreign.iter().any(|&(ty, _)| ty == adt.did()); - object && !implements(tcx, ty, adt.did(), sym::Copy) + // An opaque handle is never copied, even of a `Copy` value: lifting takes it. A + // type [`FOREIGN`] maps by its role is an object. + let foreign = self.foreign.iter().any(|&(ty, _)| ty == adt.did()); + let opaque = foreign && self.opaque(adt.did()); + let object = foreign || matches!(self.decl(adt.did(), *args), Some(Decl::Object(_))); + opaque || object && !implements(tcx, ty, adt.did(), sym::Copy) } _ => false, }) @@ -4391,8 +4585,9 @@ impl<'tcx> Collector<'tcx> { ty::Mutability::Mut => Mutability::Mut, })); } - // A generic type's constructor may belong to another of its instances. - if !polled || m == ty::Mutability::Mut || !args.is_empty() { + // A generic type's constructor may belong to another of its instances, and the glue + // cannot name an opaque handle's type to call its constructor. + if !polled || m == ty::Mutability::Mut || !args.is_empty() || self.opaque_value(inner).is_some() { return None; } let Ok(Type::Object(object)) = self.ty(inner, Pos::Behind) else { @@ -4487,6 +4682,7 @@ impl<'tcx> Collector<'tcx> { err: None, future: false, eager: false, + holds: false, task: None, collect: false, lends: false, @@ -4597,8 +4793,10 @@ impl<'tcx> Collector<'tcx> { } // Returned as a clone: a handle in it is a new handle to its clone. (Type::Str | Type::Slice | Type::Path, Pos::Return | Pos::Returned, _) => {} - // Lent from the receiver's handle, as [`Self::function`] decides. - (Type::Object(_), Pos::Return, Mutability::Not) if self.lending.take() => {} + // Lent from the receiver's handle, as [`Self::function`] decides, but for + // another crate's value, which a handle holds only erased and by value. + (Type::Object(_), Pos::Return, Mutability::Not) + if self.lending.take() && self.opaque_value(*inner).is_none() => {} // A slice's clone is a `Vec` of its elements' clones. (_, Pos::Return | Pos::Returned, _) if !self.is_clone(match inner.kind() { @@ -4777,6 +4975,14 @@ impl<'tcx> Collector<'tcx> { _ => match (self.opaque_arc(ty)) .and_then(|inner| self.foreign.iter().find(|&&(other, _)| other == inner)) { + Some(&(did, _)) + if self.orphans.contains(&Key { + def_id: did, + args: None, + }) => + { + return Err(why("type C never holds", inner.to_string())); + } Some(_) if pos == Pos::Field => { return Err(why("object in a value", inner.to_string())); } @@ -4784,15 +4990,29 @@ impl<'tcx> Collector<'tcx> { None => return Err(why("Arc", strip_args(tcx, did))), }, } + } else if let Some(did) = self.opaque_value(ty) + && let Some(&(_, i)) = self.foreign.iter().find(|&&(other, _)| other == did) + { + // Held by value, as a handle with none of its API, which Rust takes back + // or borrows. + if self.both.contains(&did) { + return Err(why(BOTH, strip_args(tcx, did))); + } + if self.orphans.contains(&Key { + def_id: did, + args: None, + }) { + return Err(why("type C never holds", strip_args(tcx, did))); + } + match pos { + Pos::Field => return Err(why("object in a value", strip_args(tcx, did))), + _ => Type::Object(i), + } } 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")) - { + // it is an error: one in a `Result` crosses as its message, and one elsewhere + // is held by value, as above, or refused. + if !self.erring.get() && !self.reach.contains(&did) && self.reaches(ty, did) { self.reached(did); } return Err(why("foreign type", strip_args(tcx, did))); diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index 6b9c0dbf6..3cc80ca17 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -153,8 +153,8 @@ 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. + 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 7b14bde17..485fede70 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -15,7 +15,8 @@ use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, CFG, Ty}; use crate::config::Package; use crate::ir::{ - Access, Closure, Collection, Family, Function, Literal, Mutability, On, Receiver, Task, TaskKind, Traits, Type, + Access, Closure, Collection, Family, Function, Held, Literal, Mutability, On, Receiver, Task, TaskKind, Traits, + Type, }; const RUNTIME: &str = include_str!("../runtime/rt.rs"); @@ -635,7 +636,10 @@ impl Gen<'_> { Type::Record(i) => generic(&api.records[*i].path, 0, &api.records[*i].args), Type::Enum(i) if api.enums[*i].foreign => foreign_path(&api.enums[*i].path), Type::Enum(i) => generic(&api.enums[*i].path, 0, &api.enums[*i].args), - Type::Object(i) if api.objects[*i].opaque => "rt::Opaque".to_string(), + Type::Object(i) if let Some(held) = api.objects[*i].opaque => match held { + Held::Arc => "rt::Opaque".to_string(), + Held::Value => "rt::Owned".to_string(), + }, Type::Object(i) if api.objects[*i].foreign => foreign_path(&api.objects[*i].path), Type::Object(i) => generic(&api.objects[*i].path, api.objects[*i].lifetimes, &api.objects[*i].args), // A negative argument is an expression, which Rust takes only in braces. @@ -717,9 +721,10 @@ impl Gen<'_> { true => format!("lift_{}({e}, w)", self.abi.enumeration(*i)), false => format!("lift_{}(&{e}, w, {take})", self.abi.enumeration(*i)), }, - Type::Object(i) if self.abi.api.objects[*i].opaque => { - format!("unsafe {{ rt::Object::::take({e}, w) }}.arc(w)") - } + Type::Object(i) if let Some(held) = self.abi.api.objects[*i].opaque => match held { + Held::Arc => format!("unsafe {{ rt::Object::::take({e}, w) }}.arc(w)"), + Held::Value => format!("unsafe {{ rt::Object::::take({e}, w) }}.take(w)"), + }, Type::Object(i) => match self.abi.api.objects[*i].copy { true => format!( "*unsafe {{ rt::Object::<{}>::{}({e}, w) }}", @@ -907,7 +912,10 @@ impl Gen<'_> { }, Type::Record(i) => format!("lower_{}({e})", self.abi.record(*i)), Type::Enum(i) => format!("lower_{}({e})", self.abi.enumeration(*i)), - Type::Object(i) if self.abi.api.objects[*i].opaque => format!("rt::Object::new(rt::Opaque::new({e}))"), + Type::Object(i) if let Some(held) = self.abi.api.objects[*i].opaque => match held { + Held::Arc => format!("rt::Object::new(rt::Opaque::new({e}))"), + Held::Value => format!("rt::Object::new(rt::Owned::new({e}))"), + }, Type::Object(_) => format!("rt::Object::new({e})"), Type::Callback(..) | Type::Closure(..) => unreachable!("a callback is never returned"), Type::Waker => format!("rt::Waker::lower({e})"), @@ -1521,9 +1529,10 @@ impl Gen<'_> { (Type::Object(i), _, _) => { let (binding, borrow) = self.borrow(*i, *m, c, future); let pass = match (m, self.abi.api.objects[*i].opaque) { - (Mutability::Not, true) => format!("{local}.get(w)"), - (Mutability::Mut, _) => format!("&mut *{local}"), - (Mutability::Not, false) => format!("&*{local}"), + (Mutability::Not, Some(_)) => format!("{local}.get(w)"), + (Mutability::Mut, Some(_)) => format!("{local}.get_mut(w)"), + (Mutability::Mut, None) => format!("&mut *{local}"), + (Mutability::Not, None) => format!("&*{local}"), }; (format!("{binding} {local} = {borrow};"), pass) } @@ -1557,9 +1566,10 @@ impl Gen<'_> { (Type::Object(i), _) => { let (binding, borrow) = self.borrow(*i, *m, c, future); let pass = match (m, self.abi.api.objects[*i].opaque) { - (Mutability::Not, true) => format!("{local}.as_deref().map(|v| v.get(w))"), - (Mutability::Mut, _) => format!("{local}.as_deref_mut()"), - (Mutability::Not, false) => format!("{local}.as_deref()"), + (Mutability::Not, Some(_)) => format!("{local}.as_deref().map(|v| v.get(w))"), + (Mutability::Mut, Some(_)) => format!("{local}.as_deref_mut().map(|v| v.get_mut(w))"), + (Mutability::Mut, None) => format!("{local}.as_deref_mut()"), + (Mutability::Not, None) => format!("{local}.as_deref()"), }; ( format!("{binding} {local} = if {c}.is_null() {{ None }} else {{ Some({borrow}) }};"), @@ -1695,8 +1705,11 @@ impl Gen<'_> { fn function_on(&mut self, function: &Function, owner: Option<(&Ty, Type)>) { let export = self.abi.export(function, owner.as_ref().map(|(ty, _)| *ty)); let name = export.call.name.clone(); - // An eager call borrows its arguments only for the call, as a synchronous one does. - let future = function.future && !function.eager; + // An eager call borrows its arguments only for the call, as a synchronous one does, + // unless the future it returns borrows them: it then owns them, as an `async fn`'s + // future does, and holds each it lends in place until the future is dropped. + let future = function.future && (!function.eager || function.holds); + let mut held = Vec::new(); let mut stmts = Vec::new(); let mut args = Vec::new(); let mut params = Vec::new(); @@ -1715,8 +1728,14 @@ impl Gen<'_> { let (stmt, arg) = self.arg(&ty, "this", "a_self", future); stmts.push(stmt); args.push(arg); + if function.holds && *receiver != Receiver::Owned { + held.push("a_self".to_string()); + } } value => { + if function.holds && *receiver != Receiver::Owned { + held.push("a_self".to_string()); + } // Read through a pointer, so the caller keeps it. stmts.push(format!( "let a_self = {};", @@ -1775,11 +1794,32 @@ impl Gen<'_> { format!("let mut a{n} = p{n}.lift(w);"), format!("::std::pin::Pin::new(&mut a{n})"), ), - _ => self.arg(¶m.ty, &format!("p{n}"), &format!("a{n}"), future), + _ => { + let lent = match ¶m.ty { + Type::Option(inner) => matches!(**inner, Type::Ref(..)), + ty => matches!(ty, Type::Ref(..)), + }; + if function.holds && lent { + held.push(format!("a{n}")); + } + self.arg(¶m.ty, &format!("p{n}"), &format!("a{n}"), future) + } }; stmts.push(stmt); args.push(arg); } + // Each owned argument the call lends moves to the heap, where it stays while the + // future borrows it, and the call reborrows it through the reference it is now. + for local in &held { + stmts.push(format!( + "let {local}_held = rt::Pinned::new({local});\n\tlet {local} = unsafe {{ {local}_held.get() }};" + )); + } + for arg in &mut args { + for local in &held { + *arg = deref_local(arg, local); + } + } // A future made of a `Poll` calls the function at each poll, passing the poll's // context, or a value made from its waker and kept until the next poll, so what that // poll registers stays registered. @@ -1861,6 +1901,13 @@ impl Gen<'_> { // A function that is not `async` runs when called, and what it returns // borrows nothing, so it is called now; an `async fn` runs when polled. let (now, later) = match (function.eager, &function.task) { + (true, _) if function.holds => { + let held: String = held.iter().map(|local| format!("{local}_held, ")).collect(); + ( + format!("\n\tlet future = rt::Holding::new({call}, ({held}));"), + "future".to_string(), + ) + } (true, _) => (format!("\n\tlet future = {call};"), "future".to_string()), (false, None) => (String::new(), call), (false, Some(task)) => { @@ -2038,6 +2085,26 @@ fn go_module_resolves_missing_parent() { } } +/// `expr` with each use of the local `name`, a reference, read through it as `(*name)`, so +/// what it lends borrows the referent rather than the local. +fn deref_local(expr: &str, name: &str) -> String { + let ident = |c: char| c.is_alphanumeric() || c == '_'; + let mut out = String::new(); + let mut rest = expr; + while let Some(at) = rest.find(name) { + let (before, after) = (&rest[..at], &rest[at + name.len()..]); + let whole = !before.ends_with(ident) && !after.starts_with(ident); + out.push_str(before); + match whole { + true => out.push_str(&format!("(*{name})")), + false => out.push_str(name), + } + rest = after; + } + out.push_str(rest); + out +} + /// A second write of the same export keeps every file's mtime, and drops only the files in /// the directories it owns that it no longer writes, with any directory that leaves empty. #[test] diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 27a100195..caa894a74 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -244,9 +244,35 @@ pub struct Object { /// Whether it is a foreign type, such as `url::Url`, that the facade maps rather than /// exports: its path is the type's in its own crate, not in the facade. pub foreign: bool, - /// Whether it is a foreign type behind an `Arc`, held erased, which the glue never - /// names: a handle with none of its API, which Rust takes back as the `Arc`. - pub opaque: bool, + /// What its handle holds of another crate's type, held erased, which the glue never + /// names: a handle with none of its API. A baseline written before the by-value form + /// has a `bool`, the `Arc` form's. + #[serde(deserialize_with = "held")] + pub opaque: Option, +} + +/// An [`Object::opaque`], read from a baseline written before the by-value form as the +/// `bool` the `Arc` form was. +fn held<'de, D: serde::Deserializer<'de>>(de: D) -> Result, D::Error> { + #[derive(serde::Deserialize)] + #[serde(untagged)] + enum Either { + Arc(bool), + Held(Option), + } + Ok(match serde::Deserialize::deserialize(de)? { + Either::Arc(arc) => arc.then_some(Held::Arc), + Either::Held(held) => held, + }) +} + +/// What an opaque handle holds of another crate's type. +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] +pub enum Held { + /// An `Arc` of it, which Rust takes back as the `Arc`, and clones share. + Arc, + /// The value itself, which Rust takes back by value or borrows. + Value, } /// A `pub` trait: implemented by the foreign side, through a table of functions. @@ -300,6 +326,11 @@ pub struct Function { /// For a future, whether the call itself runs code, as a function that is not /// `async` returning one does: the export calls it at once, and polls what it returns. pub eager: bool, + /// For an eager future, whether what it returns borrows its arguments: the export owns + /// them, as it does an `async fn`'s, and keeps them until the future is dropped. A + /// baseline written before it has none. + #[serde(default)] + pub holds: bool, /// The parameter it polls its task through, if any: C passes a waker for it or, for a /// future made of a returned `Poll`, the future's poll supplies it. pub task: Option, @@ -660,3 +691,23 @@ impl Type { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(serde::Deserialize)] + struct Opaque { + #[serde(deserialize_with = "held")] + opaque: Option, + } + + #[test] + fn held_reads_an_earlier_baseline() { + let read = |json: &str| serde_json::from_str::(json).unwrap().opaque; + assert_eq!(read(r#"{"opaque":true}"#), Some(Held::Arc)); + assert_eq!(read(r#"{"opaque":false}"#), None); + assert_eq!(read(r#"{"opaque":"Value"}"#), Some(Held::Value)); + assert_eq!(read(r#"{"opaque":null}"#), None); + } +} diff --git a/ffi/src/lock.rs b/ffi/src/lock.rs index e234276fa..7f4a6962a 100644 --- a/ffi/src/lock.rs +++ b/ffi/src/lock.rs @@ -805,6 +805,7 @@ mod tests { err: None, future: false, eager: false, + holds: false, task: None, collect: false, lends: false, @@ -862,7 +863,7 @@ mod tests { methods: vec![], traits: Traits::default(), foreign: false, - opaque: false, + opaque: None, }); base.functions[0].ok = Type::Option(Box::new(Type::Tuple(vec![Type::Object(0), Type::Int(Int::U64)]))); let old = crate::swift::generate(&Abi::new(&base, "lock"), "lock", 0).unwrap(); diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 60fdda00a..8ddfad885 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1105,6 +1105,28 @@ static int script(void) { print("recv ", payload, "\n"); } api_Channel_recv_future_free(recv); + /* The send happens at the call, and the future borrows the channel and the tag. */ + api_Channel_tagged_future *tagging = api_Channel_tagged(channel, str("tag")); + api_buf tagged_text; + if (api_Channel_tagged_poll(tagging, waker, &tagged_text) == API_POLL_READY) { + print("tagged ", tagged_text, "\n"); + } + api_Channel_tagged_future_free(tagging); + /* So does a future borrowing an optional slice, which the export owns while it is pending. */ + const uint32_t items[] = {1, 2, 3}; + api_Channel_itemized_future *itemizing = api_Channel_itemized(channel, (api_vec_u32){.ptr = items, .len = 3}); + size_t itemized; + if (api_Channel_itemized_poll(itemizing, waker, &itemized) == API_POLL_READY) { + printf("itemized %zu\n", itemized); + } + api_Channel_itemized_future_free(itemizing); + /* Another crate's future borrowing its bytes, which the export owns while it is pending. */ + api_byte_len_future *measuring = api_byte_len(str("abc")); + size_t byte_len; + if (api_byte_len_poll(measuring, waker, &byte_len) == API_POLL_READY) { + printf("byte_len %zu\n", byte_len); + } + api_byte_len_future_free(measuring); api_Channel_send(channel, str("sized")); api_Channel_recv_sized_future *sized = api_Channel_recv_sized(channel); size_t len; @@ -1445,6 +1467,15 @@ static int script(void) { print("", api_alpn(config_copy), "\n"); api_tls_Config_free(config_copy); api_tls_Config_free(config); + /* Another crate's value by value: an opaque handle, lent or taken back. */ + api_tls_Cert *cert = api_certify(str("der")); + printf("cert %llu ", (unsigned long long)api_cert_len(cert)); + print("", api_cert_der(cert), " "); + api_tls_Cert_free(cert); + api_tls_Cert *chain[2] = {api_certify(str("a")), api_certify(str("bc"))}; + printf("%llu\n", (unsigned long long)api_chain_len((api_vec_tls_Cert){.ptr = chain, .len = 2})); + api_tls_Cert_free(chain[0]); + api_tls_Cert_free(chain[1]); /* Another crate's type only signatures name, exported by its path there, and its error, * which crosses as its message. */ api_tls_Session *session; @@ -1473,6 +1504,11 @@ static int script(void) { again = api_Meters_first(lender); printf("cleared %llu\n", (unsigned long long)api_Meter_count(again)); api_Meter_free(again); + /* A field that is not Clone, lent as a method's borrowed return is. */ + api_Meter *last = api_Meters_last_get(lender); + api_Meter_add(last, 4); + printf("field lent %llu\n", (unsigned long long)api_Meter_add(last, 1)); + api_Meter_free(last); api_Meters_free(lender); /* One lent from a handle that is not Sync, on one thread at a time. */ api_Tallies *tallies = api_Tallies_new(); @@ -1775,6 +1811,8 @@ static int script(void) { printf("instants %llu %llu %s %s\n", (unsigned long long)(forward.secs * 1000 + forward.nanos / 1000000), (unsigned long long)(backward.secs * 1000 + backward.nanos / 1000000), api_Instant_eq(began, same) ? "true" : "false", api_Instant_eq(began, ended) ? "true" : "false"); + /* An instant lent inside an `Option`, which takes no handle. */ + printf("has_instant %s %s\n", api_has_instant(began) ? "true" : "false", api_has_instant(NULL) ? "true" : "false"); api_Instant_free(same); api_Instant_free(ended); api_Instant_free(began); @@ -1804,7 +1842,7 @@ static int script(void) { api_Token_free(twice); /* Each future dropped its waker once it finished, and Rust the one it was given. */ - if (drops != 12) { + if (drops != 15) { return 1; } return closures() && foreign_futures() && forwarding() && started_futures() ? 0 : 1; diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 5b8541ccd..d3536345c 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -644,6 +644,27 @@ int script() { print("recv ", *payload, "\n"); } } + // The send happens at the call, and the future borrows the channel and the tag. + { + api::Channel_tagged_future tagged = channel.tagged("tag"); + if (auto text = tagged.poll(waker)) { + print("tagged ", *text, "\n"); + } + } + // So does a future borrowing an optional slice, which the export owns while it is pending. + { + api::Channel_itemized_future itemized = channel.itemized(std::vector{1, 2, 3}); + if (auto count = itemized.poll(waker)) { + std::printf("itemized %zu\n", *count); + } + } + // Another crate's future borrowing its bytes, which the export owns while it is pending. + { + api::byte_len_future measuring = api::byte_len("abc"); + if (auto len = measuring.poll(waker)) { + std::printf("byte_len %zu\n", *len); + } + } channel.send("sized"); { api::Channel_recv_sized_future sized = channel.recv_sized(); @@ -895,6 +916,13 @@ int script() { auto config = api::secure("h3"); print("secure ", api::alpn_lent(config), " "); print("", api::alpn(config), "\n"); + auto cert = api::certify("der"); + std::printf("cert %llu ", ull(api::cert_len(cert))); + print("", api::cert_der(std::move(cert)), " "); + std::vector chain; + chain.push_back(api::certify("a")); + chain.push_back(api::certify("bc")); + std::printf("%llu\n", ull(api::chain_len(std::move(chain)))); auto session = api::resume("h3", 60); print("resume ", session.value().alpn(), " "); std::printf("%u\n", unsigned(session.value().lifetime().seconds)); @@ -906,6 +934,9 @@ int script() { std::printf("lent %llu %llu\n", added, ull(meters.first().count())); meters.clear(); std::printf("cleared %llu\n", ull(meters.first().count())); + auto last = meters.last_get(); + last.add(4); + std::printf("field lent %llu\n", ull(last.add(1))); auto tallies = api::Tallies::new_(); tallies.first().bump(); std::printf("tallied %u\n", tallies.first().bump()); @@ -1138,6 +1169,8 @@ int script() { auto ended = api::later(began, {1, 500000000}); std::printf("instants %llu %llu %s %s\n", millis(api::since(ended, began)), millis(api::since(began, ended)), began == api::later(began, {0, 0}) ? "true" : "false", began == ended ? "true" : "false"); + // An instant lent inside an `Option`, which takes no handle. + std::printf("has_instant %s %s\n", api::has_instant(&began) ? "true" : "false", api::has_instant(nullptr) ? "true" : "false"); } // tracing's level, and its filter as an optional level whose empty is `OFF`. { diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 5025c9287..f491961b9 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -390,6 +390,10 @@ Future script() async { // The send happens at the call: the future is dropped unawaited. channel.sendLater(utf8.encode('eager')); print('recv ${text(await channel.recv())}'); + // The send happens at the call, and the future borrows the channel and the tag. + print('tagged ${await channel.tagged('tag')}'); + print('itemized ${await channel.itemized(Uint32List.fromList([1, 2, 3]))}'); + print('byte_len ${await api.byteLen(utf8.encode('abc'))}'); channel.send(utf8.encode('sized')); final (payload, size) = await channel.recvSized(); print('sized ${text(payload)} $size'); @@ -564,6 +568,9 @@ Future script() async { print('nudge ${nudged.value.x} ${nudged.value.y}'); final config = api.secure('h3'); print('secure ${api.alpnLent(config)} ${api.alpn(config.clone())}'); + final cert = api.certify(utf8.encode('der')); + final certLen = api.certLen(cert); + print('cert $certLen ${text(api.certDer(cert))} ${api.chainLen([api.certify(utf8.encode('a')), api.certify(utf8.encode('bc'))])}'); config.close(); final session = api.resume('h3', 60); print('resume ${session.alpn()} ${session.lifetime().seconds}'); @@ -580,6 +587,10 @@ Future script() async { lentMeter.close(); meters.clear(); print('cleared ${meters.first().count()}'); + final lastMeter = meters.lastGet; + lastMeter.add(4); + print('field lent ${lastMeter.add(1)}'); + lastMeter.close(); meters.close(); final tallies = api.Tallies(); tallies.first().bump(); @@ -680,6 +691,7 @@ Future script() async { final ended = api.later(began, const Duration(milliseconds: 1500)); final same = api.later(began, Duration.zero); print('instants ${api.since(ended, began).inMilliseconds} ${api.since(began, ended).inMilliseconds} ${began == same} ${began == ended}'); + print('has_instant ${api.hasInstant(began)} ${api.hasInstant(null)}'); began.close(); ended.close(); same.close(); diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 37387e2e9..c20fdce5b 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -28,6 +28,7 @@ import ( "api/rt" "api/serdejson" "api/std" + "api/tls" "api/tracingcore" "api/url" ) @@ -477,6 +478,10 @@ func script() { cancel() check(errors.Is(channel.SendLater(cancelled, rt.NewBytes([]byte("eager"))), context.Canceled), "a cancelled call returns its context's error") fmt.Printf("recv %s\n", must(channel.Recv(ctx)).Copy()) + // The send happens at the call, and the future borrows the channel and the tag. + fmt.Printf("tagged %s\n", must(channel.Tagged(ctx, "tag"))) + fmt.Printf("itemized %d\n", must(channel.Itemized(ctx, &[]uint32{1, 2, 3}))) + fmt.Printf("byte_len %d\n", must(api.ByteLen(ctx, rt.NewBytes([]byte("abc"))))) // An eager call whose callback cancels its context while it makes its future is never // polled: only the eager half logs. { @@ -666,6 +671,9 @@ 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())))) + cert := api.Certify(rt.NewBytes([]byte("der"))) + certLen := must(api.CertLen(cert)) + fmt.Printf("cert %d %s %d\n", certLen, must(api.CertDer(cert)).Copy(), must(api.ChainLen([]*tls.Cert{api.Certify(rt.NewBytes([]byte("a"))), api.Certify(rt.NewBytes([]byte("bc")))}))) session := must(api.Resume("h3", 60)) fmt.Printf("resume %s %d\n", must(session.Alpn()), must(session.Lifetime()).Seconds) session.Close() @@ -678,6 +686,9 @@ func script() { fmt.Printf("lent %d %d\n", must(meter.Add(3)), must(must(meters.First()).Count())) ok(meters.Clear()) fmt.Printf("cleared %d\n", must(must(meters.First()).Count())) + lastMeter := must(meters.LastGet()) + _ = must(lastMeter.Add(4)) + fmt.Printf("field lent %d\n", must(lastMeter.Add(1))) tallies := api.NewTallies() _ = must(must(tallies.First()).Bump()) fmt.Printf("tallied %d\n", must(must(tallies.First()).Bump())) @@ -805,6 +816,7 @@ func script() { same := must(api.Later(began, 0)) fmt.Printf("instants %d %d %t %t\n", must(api.Since(ended, began)).Milliseconds(), must(api.Since(began, ended)).Milliseconds(), must(began.Equal(same)), must(began.Equal(ended))) + fmt.Printf("has_instant %t %t\n", must(api.HasInstant(began)), must(api.HasInstant(nil))) began.Close() ended.Close() same.Close() diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 094f5db59..5f5a2390e 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -314,6 +314,10 @@ fun script() { // The send happens at the call: the future is dropped unawaited. channel.sendLater(Bytes("eager".encodeToByteArray())) println("recv ${channel.recv().text()}") + // The send happens at the call, and the future borrows the channel and the tag. + println("tagged ${channel.tagged("tag")}") + println("itemized ${channel.itemized(uintArrayOf(1u, 2u, 3u))}") + println("byte_len ${byteLen(Bytes("abc".encodeToByteArray()))}") channel.send(Bytes("sized".encodeToByteArray())) val (payload, size) = channel.recvSized() println("sized ${payload.text()} $size") @@ -484,6 +488,9 @@ fun script() { nudge(nudged, 3) println("nudge ${nudged.value.x} ${nudged.value.y}") secure("h3").use { config -> println("secure ${alpnLent(config)} ${alpn(config.clone())}") } + val cert = certify(Bytes("der".encodeToByteArray())) + val certLen = certLen(cert) + println("cert $certLen ${certDer(cert).text()} ${chainLen(listOf(certify(Bytes("a".encodeToByteArray())), certify(Bytes("bc".encodeToByteArray()))))}") resume("h3", 60u).use { session -> println("resume ${session.alpn()} ${session.lifetime().seconds}") } try { resume("", 60u) @@ -497,6 +504,10 @@ fun script() { } meters.clear() println("cleared ${meters.first().use { it.count() }}") + meters.lastGet.use { last -> + last.add(4uL) + println("field lent ${last.add(1uL)}") + } } Tallies.new().use { tallies -> tallies.first().use { it.bump() } @@ -594,6 +605,7 @@ fun script() { later(began, 1500.milliseconds).use { ended -> later(began, kotlin.time.Duration.ZERO).use { same -> println("instants ${since(ended, began).inWholeMilliseconds} ${since(began, ended).inWholeMilliseconds} ${began == same} ${began == ended}") + println("has_instant ${hasInstant(began)} ${hasInstant(null)}") } } } diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 6a8ab1ff9..fe1b73332 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -391,6 +391,10 @@ async def block(): # The send happens at the call: the future is dropped unawaited. channel.send_later(b"eager") print(f"recv {text(await channel.recv())}") + # The send happens at the call, and the future borrows the channel and the tag. + print(f"tagged {await channel.tagged('tag')}") + print(f"itemized {await channel.itemized(array.array('I', [1, 2, 3]))}") + print(f"byte_len {await api.byte_len(b'abc')}") channel.send(b"sized") payload, size = await channel.recv_sized() print(f"sized {text(payload)} {size}") @@ -571,6 +575,8 @@ 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())}") + cert = api.certify(b"der") + print(f"cert {api.cert_len(cert)} {text(api.cert_der(cert))} {api.chain_len([api.certify(b'a'), api.certify(b'bc')])}") session = api.resume("h3", 60) print(f"resume {session.alpn()} {session.lifetime().seconds}") try: @@ -583,6 +589,9 @@ async def polls(): print(f"lent {first.add(3)} {meters.first().count()}") meters.clear() print(f"cleared {meters.first().count()}") + lent_last = meters.last_get + lent_last.add(4) + print(f"field lent {lent_last.add(1)}") tallies = api.Tallies.new() tallies.first().bump() print(f"tallied {tallies.first().bump()}") @@ -666,6 +675,7 @@ async def polls(): ended = api.later(began, datetime.timedelta(milliseconds=1500)) same = api.later(began, datetime.timedelta()) print(f"instants {api.since(ended, began) // ms} {api.since(began, ended) // ms} {flag(began == same)} {flag(began == ended)}") + print(f"has_instant {flag(api.has_instant(began))} {flag(api.has_instant(None))}") # tracing's level, and its filter as an optional level whose None is `OFF`. verbosity = api.Verbosity.new(api.Level.WARN) print(f"verbosity {api.spell(verbosity.filter())} {api.spell(api.louder(verbosity.filter()))}") diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index b9f477b70..9917d8a67 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -463,6 +463,10 @@ func script() { // The send happens at the call, before the future is first polled. try await channel.sendLater(Bytes("eager".utf8)) print("recv \(text(try await channel.recv()))") + // The send happens at the call, and the future borrows the channel and the tag. + print("tagged \(try await channel.tagged("tag"))") + print("itemized \(try await channel.itemized([1, 2, 3]))") + print("byte_len \(try await byteLen(Bytes("abc".utf8)))") channel.send(Bytes("sized".utf8)) let (payload, size) = try await channel.recvSized() print("sized \(text(payload)) \(size)") @@ -655,6 +659,13 @@ func script() { do { let config = secure("h3") print("secure \(alpnLent(config)) \(alpn(config.clone()))") + let cert = certify(Bytes("der".utf8)) + let certLength = certLen(cert) + let der = text(certDer(cert)) + var chain = UniqueArray() + chain.append(certify(Bytes("a".utf8))) + chain.append(certify(Bytes("bc".utf8))) + print("cert \(certLength) \(der) \(chainLen(chain))") let session = try! resume("h3", 60) print("resume \(session.alpn()) \(session.lifetime().seconds)") do { @@ -670,6 +681,9 @@ func script() { print("lent \(first.add(3)) \(meters.first().count())") meters.clear() print("cleared \(meters.first().count())") + let last = meters.lastGet + _ = last.add(4) + print("field lent \(last.add(1))") let tallies = Tallies.new() _ = tallies.first().bump() print("tallied \(tallies.first().bump())") @@ -754,6 +768,7 @@ func script() { let began = now() let ended = later(began, .milliseconds(1500)) print("instants \(millis(since(ended, began))) \(millis(since(began, ended))) \(began == later(began, .zero)) \(began == ended)") + print("has_instant \(hasInstant(began)) \(hasInstant(nil))") // tracing's level, and its filter as an optional level whose nil is `OFF`. var verbosity = Verbosity.new(.warn) print("verbosity \(spell(verbosity.filter())) \(spell(louder(verbosity.filter())))") diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 61e3c5b18..3e09d14e2 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1709,18 +1709,21 @@ fn unreached_types() { 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. + // never reached, so a handle holds it by value, and `Failure`, which holds it, 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. + assert!( + report.contains("- `Failure`: object in a value `net::Fault`"), + "{report}" + ); + // A type an `Arc` holds, and a `Result`'s error without `Display`, stay refused as + // foreign; one no public path names is held by value instead. 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("`closed`"), "{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`. @@ -1922,7 +1925,9 @@ fn relative_target() { "- `Lease`: object no export returns", "- `Void`: object no export returns", "- `release`: type C never holds `Lease`", + "- `handover`: type C never holds `tls::held::Handoff`", "- `Unnamed`: generic type no export instantiates", + "- `blame`: type C never holds `tls::held::Invalid`", // An exclude that names what exports, by its generic or instance path or as a field, // even where a method of the field's name is refused. "## Excluded by the config, though it exports", @@ -1952,6 +1957,10 @@ fn relative_target() { "the census lists `{refused}` as exporting:\n{exporting}" ); } + // Its error a handle C never holds, `verify` still exports, the error as its message. + assert!(!text.contains("`verify`"), "the census lists `verify`:\n{text}"); + // Nor does `parse_cert`'s, though it borrows the text. + assert!(!text.contains("`parse_cert`"), "the census lists `parse_cert`:\n{text}"); assert!(dir.join("build").exists()); } diff --git a/quest/m1/ffi-export/future-error-borrow.md b/quest/m1/ffi-export/future-error-borrow.md new file mode 100644 index 000000000..e37a5b6d3 --- /dev/null +++ b/quest/m1/ffi-export/future-error-borrow.md @@ -0,0 +1,22 @@ +# [S] A future whose error borrows its arguments + +## Goal + +`async fn parse(text: &str) -> Result>`, whose error is another +crate's and crosses as its message, either exports or is refused with a span; today, unless +a handle would hold the error, the export accepts it and generates glue that fails to build +(E0597: the glue awaits the future past the call that owns `text`, and the error's borrow +outlives it). Found on 2026-11-13 by +[kixel-ai/rust2#733](https://github.com/kixel-ai/rust2/pull/733)'s review, which refuses the +held case (`parse_later` in the reject fixture); main has the bug for every such error. + +## Plan + +The maintainer kept this quest on 2026-11-13 (rejected: drop) and decided its fix: +✅ the glue converts the borrowed foreign error to its message inside the `async` block, +as foreign errors already cross, while the arguments the future owns are alive, so nothing +borrowed outlives the call and the function exports as its sync form already does +(`parse_cert` in the api fixture); the held case's refusal then goes too. +Rejected: refuse every future whose error names a lifetime, which leaves out what maps. + +Public API: each such function newly exports as a future of its `Ok` type and a message. diff --git a/quest/m1/ffi-refusals/README.md b/quest/m1/ffi-refusals/README.md index 596887a42..abd4153d9 100644 --- a/quest/m1/ffi-refusals/README.md +++ b/quest/m1/ffi-refusals/README.md @@ -76,9 +76,11 @@ Decided with the maintainer on 2026-11-12, in the quest audit: refuses 94 items and 5 types at the pin, behind `ffi/moq/ffi.toml`'s then 100 excludes, and moq's `main` adds the 36 errors [the pin bump](/quest/m1/ffi-refusals/moq-pin.md) measured. So each construct left has a child again: - `NonZero`, which exports, and - [the rest at moq's main](/quest/m1/ffi-refusals/moq-main.md); `just ffi census` - fails on an exclude that names what exports. The + `NonZero`, which exports, the rest of the errors at moq's main + (exported since by rules for another crate's value, a borrowing future of a function + that is not `async`, and an object field that is not `Clone`), and + [what the excludes still hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md); + `just ffi census` fails on an exclude that names what exports. The bump is then only the bump. The types refused for not being `Send` (`clock::Entered`, `clock::Rng`, `catalog::Guard`) clear with [not-send](/quest/m1/ffi-export/not-send.md). - ✅ The closing work is a child, [no config](/quest/m1/ffi-refusals/no-config.md), as diff --git a/quest/m1/ffi-refusals/moq-excluded.md b/quest/m1/ffi-refusals/moq-excluded.md new file mode 100644 index 000000000..1e3a4267b --- /dev/null +++ b/quest/m1/ffi-refusals/moq-excluded.md @@ -0,0 +1,58 @@ +# [M] What the excludes hide at moq's main + +## Goal + +Each construct `just ffi census ` still refuses at moq's `main` behind an +exclude in `ffi/moq/ffi.toml` exports by a rule, or is left out as what C can never hold, +beyond `NonZero`, which exports, and the types +[not-send](/quest/m1/ffi-export/not-send.md) exports. Measured on 2026-11-13 at moq +`98e54e7`, with #721's reach of other crates' types and the rules for another crate's +value, a non-`async` function's borrowing future, and a lent object field in place: 23 +items beyond not-send's, 13 of them in crates #721 newly reaches. + +## Plan + +[The epic](/quest/m1/ffi-refusals/README.md)'s decisions apply: rust2 asks moq for no +source change, and what C can never hold is left out and listed. Measure again first. + +The maintainer kept this quest on 2026-11-13 and accepted each recommendation below as its plan. + +- `std::io::Error` taken by value (`accept::Failure::classify`, `accept::Health::failed`) + and `std::net::IpAddr` (`quic::demux::Datagram::local`). Decided: `IpAddr` crosses + as `SocketAddr` already does, by family; `io::Error` as an opaque handle, as another + crate's value now is, with the standard library no longer exempt. +- Trait objects: `quic::Controller`'s `Arc` + field and `tls::Serve::resolver`'s `Arc`. + Decided: an opaque handle to the `Arc`, as another crate's `Arc` already is. +- Generic parameters: `server::Request::within` (`impl Future`), + `websocket::Listener::with_protocols` (`impl IntoIterator>`), + `tcp::TlsAcceptor::offered` (`impl Iterator`), and `tcp::TlsAcceptor::accept` (an IO + stream). Decided: `AsRef` items as strings and an `Iterator` parameter as the + array of its items, as returns already are; a foreign future as #705's is; the IO + stream left out as what C can never hold, since no export returns one. +- `server::Config::websocket`, a borrowed `Option` of a listener that is not `Clone`. + Decided: lent as `Some` of a handle, as a bare field now is. +- `server::Listener::accept_with`'s future is not `Send`. Left out today as what C can + never hold, since it takes a `qmux::Session` no export returns once the excludes go; + confirm the census lists it so. + +- Reached since #721 exports other crates' types with their API: rustls's + `ClientConfig` fields of `Arc` (5) and `client::Resumption::store`, under the + trait-object decision above. Four more constructs, decided by the maintainer on 2026-11-13: + - A `'static` borrow parameter (`CertificateDer::from_slice`, `Der::from_slice`): + ✅ exported by interning by content (rejected: left out and listed). The binding keeps + one process-wide table keyed by the bytes' contents; the first call with given bytes + copies them into a leaked Rust allocation, and later calls with equal bytes reuse it. + Never key by C's pointer, which C may free or reuse. The generated docs on such a + parameter say memory grows with each distinct value and is never freed. This is sound + for a shared `&'static [u8]`: the copy is immutable and never freed, and equal bytes + differ only by address. Refuse with a span any other `'static` borrow, such as a + `&'static mut` (interning would alias it) or a non-byte element type. + - `rustls::ConfigBuilder`, both by value and behind an `Arc`: + ✅ left out and listed (rejected: a handle everywhere). + - `qmux::Session::connect` and `accept`, bounded by qmux's `Transport`: ✅ left out and + listed (rejected: a callback interface). + - `moq_sock::demux::Discard::ALL` (`[Discard; 4]`): ✅ crosses as the `Vec` of its + elements, as a returned slice does (rejected: left out). + +Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/moq-main.md b/quest/m1/ffi-refusals/moq-main.md deleted file mode 100644 index e41d8b213..000000000 --- a/quest/m1/ffi-refusals/moq-main.md +++ /dev/null @@ -1,28 +0,0 @@ -# [M] Every refusal at moq's main has a rule - -## Goal - -`just ffi moq-cpp ` at moq's `main` exports with no error and no new exclude: -each construct the export refuses there, beyond -`NonZero`, which exports, either exports by a rule or is left out as what C -can never hold. Measured on 2026-11-12 at moq `6936f0a` -([the pin bump](/quest/m1/ffi-refusals/moq-pin.md)): single refusals such as -`qmux::Session` and `CertificateDer`, third-party types taken by value; a borrowing -future from the non-async `Server::accept`; and borrowed returns that are not `Clone`. - -## Plan - -[The epic](/quest/m1/ffi-refusals/README.md)'s decisions apply: rust2 asks moq for no -source change, a third-party type behind an `Arc` crosses as an opaque handle, and what C -can never hold is left out and listed. - -- Start from a census at a moq `main` checkout, and list every refusal it still has by - construct in the PR. A construct that needs a decision the epic does not already make - becomes its own quest here, with the options and a recommendation, rather than a guess. -- Recommended for a third-party type by value: an opaque handle with none of its API, as - the `Arc` form already is, since the value moves into the handle exactly. -- Recommended for the borrowing future of a non-async fn: the rule async fns' borrowing - futures already follow ([#710](https://github.com/kixel-ai/rust2/pull/710)). -- No exclude is added to `ffi/moq/ffi.toml` to pass. - -Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/moq-pin.md b/quest/m1/ffi-refusals/moq-pin.md index 30c9c5a02..db0cb6c8a 100644 --- a/quest/m1/ffi-refusals/moq-pin.md +++ b/quest/m1/ffi-refusals/moq-pin.md @@ -60,7 +60,7 @@ split on 2026-11-12 moved the `just ts moq` failure to 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). -[kixel-ai/rust2#721](https://github.com/kixel-ai/rust2/pull/721) made the exporter change: a +[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, the glue naming them through its own dependency on their crate's @@ -108,7 +108,3 @@ returns that are not `Clone`. `rs/moq-tokio/src/client.rs:748`, on the `Instrumented<...>` from `tokio::spawn(panic::isolate(time::run(driver)).instrument(..))`, and in the moq-ffi facade on `moq_net::Driver: Sync`. - -## Required - -- [Every refusal at moq's main](/quest/m1/ffi-refusals/moq-main.md) - the rest of them, so the bump adds no exclude diff --git a/quest/m1/ffi-refusals/no-config.md b/quest/m1/ffi-refusals/no-config.md index 5134f1bbe..c483171da 100644 --- a/quest/m1/ffi-refusals/no-config.md +++ b/quest/m1/ffi-refusals/no-config.md @@ -30,4 +30,5 @@ that passes them). ## Required - [The moq pin bump](/quest/m1/ffi-refusals/moq-pin.md) - the pin is at moq's `main`, where the census is taken +- [What the excludes hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md) - exports the constructs the census still refuses there behind an exclude - [Not Send](/quest/m1/ffi-export/not-send.md) - exports the three types the census still refuses for not being `Send`