diff --git a/ffi/README.md b/ffi/README.md index 2000f5c14..78a3ceef1 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -112,14 +112,15 @@ public path names, or an error taken by value, is held by value as an opaque han | `bool`, integers but 128-bit, floats, `char` | `bool`, `` types, `float`, `double`, a `uint32_t` code point | | `u128` | `_u128`: its low and high 64 bits | | `NonZero` of an integer but 128-bit | `T`, in every binding too; a zero passed in aborts, and `Option>` is `T`'s option | -| `[u8; N]` | `_array_u8_`: a struct of its `N` bytes, `items`, copied across; an empty one, or one of any other element, is refused | +| `[u8; N]` | `_array_u8_`: a struct of its `N` bytes, `items`, copied across; an empty one is refused | +| `[T; N]` of any other `T`, returned or a constant's value | `Vec` of its `N` items; taken, it is refused | | `&str`, `String`, `&[u8]`, `Vec`, `bytes::Bytes` | `_buf`: an owned buffer returned; passed in, a view, or a buffer Rust returned, which Rust takes back without a copy unless it sits behind a pointer or in an array; `_buf_clone` shares one the caller keeps, which a `Vec`, `String`, or `PathBuf` parameter then copies, since only a sole owner's allocation becomes a `Vec` | | `&Path`, `PathBuf` | `_buf` of the path's bytes as the OS holds them on Unix, which need not be UTF-8, else UTF-8 | | `Duration` | `_duration` | | `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` | `_socket_addr`: its IP's bytes, port, and whether it is IPv6; one of the other family passed to `V4` or `V6` aborts | | `url::Url` | an object `_Url`, made by `_Url_parse`, which fails with the parse error's message, and printed by `_to_string` | -| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | -| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | +| `Arc` of another crate's `Send` and `Sync` type that no other rule maps, such as `Arc`, or `Arc` and `&'static dyn Trait` of another crate's trait without generic arguments, whose auto traits are `Send` and `Sync` but those the trait implies, borrowing nothing C lends, as rustls's `Arc` | an opaque object named by `T`'s crate and name, such as `_rustls_ServerConfig`, with `_clone` and `_free` and none of `T`'s API: it only passes back to Rust | +| another crate's `Send` and `Sync` type taken or returned by value or lent, with no type parameters, that no other rule maps, that is no iterator or future, and that is not reached by its public path, such as one only a `#[doc(hidden)]` module names, or a standard library type no other rule maps, such as `io::Error`, named by its full path, `_std_io_Error` | an opaque object named as the `Arc` form is, with `_free` and none of `T`'s API, holding the value: Rust takes it back by value, or borrows it; a type also named behind an `Arc` is that form, and refused by value | | `std::time::Instant` | an object `_Instant`, which only Rust makes, copied into each call that takes it and compared by `_eq`, with none of its methods | | `tracing::Level` | `_Level`: a C enum of its five levels, `TRACE` to `ERROR` | | `tracing::level_filters::LevelFilter` | `Option`, whose `None` is `OFF` | @@ -139,6 +140,7 @@ public path names, or an error taken by value, is held by value as an opaque han | `impl Into`, where `X` does not map | what a `From` implementation into `X` takes: a source parameter by its bounds as above, so `impl> From for Timed` takes `Bytes`, and by each `Into` whose `Y` does not map, what converts into `Y` in turn, each `Y` once and refusing a chain longer than the crate's recursion limit; any other source as it is, so `impl<'a, V> From<&'a V> for Timed<&'a V>` takes `&V`. Two sources C passes as one buffer, such as `String` and `Vec`, are refused, unless they are forms of one value, as `&str` and `String` are | | `impl IntoIterator`, where `X` is no type parameter | `Vec`, or `&[Y]` where `X` is `&Y` | | `impl io::Read`, not bounded by `Seek` | `&[u8]` | +| `impl Iterator` taken | `Vec`, whose items Rust iterates; for `X` of `&str` or `&[u8]`, an array of buffers C lends for the call; an iterator of other references, or one a future or a callback takes, is refused | | another type parameter | `serde_json::Value` for a serde `Serialize` or `Deserialize` bound, else the first of `String`, `Bytes`, and `Vec` meeting its bounds, or a foreign implementation of its one exported trait; else an instance of the function at each type the exports implement a trait bounding it for, through a blanket impl at each type implementing what the impl requires, as `&X` where that meets its bounds too and no bound, its own or one a supertrait implies, makes it outlive the call, so C keeps its handle, and, as an argument of a generic type, at each argument of an instance that meets its bounds and makes each generic type the signature names an instance | | a const parameter of a function | an instance of the function at each value an instance of a generic type the signature passes it to has there, where each generic type the signature then names is an instance | | a const argument | a `bool` or an integer below 128 bits; any other is refused | @@ -158,11 +160,11 @@ A record or enum holds only values and `Copy` handles: one with a field that doe or that holds itself, is an object instead, and the census lists it. A borrowed return is returned as a clone, so it must be `Clone`, and a handle in it is a new handle to the clone, but for an object a `&self` method of an object returns borrowed from its receiver -alone, or an object's `pub` field holds: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it +alone, or an object's `pub` field holds, bare or as an `Option`'s `Some`: that one, if not `Clone`, is a lent handle, which holds its receiver and checks it on each use, on one thread at a time where the receiver is not `Sync`. A handle outlives every call, so every lifetime an object takes is `'static`, as is every lifetime that must outlive one; any other lifetime is the call's. A signature may not lend C's borrow for one that is `'static`, but for a -`&str`, which Rust interns, nor return an object that borrows. A parameter is a reference +`&str` or `&[u8]`, which Rust interns, nor return an object that borrows. A parameter is a reference only at its top or as `Some` of an `Option`, lent as the reference alone is, so `Option<&T>` is a null or borrowed handle, a null or viewed buffer, or an option of a value, and not inside a `Box` or any other type. A `&mut` of a value, but a `str` or a @@ -170,7 +172,8 @@ slice, is in and out, and not inside an `Option`, a callback, or a future, nor b by what the call returns; a `&mut` of another crate's `Arc` is refused. Only a bare returned `&Object` is lent, never one inside what a call returns nor its error. What C could never hold, an object no export C can call returns or lends to a closure, a generic type no export -instantiates, and whatever takes one, is left out and listed in the census. Everything +instantiates, a type parameter bounded by another crate's trait no type C holds implements, +and whatever takes one, is left out and listed in the census. Everything else is refused, and the census counts why. ## Targets @@ -283,8 +286,8 @@ where it was while its file is unchanged. shared and aborts, naming the function, once it was since borrowed exclusively, moved out, or freed, which Rust's borrow checker would refuse. Borrowing a lent handle exclusively aborts too, as Rust lent it shared. -- **Interned strings**: a `&str` a function needs for `'static`, as `Path::from_static` - does, is leaked once per distinct content and reused for every later equal one, so a +- **Interned strings**: a `&str` or `&[u8]` a function needs for `'static`, as + `Path::from_static` and `CertificateDer::from_slice` do, is leaked once per distinct content and reused for every later equal one, so a caller passing ever-new strings grows the set without bound. - **Arrays** of a `Vec` are a pointer, a length, and an owner, as a buffer is: passed in, Rust copies each element out of C's array, or for a slice of a fixed-width integer diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 93a1a5573..7d0a4dc1c 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -678,6 +678,33 @@ fn main() { String::from_utf8_lossy(&api::cert_der(cert)), api::chain_len(chain) ); + // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. + let resolver = api::resolver("r1"); + println!("resolver {}", api::resolved(resolver)); + let mut codecs = api::Codecs::new(); + println!("codecs {}", codecs.ids()); + let mut list = codecs.list.clone(); + list.reverse(); + codecs.list = list; + println!("codecs reversed {}", codecs.ids()); + // A standard library value no type maps, in a handle. + let failure = api::failure("boom"); + println!( + "failure {} {}", + api::failure_message(&failure), + api::failure_kind(failure) + ); + // Iterators, passed as the arrays of their items. + println!("sum_all {}", api::sum_all(vec![1u32, 2, 3].into_iter())); + println!("weigh_all {}", api::weigh_all(vec![Counter::new("w", 3)].into_iter())); + println!("offered_len {}", api::offered_len([&b"h3"[..], b"moq-00"].into_iter())); + println!("join_words {}", api::join_words(["a", "b", "c"])); + // Bytes that must be `'static`, interned. + println!("der {}", String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes())); + println!( + "der again {}", + String::from_utf8_lossy(&api::Der::from_slice(b"der").bytes()) + ); let session = api::resume("h3", 60).unwrap(); println!("resume {} {}", session.alpn(), session.lifetime().seconds); println!("resume err {}", api::resume("", 60).err().unwrap()); @@ -689,6 +716,11 @@ fn main() { println!("cleared {}", meters.first().count()); meters.last.add(4); println!("field lent {}", meters.last.add(1)); + // An optional field that is not Clone, lent as `Some` of a handle. + println!("spare {}", meters.spare.is_some()); + meters.spare = Some(api::Meter::default()); + meters.spare.as_ref().unwrap().add(5); + println!("spare lent {}", meters.spare.as_ref().unwrap().add(1)); let tallies = api::Tallies::new(); tallies.first().bump(); println!("tallied {}", tallies.first().bump()); @@ -799,6 +831,7 @@ fn main() { // Slices, passed in and returned as clones, and the socket address of each family. println!("shapes {:?} greetings {:?}", api::Shape::ALL, api::GREETINGS); + println!("both {:?} primes {:?}", api::Shape::BOTH, api::PRIMES); let trail = api::Trail::new( &[api::Point { x: 1, y: 2 }, api::Point { x: 3, y: 4 }], &["a".to_string(), "b".to_string()], diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 5714fb9da..b3e7f593a 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -602,11 +602,13 @@ impl Meter { } } -/// Owns a meter it lends, and one in a field, lent as the method's is. +/// Owns a meter it lends, and one in a field, lent as the method's is, and an optional one, +/// lent as `Some` of it. #[derive(Default)] pub struct Meters { first: Meter, pub last: Meter, + pub spare: Option, } impl Meters { @@ -2710,6 +2712,133 @@ pub fn blame(err: tls::held::Invalid) -> String { err.to_string() } +/// Another crate's trait object behind an `Arc`: an opaque handle, taken back as the `Arc`. +pub fn resolver(name: &str) -> Arc { + Arc::new(tls::held::Named(name.to_string())) +} + +/// The name a resolver resolves, from its handle. +pub fn resolved(resolver: Arc) -> String { + resolver.name() +} + +/// A resolver as a tuple struct's field, whose accessors each binding names as its `_0`. +pub struct Resolving(pub Arc); + +impl Resolving { + pub fn new(name: &str) -> Self { + Self(resolver(name)) + } +} + +/// Codecs, each another crate's `&'static dyn Codec`, held by value in an opaque handle. +pub struct Codecs { + pub list: Vec<&'static dyn tls::held::Codec>, + seen: u8, +} + +impl Codecs { + pub fn new() -> Self { + Self { + list: vec![&tls::held::ZLIB, &tls::held::BROTLI], + seen: 0, + } + } + + /// The ids of the listed codecs, in order, as one number of a digit each. + pub fn ids(&mut self) -> u32 { + self.seen += 1; + self.list.iter().fold(0, |n, codec| n * 10 + u32::from(codec.id())) + } +} + +impl Default for Codecs { + fn default() -> Self { + Self::new() + } +} + +/// A standard library value no exported type maps: an opaque handle held by value. +pub fn failure(message: &str) -> std::io::Error { + std::io::Error::other(message.to_string()) +} + +/// The failure's message, borrowed from its handle. +pub fn failure_message(error: &std::io::Error) -> String { + error.to_string() +} + +/// The failure's kind, taken back by value. +pub fn failure_kind(error: std::io::Error) -> String { + format!("{:?}", error.kind()) +} + +/// The sum of what an iterator yields, which C passes as the array of its items. +pub fn sum_all(items: impl Iterator) -> u32 { + items.sum() +} + +/// What a counter weighs, owned or borrowed, which C cannot implement for its constant. +pub trait Weigh { + const SCALE: u64; + fn weight(&self) -> u64; +} + +impl Weigh for Counter { + const SCALE: u64 = 1; + fn weight(&self) -> u64 { + self.get() * Self::SCALE + } +} + +impl Weigh for &Counter { + const SCALE: u64 = 10; + fn weight(&self) -> u64 { + self.get() * Self::SCALE + } +} + +/// The weights of an iterator's items summed: C passes the array of its counters, each +/// moved in, so `&Counter`'s weight is not taken. +pub fn weigh_all, W: Weigh>(items: I) -> u64 { + items.map(|item| item.weight()).sum() +} + +/// The total length of borrowed byte strings, as moq-tokio's TLS acceptor reads offered ALPNs. +pub fn offered_len<'a>(alpns: impl Iterator) -> usize { + alpns.map(<[u8]>::len).sum() +} + +/// Words joined with spaces: an `IntoIterator` of what converts to `&str`, as moq-tokio's +/// WebSocket listener takes its protocols. +pub fn join_words(words: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + let words: Vec = words.into_iter().map(|w| w.as_ref().to_string()).collect(); + words.join(" ") +} + +/// Bytes that must outlive every handle, as rustls's `CertificateDer::from_slice` borrows +/// its DER: the glue interns them. +pub struct Der<'a>(&'a [u8]); + +impl<'a> Der<'a> { + pub fn from_slice(bytes: &'a [u8]) -> Self { + Self(bytes) + } + + pub fn bytes(&self) -> Vec { + self.0.to_vec() + } +} + +/// Reads a stream no type C holds implements: left out, as C never holds one. +pub fn pump(mut stream: T) -> u8 { + stream.read() +} + /// 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 { @@ -3064,11 +3193,17 @@ impl Site { impl Shape { /// Every shape, as a constant slice. pub const ALL: &'static [Shape] = &[Shape::Circle, Shape::Square]; + + /// Every shape, as a constant array, returned as the array of its elements. + pub const BOTH: [Shape; 2] = [Shape::Circle, Shape::Square]; } /// Greetings, as a constant slice of references, each returned as a clone. pub const GREETINGS: &[&str] = &["hi", "hello"]; +/// Primes, as a constant array of a block's element. +pub const PRIMES: [u32; 3] = [2, 3, 5]; + /// A trail through points, each labeled: slices passed in and lent back out. pub struct Trail { points: Vec, diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index db45287ed..411d63481 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -1,153 +1,162 @@ -fixtures/reject/src/lib.rs:1015: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:1022: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:1028: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:1033: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:1038: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:1044: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:1046:2: note: has this discriminant -fixtures/reject/src/lib.rs:1051: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:1053:2: note: has this discriminant -fixtures/reject/src/lib.rs:1058: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:1060: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:1064:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1069:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1075:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1089:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1095:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1100:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1105: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:1095:1: note: C cannot implement `Trusted`: unsafe trait -fixtures/reject/src/lib.rs:1110: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:1100:1: note: C cannot implement `Hazard`: unsafe fn `risk` -fixtures/reject/src/lib.rs:1115: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: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:1137:1: rust2-ffi: cannot export fn `wrap`: returned object that borrows `View<'_>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1142:1: rust2-ffi: cannot export fn `hidden_wrap`: returned object that borrows `impl std::clone::Clone + '_`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1158:1: rust2-ffi: cannot export fn `picked`: closure signature `&'static Mark`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1163:1: rust2-ffi: cannot export fn `maybe_picked`: closure signature `std::option::Option<&'static Mark>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1168: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:1173: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:1178: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:1183: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:1199:2: rust2-ffi: cannot export method `Counter::try_bump`: `&mut self` of a value returning a Result; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1000: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:1016: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:1023: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:1029: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:1034: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:1039: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:1045: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:1047:2: note: has this discriminant +fixtures/reject/src/lib.rs:1052: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:1054:2: note: has this discriminant +fixtures/reject/src/lib.rs:1059: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:1061:2: note: has this discriminant +fixtures/reject/src/lib.rs:1065:1: rust2-ffi: cannot export fn `raw`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:106:1: rust2-ffi: cannot export fn `forever_mut`: 'static borrow `&'static mut [u8]`; &mut of a slice `[u8]`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1070:1: rust2-ffi: cannot export fn `sum`: C-variadic function; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1076:1: rust2-ffi: cannot export fn `custom`: uncallable ABI `"custom"`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1090:2: rust2-ffi: cannot export method `Raw::peek`: unsafe fn; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1096:1: rust2-ffi: cannot export trait `Trusted`: unsafe trait; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1101:1: rust2-ffi: cannot export trait `Hazard`: unsafe fn `risk`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1106: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:1096:1: note: C cannot implement `Trusted`: unsafe trait +fixtures/reject/src/lib.rs:1111: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:1101:1: note: C cannot implement `Hazard`: unsafe fn `risk` +fixtures/reject/src/lib.rs:1116:1: rust2-ffi: cannot export fn `wide_non_zero`: NonZero `u128`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:112:1: rust2-ffi: cannot export fn `boxed`: reference inside a parameter `std::boxed::Box<&str>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1138:1: rust2-ffi: cannot export fn `wrap`: returned object that borrows `View<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1143:1: rust2-ffi: cannot export fn `hidden_wrap`: returned object that borrows `impl std::clone::Clone + '_`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1159:1: rust2-ffi: cannot export fn `picked`: closure signature `&'static Mark`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1164:1: rust2-ffi: cannot export fn `maybe_picked`: closure signature `std::option::Option<&'static Mark>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1169: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:1174: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:1179: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:1184: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:1189:1: rust2-ffi: cannot export fn `count_later`: iterator of borrows in a future or callback; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1194:1: rust2-ffi: cannot export fn `count_opaques`: generic parameter `std::iter::Iterator`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1199:1: rust2-ffi: cannot export fn `unpin_resolver`: trait object `dyn tls::held::Resolver + std::marker::Unpin`; exclude it in the config to leave it out fixtures/reject/src/lib.rs: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:1204:2: rust2-ffi: cannot export method `Counter::bump_later`: `&mut self` of a value in a future; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:1209:2: rust2-ffi: cannot export method `Counter::bump_ref`: returned borrow of a value written back `&u8`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:127: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:144: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:161: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:166: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:166: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:169: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:1204:1: rust2-ffi: cannot export fn `borrowed_resolver`: returned object that borrows `std::sync::Arc<(dyn tls::held::Resolver + 'a)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1209:1: rust2-ffi: cannot export fn `peek_resolver`: reference to a handle inside a value `std::option::Option>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1214:1: rust2-ffi: cannot export fn `peek_codec`: trait object `dyn tls::held::Codec`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1229:1: rust2-ffi: cannot export fn `pump_pipe`: generic parameter `tls::held::Stream`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1234:1: rust2-ffi: cannot export fn `pump_sink`: generic parameter `tls::held::Sink`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1239:1: rust2-ffi: cannot export fn `widen`: generic parameter `tls::held::Width`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1255:2: rust2-ffi: cannot export method `Counter::try_bump`: `&mut self` of a value returning a Result; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1260:2: rust2-ffi: cannot export method `Counter::bump_later`: `&mut self` of a value in a future; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:1265:2: rust2-ffi: cannot export method `Counter::bump_ref`: returned borrow of a value written back `&u8`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:128: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:145: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:162: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:167: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:167: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: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:175: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:180: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:185: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:190: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:195: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:200: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:210: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:170: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:176: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:181: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:186: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:191: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:196: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:201: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:211: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:220: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:232: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:251: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:262: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:265: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:276: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:285: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:296:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:301: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:306: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:221: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:233: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:252: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:263: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:266: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:277: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:286: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:297:1: rust2-ffi: cannot export fn `probe`: const generic `N`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:302: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:307: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: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:311: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:314: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:319: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:322: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:330: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:340: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:345: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:350: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:355: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:312: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:315: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:320: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:323: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:331: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:341: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:346: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:351: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:356: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:35:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:360: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:365: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:370: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:376: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:382: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:387: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:392: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:397: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:361: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:366: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:371: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:377: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:383: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:388: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:393: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:398: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:39:1: rust2-ffi: cannot export macro `noop`: macro; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:402: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:407: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:419: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:434: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:439: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:444: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:458: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:472: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:403: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:408: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:420: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:435: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:440: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:445: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:459: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:473: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: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:487: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:502: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:525: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:488: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:503: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:526: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:52:1: rust2-ffi: cannot export fn `letters`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:540:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out - fixtures/reject/src/lib.rs:532:1: note: applies past the recursion limit -fixtures/reject/src/lib.rs:570: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:547:1: note: `std::string::String` converts too, which C passes alike -fixtures/reject/src/lib.rs:575:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:580: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:585: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:590: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:595: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:621: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:626: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:600:1: note: C cannot implement `Source`: callback signature `items` -fixtures/reject/src/lib.rs:631: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:636: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:636:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:643: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:643:20: note: `'b` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:650: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:650:20: note: `'a` is `'static`, as a handle outlives every call -fixtures/reject/src/lib.rs:659: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:665: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:541:1: rust2-ffi: cannot export fn `grows`: growing conversion `Grows`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:533:1: note: applies past the recursion limit +fixtures/reject/src/lib.rs:571: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:548:1: note: `std::string::String` converts too, which C passes alike +fixtures/reject/src/lib.rs:576:1: rust2-ffi: cannot export fn `alphabet`: Range `char`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:581: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:586: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:591: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:596: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:622: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:627: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:601:1: note: C cannot implement `Source`: callback signature `items` +fixtures/reject/src/lib.rs:632: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:637: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:637:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:644: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:644:20: note: `'b` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:651: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:651:20: note: `'a` is `'static`, as a handle outlives every call +fixtures/reject/src/lib.rs:660: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:666: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: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:671: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:688: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:672: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:689: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:705: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:728: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:742: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:747: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:754: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:760: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:765: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:770: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:706: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:729: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:743: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:748: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:755: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:761: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:766: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:771: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:790: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:797: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:821: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:839: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:844: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:849: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:855: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:861: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:872: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:891: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:896: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:903: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:910: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:915: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:922: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:927: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:932: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:937: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:950: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:961: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:964: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:975: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:993:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:999: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:791: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:798: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:822: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:840: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:845: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:850: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:856: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:862: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:873: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:892: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:897: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:904: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:911: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:916: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:923: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:928: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:933: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:938: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:951: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:962: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:965: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:976: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:994:2: rust2-ffi: cannot export method `Risky::new`: unsafe fn; 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 0e1bb80a0..0b8572f02 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -101,8 +101,9 @@ impl<'a> Text<'a> { } } -/// Bytes that must be `'static`, which only a string's interning makes them. -pub fn forever(bytes: &'static [u8]) -> usize { +/// Bytes lent mutably for as long as the program runs, which interning would alias: every +/// call with equal bytes would share one copy. +pub fn forever_mut(bytes: &'static mut [u8]) -> usize { bytes.len() } @@ -1184,6 +1185,61 @@ pub fn boxed_bytes(bytes: Box<[u8]>) -> usize { bytes.len() } +/// An iterator of borrowed strings a future keeps past the call that lent them. +pub async fn count_later<'a>(words: impl Iterator + Send) -> usize { + words.count() +} + +/// An iterator of borrowed objects, which C lends none of inside an array. +pub fn count_opaques<'a>(items: impl Iterator) -> usize { + items.count() +} + +/// A trait object with another auto trait than the one form its handle names. +pub fn unpin_resolver() -> std::sync::Arc { + std::sync::Arc::new(tls::held::Named("unpin".into())) +} + +/// A trait object that borrows, which no handle outliving the call may hold. +pub fn borrowed_resolver<'a>(_ids: &'a [u32]) -> std::sync::Arc { + std::sync::Arc::new(tls::held::Named("borrowed".into())) +} + +/// A trait-object handle inside a borrowed value, which lifting would take out of C's handle. +pub fn peek_resolver(resolver: &Option>) -> bool { + resolver.is_some() +} + +/// A `'static` trait-object handle inside a borrowed value, refused as the `Arc` form is. +pub fn peek_codec(codec: &Option<&'static dyn tls::held::Codec>) -> bool { + codec.is_some() +} + +/// A stream an exported type implements, so the bound is met by a value C holds: refused, +/// not left out. +pub struct Pipe(pub u8); + +impl tls::held::Stream for Pipe { + fn read(&mut self) -> u8 { + self.0 + } +} + +/// Reads one byte of a stream. +pub fn pump_pipe(mut stream: T) -> u8 { + stream.read() +} + +/// A sink a reference to any exported type meets: refused, not left out. +pub fn pump_sink(sink: T) -> u8 { + sink.write(1) +} + +/// A width only `u32`, which C passes by role, meets: refused, not left out. +pub fn widen(x: T) -> u32 { + x.bits() +} + /// A `Copy` count, a value, whose change a raised error or a future would lose, and which a /// returned borrow would still hold as it is written back. #[derive(Clone, Copy)] diff --git a/ffi/fixtures/tls/src/lib.rs b/ffi/fixtures/tls/src/lib.rs index 5bbd68985..415af9925 100644 --- a/ffi/fixtures/tls/src/lib.rs +++ b/ffi/fixtures/tls/src/lib.rs @@ -193,4 +193,66 @@ pub mod held { /// A `Copy` token, which an opaque handle holds by value. #[derive(Clone, Copy, Debug)] pub struct Token(pub u32); + + /// A trait C never implements, whose `Arc` an opaque handle holds, as + /// moq-tokio's TLS server takes rustls's certificate resolver. + pub trait Resolver: Send + Sync { + fn name(&self) -> String; + } + + /// A resolver of a fixed name. + pub struct Named(pub String); + + impl Resolver for Named { + fn name(&self) -> String { + self.0.clone() + } + } + + /// A trait whose `&'static dyn Codec` an opaque handle holds by value, as rustls's + /// client config lists its certificate compressors. + pub trait Codec: Send + Sync { + fn id(&self) -> u8; + } + + /// A codec of a fixed id. + pub struct Fixed(pub u8); + + impl Codec for Fixed { + fn id(&self) -> u8 { + self.0 + } + } + + /// The codecs there are, each `'static`. + pub static ZLIB: Fixed = Fixed(1); + pub static BROTLI: Fixed = Fixed(2); + + /// A stream no type C holds implements, which C cannot implement either, as tokio's + /// `AsyncRead` bounds the stream moq-tokio's TLS acceptor takes. + pub trait Stream { + fn read(&mut self) -> u8; + } + + /// A sink every reference meets, whatever it refers to, so a value C holds may meet it. + pub trait Sink { + fn write(&self, byte: u8) -> u8; + } + + impl Sink for &T { + fn write(&self, byte: u8) -> u8 { + byte + } + } + + /// A width only `u32` has, a value C passes by role, so a value C holds may meet it. + pub trait Width { + fn bits(&self) -> u32; + } + + impl Width for u32 { + fn bits(&self) -> u32 { + 32 + } + } } diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index 4f87d828e..783c59cfb 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -11,10 +11,8 @@ exclude = [ "hang::moq_net", "kio", "moq_quic::VarInt::from_u64_unchecked", - "moq_sock::demux::Discard::ALL", "moq_tokio::accept::Failure::classify", "moq_tokio::accept::Health::failed", - "moq_tokio::quic::Controller::0", "moq_tokio::quic::demux::Datagram::local", "moq_tokio::quic::driver::connection::Connection::congestion_state", "moq_tokio::quic::driver::connection::Connection::poll_closed", @@ -23,7 +21,7 @@ exclude = [ "moq_tokio::quic::driver::send::Options::group", "moq_tokio::quic::driver::send::Stream::write", "moq_tokio::tcp::TlsAcceptor::accept", - "moq_tokio::tcp::TlsAcceptor::offered", + "moq_tokio::websocket::Listener::accept", "mp4_atom::TrunSamples::iter", "mp4_atom::Tx3g::box_record", "mux::catalog::Guard", @@ -55,17 +53,9 @@ exclude = [ "mux::container::Producer::modify", "mux::container::Producer::modify", "mux::container::fmp4::mp4_atom", - "rustls::ClientConfig::cert_compressors", - "rustls::ClientConfig::cert_decompressors", - "rustls::ClientConfig::client_auth_cert_resolver", - "rustls::ClientConfig::key_log", - "rustls::ClientConfig::time_provider", "rustls::ConfigBuilder", "rustls::ConfigBuilder", "rustls::client::Resumption::store", - "rustls_pki_types::CertificateDer::from_slice", - "rustls_pki_types::Der::from_slice", - "tokio::server::Config::websocket", "tokio::server::Request::within", "tokio::tls::Serve::resolver", ] diff --git a/ffi/runtime/rt.rs b/ffi/runtime/rt.rs index 89e8c27a6..61cf66588 100644 --- a/ffi/runtime/rt.rs +++ b/ffi/runtime/rt.rs @@ -36,19 +36,33 @@ pub fn intern(s: &str) -> &'static str { s } +/// `b` for as long as the program runs, as [`intern`] keeps a string: keyed by its +/// contents, never by the caller's pointer, which the caller may free or reuse. +pub fn intern_bytes(b: &[u8]) -> &'static [u8] { + static INTERNED: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + let mut interned = INTERNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(&b) = interned.get(b) { + return b; + } + let b: &'static [u8] = Box::leak(Box::from(b)); + interned.insert(b); + b +} + /// An `Arc` of another crate's type, held erased behind a handle with none of its API, so /// the export names neither the type nor its crate. Rust takes it back as the `Arc` it /// gave, and a handle of another such type aborts. A clone clones the `Arc` itself, so /// Rust counts each handle as an owner. pub struct Opaque(Box); -/// An `Arc` of any `T`, erased. +/// An `Arc` of any `T`, a trait object's too, erased. trait Held: Send + Sync { fn any(&self) -> &dyn std::any::Any; fn clone_box(&self) -> Box; } -impl Held for Arc { +impl Held for Arc { fn any(&self) -> &dyn std::any::Any { self } @@ -65,18 +79,18 @@ impl Clone for Opaque { } impl Opaque { - pub fn new(value: Arc) -> Self { + pub fn new(value: Arc) -> Self { Self(Box::new(value)) } /// The `Arc` it holds, lent. - pub fn get(&self, what: &str) -> &Arc { + pub fn get(&self, what: &str) -> &Arc { (self.0.any().downcast_ref()) .unwrap_or_else(|| fail(what, "an opaque handle holds another type")) } /// A clone of the `Arc` it holds. - pub fn arc(&self, what: &str) -> Arc { + pub fn arc(&self, what: &str) -> Arc { Arc::clone(self.get(what)) } } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 4ce80420b..f1a3dcd9e 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -63,13 +63,18 @@ pub const NOT_INFERRED: &str = "instance not inferred"; /// What C can never hold: left out and listed in the census rather than refused, since /// exporting it would need constructors or returns the crate has no use for. -const UNHELD: [&str; 4] = [ +const UNHELD: [&str; 5] = [ "object no export returns", "value no export returns", "generic type no export instantiates", "type C never holds", + UNMET, ]; +/// The construct of a type parameter bounded by another crate's trait that no export +/// implements and C cannot: no value C holds could be passed for it. +const UNMET: &str = "bound no type C holds meets"; + fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -260,6 +265,8 @@ struct Collector<'tcx> { /// lent from the receiver's handle. lending: std::cell::Cell, bytes: Option, + /// `std::vec::IntoIter`, which an `impl Iterator` parameter takes. + vec_iter: Option, /// `serde_json::Map`, a map of `serde_json::Value`s. json_map: Option, /// The standard library's crates, `core`, `alloc`, and `std`, known by what each @@ -330,6 +337,26 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { }; let bytes = root("bytes", "Bytes"); let json_map = root("serde_json", "Map"); + // What `Vec` iterates by value as. + let vec_iter = (|| { + let into_iter = tcx.get_diagnostic_item(sym::IntoIterator)?; + let assoc = (tcx + .associated_items(into_iter) + .filter_by_name_unhygienic(rustc_span::Symbol::intern("IntoIter"))) + .next()?; + let vec = tcx.get_diagnostic_item(sym::Vec)?; + let alloc = tcx.lang_items().global_alloc_ty()?; + let alloc = Ty::new_adt(tcx, tcx.adt_def(alloc), ty::GenericArgs::empty()); + let vec = Ty::new_adt(tcx, tcx.adt_def(vec), tcx.mk_args(&[tcx.types.u8.into(), alloc.into()])); + let iter = Ty::new_projection(tcx, ty::IsRigid::No, assoc.def_id, [vec]); + let iter = tcx + .try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), ty::Unnormalized::new_wip(iter)) + .ok()?; + match iter.kind() { + ty::Adt(adt, _) => Some(adt.did()), + _ => None, + } + })(); let sysroot: Vec = [ tcx.lang_items().sized_trait(), tcx.lang_items().owned_box(), @@ -401,6 +428,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected { impls: Default::default(), lending: Default::default(), bytes, + vec_iter, json_map, sysroot: sysroot.clone(), foreign: Vec::new(), @@ -903,25 +931,61 @@ impl<'tcx> Collector<'tcx> { return None; } let inner = args.type_at(0); - let ty::Adt(adt, inner_args) = inner.kind() else { - return None; + let (did, inner_args) = match inner.kind() { + ty::Adt(adt, inner_args) => (adt.did(), inner_args.as_slice()), + ty::Dynamic(..) => (self.held_trait(inner)?, &[][..]), + _ => return None, }; - let did = adt.did(); let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); let held = !self.walked(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; (held && inner_args.is_empty() && self.is_send(inner, TypingEnv::fully_monomorphized()) && self.is_sync(inner)) .then_some(did) } + /// The trait of a trait object an opaque handle may hold: one of a crate the walk from + /// the root does not reach, and not the standard library's, whose traits are closures and + /// markers; taking no arguments, as its handle names none; and with no associated type + /// fixed, which would be one. + /// + /// One object type per trait, as the handle names only the trait: its auto traits are + /// `Send` and `Sync` but those the trait implies, as `dyn Trait + Send + Sync` and, where + /// the trait has them as supertraits, `dyn Trait` are. Its lifetime is held, as + /// [`Self::lifetimes`] says, so one that borrows what C lends is refused. + fn held_trait(&self, ty: Ty<'tcx>) -> Option { + let tcx = self.tcx; + let ty::Dynamic(preds, _) = ty.kind() else { + return None; + }; + let principal = preds.principal()?.skip_binder(); + let did = principal.def_id; + let plain = principal.args.is_empty() && preds.projection_bounds().next().is_none(); + let implied: Vec = rustc_middle::ty::elaborate::supertrait_def_ids(tcx, did).collect(); + let canonical: Vec = [tcx.get_diagnostic_item(sym::Send), tcx.get_diagnostic_item(sym::Sync)] + .into_iter() + .flatten() + .filter(|tr| !implied.contains(tr)) + .collect(); + let auto: Vec = preds.auto_traits().collect(); + let same = auto.len() == canonical.len() && auto.iter().all(|tr| canonical.contains(tr)); + (plain && same && !self.walked(did.krate) && !self.sysroot.contains(&did.krate)).then_some(did) + } + /// The type a handle holds by value, if it exports as an opaque handle: as /// [`Self::opaque_arc`]'s, a type of a crate the walk from the root does not reach, /// taking no type parameters, and `Send` and `Sync`, but not an iterator or a future, /// nor one that exports by its own crate's path. Its lifetimes are `'static`, as an object's are. fn opaque_value(&self, ty: Ty<'tcx>) -> Option { + // A `'static` borrow of a trait object is a value, as `&'static dyn Trait` is `Copy`, + // held as the `Arc` form's trait is. + if let ty::Ref(region, inner, ty::Mutability::Not) = ty.kind() { + let did = self.held_trait(*inner).filter(|_| region.is_static())?; + return (self.opaque(did) && self.is_send(ty, TypingEnv::fully_monomorphized()) && self.is_sync(ty)) + .then_some(did); + } let ty::Adt(adt, args) = ty.kind() else { return None }; let did = adt.did(); - let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did); - let held = !self.walked(did.krate) && !self.sysroot.contains(&did.krate) && !mapped; + let mapped = Some(did) == self.bytes || Some(did) == self.json_map || !self.opaque(did) || self.by_role(did); + let held = !self.walked(did.krate) && !mapped; // Each lifetime is `'static` in the export, as an object's is. let erasable = args.iter().all(|arg| matches!(arg.kind(), GenericArgKind::Lifetime(_))); // Asked of a signature's type, whose lifetimes may be bound by it. @@ -942,6 +1006,30 @@ impl<'tcx> Collector<'tcx> { .then_some(did) } + /// Whether `did` is one of the standard library's types that crosses by its role rather + /// than in a handle, such as `String` or `SocketAddr`, or that will: `IpAddr` and its + /// families, which stay refused until they cross as `SocketAddr` does. A collection's + /// allocator and hasher are part of the collection's role. + fn by_role(&self, did: DefId) -> bool { + const ROLES: [&str; 14] = [ + "String", + "Duration", + "Path", + "PathBuf", + "Waker", + "Context", + "SocketAddr", + "SocketAddrV4", + "SocketAddrV6", + "IpAddr", + "Ipv4Addr", + "Ipv6Addr", + "Global", + "RandomState", + ]; + self.sysroot.contains(&did.krate) && ROLES.contains(&self.tcx.item_name(did).as_str()) + } + /// Whether `did`, the type of `ty`, exports with its API by its public path in its own /// crate once a signature names it: an error never does, crossing as its message. fn reaches(&self, ty: Ty<'tcx>, did: DefId) -> bool { @@ -995,6 +1083,10 @@ impl<'tcx> Collector<'tcx> { /// Whether the foreign type `did` is a value C holds as its bytes, as a `Copy` one is. fn foreign_value(&self, did: DefId) -> bool { let tcx = self.tcx; + // A trait object's handle holds the `Arc` or `&'static`, never a value. + if tcx.def_kind(did) == DefKind::Trait { + return false; + } let ty = tcx.type_of(did).instantiate_identity().skip_norm_wip(); !self.opaque(did) && implements(tcx, ty, did, sym::Copy) && padding(tcx, ty).is_some() } @@ -1724,23 +1816,33 @@ impl<'tcx> Collector<'tcx> { let name = tcx.item_name(def_id); if self.opaque(def_id) { let owned = self.owned.contains(&def_id); + // A trait's handle holds a trait object of it. + let held = match tcx.def_kind(def_id) { + DefKind::Trait if owned => format!("&'static dyn {}", tcx.def_path_str(def_id)), + DefKind::Trait => format!("dyn {}", tcx.def_path_str(def_id)), + _ => tcx.def_path_str(def_id), + }; let docs = match owned { true => format!( - "`{}`: a handle to another crate's value, which Rust takes back or borrows, with none of its API.", - tcx.def_path_str(def_id) + "`{held}`: a handle to another crate's value, which Rust takes back or borrows, with none of its API." ), false => format!( - "`Arc<{}>`: a handle to another crate's value, which Rust takes back, with none of its API.", - tcx.def_path_str(def_id) + "`Arc<{held}>`: a handle to another crate's value, which Rust takes back, with none of its API." ), }; + // The standard library's is named through its module, as `std::io::Error`, since its + // names repeat across modules. + let path: Path = match self.sysroot.contains(&def_id.krate) { + true => tcx.def_path_str(def_id).split("::").map(str::to_string).collect(), + false => vec![krate.to_string(), name.to_string()], + }; return Object { - path: vec![krate.to_string(), name.to_string()], home: Home { krate: self.keys[&def_id.krate].clone(), outside: 2, }, - shown: vec![self.report.root.clone(), krate.to_string(), name.to_string()], + shown: [&[self.report.root.clone()][..], &path].concat(), + path, args: Vec::new(), span, on: On::ALL, @@ -1941,7 +2043,20 @@ impl<'tcx> Collector<'tcx> { fn arg(&self, ty: Ty<'tcx>) -> Result { let arg = match ty.kind() { ty::Tuple(list) if list.is_empty() => Type::Unit, - _ => self.ty(ty, Pos::Behind)?, + _ => match self.ty(ty, Pos::Behind) { + Ok(arg) => arg, + // A type a handle holds erased, which the glue never names, names no instance C + // holds. + Err(why) + if why.construct == "foreign type" + && let ty::Adt(adt, _) = ty.kind() + && (self.barred.contains(&adt.did()) + || self.foreign.iter().any(|&(other, _)| other == adt.did())) => + { + return Err(self::why("type C never holds", self.spell(ty))); + } + Err(why) => return Err(why), + }, }; match arg { Type::Unit @@ -2432,8 +2547,13 @@ impl<'tcx> Collector<'tcx> { let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); // A field that is an object but not `Clone` is lent from the receiver's handle, // as a method's borrowed return of one is. + // So is an `Option` of one, as `Some` of the borrow. + let object = match ty.kind() { + ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => args.type_at(0), + _ => ty, + }; let lends = !self.is_clone(ty) - && matches!(ty.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); + && matches!(object.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); let mapped = { self.lending.set(lends); let get = self.ty(read, Pos::Return); @@ -2484,8 +2604,7 @@ impl<'tcx> Collector<'tcx> { instance: None, home: Home::default(), }; - let lent = lends - && matches!(&get, Type::Ref(Mutability::Not, inner) if matches!(**inner, Type::Object(_))); + let lent = lends && lent(&get); let mut getter = accessor(Receiver::Ref, Vec::new(), get, false); getter.lends = lent; accessors.push(getter); @@ -2820,6 +2939,8 @@ impl<'tcx> Collector<'tcx> { ty::Ref(_, inner, ty::Mutability::Not) => { self.arg(inner).map(|inner| Type::Ref(Mutability::Not, Box::new(inner))) } + // An iterator parameter's instance, the array C passes, as it maps there. + ty::Adt(adt, _) if Some(adt.did()) == self.vec_iter => self.ty(ty, Pos::Param), _ => self.arg(ty), }, GenericArgKind::Lifetime(_) => unreachable!("no lifetime names an instance"), @@ -3082,6 +3203,22 @@ impl<'tcx> Collector<'tcx> { if future && params.iter().any(|p: &Param| p.ty.written()) { errs.push(why("&mut of a value in a future", "")); } + // Each borrowed item is lent for the call, which a future outlives, and a callback + // would take an iterator from Rust, which no language holds. + if (future || callback) + && params + .iter() + .any(|p: &Param| matches!(p.ty, Type::List(Collection::IterRef, _))) + { + errs.push(why("iterator of borrows in a future or callback", "")); + } + if callback + && params + .iter() + .any(|p: &Param| matches!(p.ty, Type::List(Collection::Iter, _))) + { + errs.push(why("iterator in a callback", "")); + } // A reader is lent for the call, which a future outlives. if future && params.iter().any(|p: &Param| *p.ty.base() == Type::Reader) { errs.push(why("reader lent to a future", "")); @@ -3171,8 +3308,7 @@ impl<'tcx> Collector<'tcx> { } } } - let lends = matches!(ok, Ok(Type::Ref(Mutability::Not, ref inner)) if matches!(**inner, Type::Object(_))) - && !self.is_clone(ok_ty.peel_refs()); + let lends = ok.as_ref().is_ok_and(lent) && !self.is_clone(ok_ty.peel_refs()); let ok = ok.map_err(|why| errs.push(why)).ok(); let err = match err { Some(Ok(err)) => Some(err), @@ -3182,13 +3318,24 @@ impl<'tcx> Collector<'tcx> { } None => None, }; + // What interning costs, which the caller cannot see from the parameter's type. + let mut docs = docs(tcx, def_id); + for param in params.iter().filter(|p| p.interned) { + if !docs.is_empty() { + docs.push_str("\n\n"); + } + docs.push_str(&format!( + "`{}` must live as long as the program, so each distinct value passed is copied once and never freed: memory grows with each distinct value.", + param.name + )); + } match (errs.is_empty(), ok) { (true, Some(ok)) => Ok(Function { path, shown, span: tcx.def_span(def_id), on: On::ALL, - docs: docs(tcx, def_id), + docs, receiver, params, units, @@ -3233,7 +3380,11 @@ impl<'tcx> Collector<'tcx> { let mut kept = Vec::new(); // Each choice of the parameters so far, with the arguments that name it. let mut choices: Vec<(Vec>, Vec>)> = vec![(args, Vec::new())]; - for (i, arg) in identity.iter().enumerate() { + // A parameter another iterates, as `S` in `I: IntoIterator`, is chosen first, + // so the iterator's choice sees its items. + let mut order: Vec<(usize, ty::GenericArg<'tcx>)> = identity.iter().enumerate().collect(); + order.sort_by_key(|&(_, arg)| !arg.as_type().is_some_and(|ty| self.iterated(def_id, ty))); + for (i, arg) in order { let param = match arg.kind() { _ if i < count => continue, GenericArgKind::Lifetime(_) => continue, @@ -3449,14 +3600,23 @@ impl<'tcx> Collector<'tcx> { } else if tcx.is_diagnostic_item(sym::IntoIterator, tr) { // Borrowed items iterate a slice C lends, borrowed for the items' own lifetime, // so the signature's borrows decide whether C's slice lives long enough. - let items = self.items(&identity.clauses, param).and_then(|item| match item.kind() { - ty::Ref(region, elem, ty::Mutability::Not) - if !outlives && !matches!(region.kind(), ty::ReBound(..)) => - { - Some(Ty::new_imm_ref(tcx, *region, Ty::new_slice(tcx, *elem))) - } - _ => self.vec_of(item), - }); + let items = self + .items(&identity.clauses, param, sym::IntoIterator) + .and_then(|item| match item.kind() { + ty::Ref(region, elem, ty::Mutability::Not) + if !outlives && !matches!(region.kind(), ty::ReBound(..)) => + { + Some(Ty::new_imm_ref(tcx, *region, Ty::new_slice(tcx, *elem))) + } + _ => self.vec_of(item), + }); + candidates.extend(items.map(|ty| (ty, None))); + } else if tcx.is_diagnostic_item(sym::Iterator, tr) { + // The array of its items, which Rust iterates by value: a borrowed string or bytes + // borrow what C lends for the call, the rest are owned. + let items = (self.items(&identity.clauses, param, sym::Iterator)) + .filter(|item| !outlives || !item.is_ref()) + .and_then(|item| self.vec_iter_of(item)); candidates.extend(items.map(|ty| (ty, None))); } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("IoRead"), tr) && !outlives { // What it reads, which C lends for the call. @@ -3477,11 +3637,14 @@ impl<'tcx> Collector<'tcx> { // `impl Into>` takes a `String` too, which maps where `Arc` does not. // Not another crate's type a handle holds: the glue never names it, so nothing would // fix the call's type argument. - candidates.retain(|&(candidate, _)| { + let takes = |candidate: Ty<'tcx>| { self.at(def_id, param, base, candidate).is_some() && self.maps(candidate, Pos::Param) && !(candidate.walk().filter_map(|arg| arg.as_type())).any(|ty| self.is_opaque(ty)) - }); + }; + let iterated = self.iterated(def_id, param); + // An array's items are owned, as C lends nothing inside one. + candidates.retain(|&(candidate, _)| !(iterated && candidate.is_ref()) && takes(candidate)); // Two sources that C passes as one buffer but that hold different values, as a // `String` and a `Vec` do, leave the caller no say in which conversion runs. Forms // of one value, as `&str` and `String` are, convert alike. @@ -3512,12 +3675,64 @@ impl<'tcx> Collector<'tcx> { .filter(|b| !sized.contains(&Some(b.def_id()))) .map(|b| tcx.def_path_str(b.def_id())) .collect(); + // Another crate's trait, which no type the export holds meets, as instantiating found + // none, and C cannot implement: no value C holds could be passed. The standard library's + // traits are met by values C passes, which the rules may yet take. + // An impl for a type the export names, for a value C passes by role that meets every + // bound, or for any type at all, may yet meet it. + let unmet = (bounds.iter().map(|b| b.def_id())).any(|tr| { + let foreign = !self.sysroot.contains(&tr.krate) && !marker(tcx, tr) && !self.walked(tr.krate); + let met = || { + tcx.all_impls(tr).any(|imp| { + // A blanket impl for any type, or for a reference to any type but one that + // needs that type to meet the bound itself, as tokio's `&mut T` impls do. + let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + let inner = ty.peel_refs(); + let role = || { + !ty.has_non_region_param() && takes(ty::fold_regions(tcx, ty, |_, _| tcx.lifetimes.re_erased)) + }; + match inner.kind() { + ty::Param(_) => { + ty == inner + || !(tcx.clauses_of(imp).instantiate_identity(tcx).clauses.iter()) + .filter_map(|clause| clause.skip_norm_wip().as_trait_clause()) + .any(|bound| bound.def_id() == tr && bound.self_ty().skip_binder() == inner) + } + ty::Adt(adt, _) => { + self.items.iter().any(|(item, _)| *item == adt.did()) + || self.foreign.iter().any(|&(f, _)| f == adt.did()) + || role() + } + _ => role(), + } + }) + }; + foreign && !met() || matches!(self.trait_decl(tr), Some(Decl::Refused(_))) + }); match local[..] { [_] => Err(why("callback bound", names.join(" + "))), + [] if unmet => Err(why(UNMET, names.join(" + "))), _ => Err(why("generic parameter", names.join(" + "))), } } + /// Whether `param` is the `Item` of another of `def_id`'s parameters' `IntoIterator` or + /// `Iterator` bounds. + fn iterated(&self, def_id: DefId, param: Ty<'tcx>) -> bool { + let tcx = self.tcx; + (tcx.clauses_of(def_id).instantiate_identity(tcx).clauses.iter()) + .filter_map(|clause| clause.skip_norm_wip().as_projection_clause()) + .map(|pred| pred.skip_binder()) + .any(|pred| { + let item = pred.projection_term.expect_projection_def_id(); + let iterator = tcx.parent(item); + (tcx.is_diagnostic_item(sym::IntoIterator, iterator) || tcx.is_diagnostic_item(sym::Iterator, iterator)) + && tcx.item_name(item) == sym::Item + && pred.projection_term.self_ty() != param + && pred.term.as_type() == Some(param) + }) + } + /// `serde_json::Value`, if it exports as a foreign object. fn json(&self) -> Option> { let tcx = self.tcx; @@ -3528,7 +3743,12 @@ impl<'tcx> Collector<'tcx> { /// The `Item` that `clauses` bind `param`'s `IntoIterator` to, if it names no type /// parameter, which a `Vec` of it then iterates as. - fn items(&self, clauses: &[ty::Unnormalized<'tcx, ty::Clause<'tcx>>], param: Ty<'tcx>) -> Option> { + fn items( + &self, + clauses: &[ty::Unnormalized<'tcx, ty::Clause<'tcx>>], + param: Ty<'tcx>, + iterator: rustc_span::Symbol, + ) -> Option> { let tcx = self.tcx; (clauses.iter()) .filter_map(|clause| clause.skip_norm_wip().as_projection_clause()) @@ -3537,7 +3757,7 @@ impl<'tcx> Collector<'tcx> { let term = pred.projection_term; let item = term.expect_projection_def_id(); term.self_ty() == param - && tcx.is_diagnostic_item(sym::IntoIterator, tcx.parent(item)) + && tcx.is_diagnostic_item(iterator, tcx.parent(item)) && tcx.item_name(item) == sym::Item }) .and_then(|pred| pred.term.as_type()) @@ -3726,13 +3946,16 @@ impl<'tcx> Collector<'tcx> { // A lifetime bound, such as `'static`, which a reference to a value C passes for the // call cannot meet, though `at` holds modulo regions. let outlives = must_outlive(&self.implied(def_id, base), param); + // An array's items are owned, as C lends nothing inside one. + let iterated = self.iterated(def_id, param); + let owned = outlives || iterated; let mut found: Vec> = Vec::new(); for ty in self.implementors(def_id, param) { - if outlives && ty.is_ref() { + if owned && ty.is_ref() { continue; } // An implementation for `&X` is taken as it is: C passes no reference to one. - let borrowed = (!ty.is_ref() && !outlives).then(|| Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty)); + let borrowed = (!ty.is_ref() && !owned).then(|| Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty)); let ty = match borrowed.filter(|&borrowed| at(borrowed).is_some()) { Some(borrowed) => borrowed, None if at(ty).is_some() => ty, @@ -3754,7 +3977,7 @@ impl<'tcx> Collector<'tcx> { .filter_map(exported) .any(|(_, args)| args.iter().any(|arg| arg.walk().any(|a| a == param.into()))); for site in self.instances.iter().filter(|_| argument) { - for candidate in site.args.types() { + for candidate in site.args.types().filter(|ty| !(iterated && ty.is_ref())) { let erased = tcx.erase_and_anonymize_regions(candidate); if found .iter() @@ -4110,6 +4333,15 @@ impl<'tcx> Collector<'tcx> { } /// `Vec`. + /// `std::vec::IntoIter`, an iterator C passes as the array of its items. + fn vec_iter_of(&self, item: Ty<'tcx>) -> Option> { + let tcx = self.tcx; + let ty::Adt(_, args) = self.vec_of(item)?.kind() else { + return None; + }; + Some(Ty::new_adt(tcx, tcx.adt_def(self.vec_iter?), *args)) + } + fn vec_of(&self, item: Ty<'tcx>) -> Option> { let tcx = self.tcx; let vec = tcx.get_diagnostic_item(sym::Vec)?; @@ -4387,12 +4619,13 @@ impl<'tcx> Collector<'tcx> { let mut refused = Vec::new(); let mut interned = Vec::new(); for &(region, n, input) in &lent { - // A string lives as long as the program once interned, which a binding passes - // as it passes any other. + // A string or bytes live as long as the program once interned, which a binding + // passes as it passes any other. Shared and never freed, the copy is as good as + // the caller's: equal contents differ only by address. if statics.contains(®ion) && let ty::Ref(r, inner, ty::Mutability::Not) = input.kind() && *r == region - && inner.is_str() + && (inner.is_str() || matches!(inner.kind(), ty::Slice(elem) if *elem == tcx.types.u8)) { interned.push(n); continue; @@ -4507,7 +4740,11 @@ impl<'tcx> Collector<'tcx> { let mut lent = Vec::new(); for ty in ty.walk().filter_map(|arg| arg.as_type()) { match ty.kind() { + // Another crate's `&'static dyn Trait`, which a handle holds. + ty::Ref(region, ..) if self.opaque_value(ty).is_some() => held.push(*region), ty::Ref(region, ..) => lent.push(*region), + // A trait object a handle holds holds its own lifetime, as `dyn Trait + 'a` does. + ty::Dynamic(_, region) if self.held_trait(ty).is_some() => held.push(*region), // An object, an opaque value, or another crate's value an opaque handle holds, holds // what its lifetime parameters name. ty::Adt(adt, args) @@ -4624,6 +4861,8 @@ impl<'tcx> Collector<'tcx> { fn holds_handle(&self, ty: Ty<'tcx>) -> bool { let tcx = self.tcx; ty.walk().filter_map(|arg| arg.as_type()).any(|ty| match ty.kind() { + // A trait object's handle, named by its trait rather than an ADT. + _ if self.is_opaque(ty) => true, ty::Adt(adt, args) => { // An opaque handle is never copied, even of a `Copy` value: lifting takes it. A // type [`FOREIGN`] maps by its role is an object. @@ -4883,6 +5122,25 @@ impl<'tcx> Collector<'tcx> { ty::Float(ty::FloatTy::F64) => Type::F64, ty::Uint(ty::UintTy::U128) => Type::U128, ty::Int(_) | ty::Uint(_) => Type::Int(int(ty).ok_or_else(|| why("128-bit integer", ty.to_string()))?), + // Another crate's `&'static dyn Trait`, held by value. + ty::Ref(..) + if let Some(did) = self.opaque_value(ty) + && let Some(&(_, i)) = self.foreign.iter().find(|&&(other, _)| other == did) => + { + if self.both.contains(&did) { + return Err(why(BOTH, tcx.def_path_str(did))); + } + if self.orphans.contains(&Key { + def_id: did, + args: None, + }) { + return Err(why("type C never holds", tcx.def_path_str(did))); + } + match pos { + Pos::Field => return Err(why("object in a value", tcx.def_path_str(did))), + _ => Type::Object(i), + } + } ty::Ref(_, inner, m) => { let inner_ty = match inner.kind() { ty::Str => Type::Str, @@ -4944,6 +5202,16 @@ impl<'tcx> Collector<'tcx> { // another crate's value, which a handle holds only erased and by value. (Type::Object(_), Pos::Return, Mutability::Not) if self.lending.take() && self.opaque_value(*inner).is_none() => {} + // A borrowed `Option` of one is lent as `Some` of a borrow of it, so C holds the + // handle the bare borrow would be. + (Type::Option(object), Pos::Return, Mutability::Not) + if matches!(**object, Type::Object(_)) + && let ty::Adt(_, args) = inner.kind() + && self.opaque_value(args.type_at(0)).is_none() + && self.lending.take() => + { + return Ok(Type::Option(Box::new(Type::Ref(Mutability::Not, object.clone())))); + } // A slice's clone is a `Vec` of its elements' clones. (_, Pos::Return | Pos::Returned, _) if !self.is_clone(match inner.kind() { @@ -5026,6 +5294,28 @@ impl<'tcx> Collector<'tcx> { Type::List(c, Box::new(inner)) } else if Some(did) == self.bytes { Type::Bytes + } else if Some(did) == self.vec_iter + && pos == Pos::Param + && tcx.lang_items().global_alloc_ty() == args.type_at(1).ty_adt_def().map(|adt| adt.did()) + { + // An `impl Iterator` parameter's, which C passes as the array of its items. A + // borrowed string or bytes borrow what C lends for the call. + let elem = args.type_at(0); + match elem.kind() { + ty::Ref(_, inner, ty::Mutability::Not) if inner.is_str() => { + Type::List(Collection::IterRef, Box::new(Type::String)) + } + ty::Ref(_, inner, ty::Mutability::Not) if matches!(inner.kind(), ty::Slice(byte) if *byte == tcx.types.u8) => { + Type::List(Collection::IterRef, Box::new(Type::Vec)) + } + _ => { + let inner = self.ty(elem, pos.inner())?; + if borrows(&inner) { + return Err(why("iterator of references", elem.to_string())); + } + Type::List(Collection::Iter, Box::new(inner)) + } + } } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("Duration"), did) { Type::Duration } else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("NonZero"), did) { @@ -5116,7 +5406,8 @@ impl<'tcx> Collector<'tcx> { } else if tcx.is_diagnostic_item(sym::Arc, did) { let inner = args.type_at(0); match inner.kind() { - ty::Dynamic(preds, ..) => { + // Another crate's trait is held as its other types are, below. + ty::Dynamic(preds, ..) if self.opaque_arc(ty).is_none() => { return self.dynamic(preds.principal_def_id(), Dyn::Arc, inner, pos); } // Held erased, as a handle with none of its API, which Rust takes back. @@ -5232,6 +5523,15 @@ impl<'tcx> Collector<'tcx> { Err(_) => return Err(why("array too long", ty.to_string())), } } + // Returned as the array of its elements, as a returned slice is: C has no fixed-size + // array of a value that is not plain bytes. + ty::Array(elem, len) if matches!(pos, Pos::Return | Pos::Returned) => { + let n = len + .try_to_target_usize(tcx) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| why("array of unknown length", ty.to_string()))?; + Type::List(Collection::Array(n), Box::new(self.ty(*elem, Pos::Returned)?)) + } ty::Array(..) => return Err(why("array of an element other than u8", ty.to_string())), ty::Slice(_) | ty::Str => return Err(why("unsized type", ty.to_string())), ty::Dynamic(..) => return Err(why("trait object", ty.to_string())), @@ -5448,6 +5748,16 @@ fn lends_inside(ty: &Type) -> bool { } } +/// Whether a return of `ty` is a borrowed object, or `Some` of one, which its receiver's +/// handle may lend. +fn lent(ty: &Type) -> bool { + let borrowed = |ty: &Type| matches!(ty, Type::Ref(Mutability::Not, inner) if matches!(**inner, Type::Object(_))); + match ty { + Type::Option(inner) => borrowed(inner), + ty => borrowed(ty), + } +} + /// Whether a callback can return `ty`: a value with no memory to own. fn foreign_return(ty: &Type) -> bool { matches!( diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 4afb15ec9..d2e02a13c 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -82,6 +82,8 @@ fn collection(c: Collection) -> String { Collection::Vec => "::std::vec::Vec".to_string(), Collection::Box => "::std::boxed::Box".to_string(), Collection::Slice => unreachable!("a slice is spelled `[T]`"), + Collection::Array(_) => unreachable!("an array is spelled `[T; N]`"), + Collection::Iter | Collection::IterRef => "::std::vec::IntoIter".to_string(), Collection::BTreeSet => "::std::collections::BTreeSet".to_string(), Collection::BTreeMap => "::std::collections::BTreeMap".to_string(), Collection::JsonMap => format!("::{}::Map", foreign("serde_json")), @@ -629,6 +631,9 @@ impl Gen<'_> { } (Collection::Box, _) => format!("{}<[{}]>", collection(*c), self.rust(inner)), (Collection::Slice, _) => format!("[{}]", self.rust(inner)), + (Collection::Array(n), _) => format!("[{}; {n}]", self.rust(inner)), + (Collection::IterRef, Type::String) => format!("{}<&str>", collection(*c)), + (Collection::IterRef, _) => format!("{}<&[u8]>", collection(*c)), _ => format!("{}<{}>", collection(*c), self.rust(inner)), }, Type::Option(inner) => format!("Option<{}>", self.rust(inner)), @@ -687,6 +692,12 @@ impl Gen<'_> { _ => "::std::vec::Vec::<_>", } ), + // An iterator iterates the `Vec` of its items. + Type::List(Collection::Iter, inner) => format!( + "::std::iter::IntoIterator::into_iter({})", + self.lift(&Type::List(Collection::Vec, inner.clone()), e, take) + ), + Type::List(Collection::IterRef, _) => unreachable!("an iterator of borrows is lent by `arg`"), Type::List(c, inner) => format!( "unsafe {{ {e}.items(w) }}.iter().map(|c| {}).collect::<{}>()", // An array's items are behind its pointer, so only read. @@ -696,6 +707,9 @@ impl Gen<'_> { Collection::Box => format!("{}<[_]>", collection(*c)), Collection::Vec | Collection::Slice => format!("{}<_>", collection(Collection::Vec)), Collection::BTreeSet => format!("{}<_>", collection(*c)), + Collection::Array(_) | Collection::Iter | Collection::IterRef => { + unreachable!("{c:?} is lifted apart") + } } ), // A foreign enum's option converts into its filter, as `tracing::LevelFilter`. @@ -867,7 +881,7 @@ impl Gen<'_> { Type::Array(n) => format!("{} {{ items: {e} }}", self.abi.array(*n)), Type::SocketAddr(_) => format!("rt::SocketAddr::lower(::std::net::SocketAddr::from({e}))"), // A block hands over its own allocation. - Type::List(Collection::Box, _) if ty.block().is_some() => { + Type::List(Collection::Box | Collection::Array(_), _) if ty.block().is_some() => { format!("rt::List::owned(::std::vec::Vec::from({e}))") } Type::List(..) if ty.block().is_some() => format!("rt::List::owned({e})"), @@ -1603,6 +1617,14 @@ impl Gen<'_> { (format!("{binding} {local} = {};", self.lift(inner, c, "true")), pass) } }, + // An iterator of borrowed strings or bytes, each lent from its owned copy for the call. + Type::List(Collection::IterRef, item) => ( + format!( + "let {local}_items = {};\n\tlet {local} = {local}_items.iter().map(|v| &v[..]).collect::<::std::vec::Vec<_>>();", + self.lift(&Type::List(Collection::Vec, item.clone()), c, "true") + ), + format!("::std::iter::IntoIterator::into_iter({local})"), + ), // `Some` of a borrow, lent as the borrow alone is: a null handle or buffer is `None`. Type::Option(opt) if let Type::Ref(m, inner) = &**opt => match (&**inner, future) { (Type::Object(i), _) => { @@ -1828,6 +1850,10 @@ impl Gen<'_> { pass, ) } + _ if param.interned && *param.ty.base() == Type::Slice => ( + format!("let a{n} = rt::intern_bytes(unsafe {{ p{n}.hold(w) }}.bytes());"), + format!("a{n}"), + ), _ if param.interned => ( format!("let a{n} = rt::intern(unsafe {{ p{n}.hold(w) }}.str(w));"), format!("a{n}"), diff --git a/ffi/src/go.rs b/ffi/src/go.rs index b8bb49d1e..1a804397e 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2247,6 +2247,11 @@ impl<'a> Gen<'a> { } } }; + // A positional field's accessor, `0Get`, is `V0Get`, as its field is `V0`. + let member = match member.starts_with(|c: char| c.is_ascii_digit()) { + true => format!("V{member}"), + false => member, + }; let classes = self.classes.get(self.pkg); let member = match (receiver.is_some(), member.as_str()) { // What every object or value of the type already has. diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index b3bebcfdf..659f525a8 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -476,8 +476,9 @@ pub enum Receiver { pub struct Param { pub name: String, pub ty: Type, - /// Whether it is a `&str` that must be `'static`, which the glue interns: it leaks each - /// distinct string once and lends that copy to every later call with equal content. + /// Whether it is a `&str` or `&[u8]` that must be `'static`, which the glue interns: it + /// leaks each distinct value once and lends that copy to every later call with equal + /// content. pub interned: bool, } @@ -611,6 +612,13 @@ pub enum Collection { BTreeMap, /// `serde_json::Map`, of `String` keys and `serde_json::Value`s. JsonMap, + /// `[T; N]` of any `T` but `u8`, which is [`Type::Array`]: only returned. + Array(usize), + /// `std::vec::IntoIter`, which an `impl Iterator` parameter takes: only a parameter. + Iter, + /// `std::vec::IntoIter<&str>` or `std::vec::IntoIter<&[u8]>`, of a [`Type::String`] or + /// [`Type::Vec`], each lent for the call: only a parameter. + IterRef, } /// The addresses a socket address type holds. @@ -716,11 +724,13 @@ impl Type { /// one array type holds them on every target. pub fn block(&self) -> Option<&Type> { match self { - Type::List(Collection::Vec | Collection::Slice | Collection::Box, inner) => match &**inner { - Type::Int(Int::Usize | Int::Isize) => None, - Type::Int(_) | Type::F32 | Type::F64 => Some(inner), - _ => None, - }, + Type::List(Collection::Vec | Collection::Slice | Collection::Box | Collection::Array(_), inner) => { + match &**inner { + Type::Int(Int::Usize | Int::Isize) => None, + Type::Int(_) | Type::F32 | Type::F64 => Some(inner), + _ => None, + } + } _ => None, } } diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 5010af5fb..392d94fe8 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -2000,6 +2000,11 @@ fn kw(name: &str) -> String { /// A member's Python name: its snake-case name, with `_` appended if a keyword, and until /// it is none of `reserved`, such as one Python gives every such class. fn member(snake: &str, reserved: &[&str]) -> String { + // A positional field's accessor, `0_get`, is `_0_get`, as its field is `_0`. + let digit = snake + .starts_with(|c: char| c.is_ascii_digit()) + .then(|| format!("_{snake}")); + let snake = digit.as_deref().unwrap_or(snake); if !reserved.contains(&snake) { return kw(snake); } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 3cebce763..3361f0e93 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1549,6 +1549,41 @@ static int script(void) { printf("%llu\n", (unsigned long long)api_chain_len((api_vec_tls_Cert){.ptr = chain, .len = 2})); api_tls_Cert_free(chain[0]); api_tls_Cert_free(chain[1]); + /* Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. */ + api_tls_Resolver *resolver = api_resolver(str("r1")); + print("resolver ", api_resolved(resolver), "\n"); + api_tls_Resolver_free(resolver); + api_Codecs *codecs = api_Codecs_new(); + printf("codecs %u\n", api_Codecs_ids(codecs)); + api_vec_tls_Codec listed = api_Codecs_list_get(codecs); + api_tls_Codec *codecs_reversed[2] = {listed.ptr[1], listed.ptr[0]}; + api_Codecs_list_set(codecs, (api_vec_tls_Codec){.ptr = codecs_reversed, .len = 2}); + /* The setter took each handle's value: the array, and the handles, are still ours to free. */ + api_vec_tls_Codec_free(listed); + printf("codecs reversed %u\n", api_Codecs_ids(codecs)); + api_Codecs_free(codecs); + /* A standard library value no type maps, in a handle. */ + api_std_io_Error *failure = api_failure(str("boom")); + print("failure ", api_failure_message(failure), " "); + print("", api_failure_kind(failure), "\n"); + api_std_io_Error_free(failure); + /* Iterators, passed as the arrays of their items. */ + const uint32_t summed_items[] = {1, 2, 3}; + printf("sum_all %u\n", api_sum_all((api_vec_u32){.ptr = summed_items, .len = 3})); + /* Each counter moves in, leaving its handle only to free. */ + api_Counter *weighed = api_Counter_new(str("w"), 3); + printf("weigh_all %llu\n", (unsigned long long)api_weigh_all_Counter((api_vec_Counter){.ptr = &weighed, .len = 1})); + api_Counter_free(weighed); + const api_buf alpns[] = {str("h3"), str("moq-00")}; + printf("offered_len %zu\n", api_offered_len((api_vec_bytes){.ptr = alpns, .len = 2})); + const api_buf joined_words[] = {str("a"), str("b"), str("c")}; + print("join_words ", api_join_words((api_vec_string){.ptr = joined_words, .len = 3}), "\n"); + /* Bytes that must be `'static`, interned. */ + for (int i = 0; i < 2; i++) { + api_Der *der = api_Der_from_slice(str("der")); + print(i == 0 ? "der " : "der again ", api_Der_bytes(der), "\n"); + api_Der_free(der); + } /* Another crate's type only signatures name, exported by its path there, and its error, * which crosses as its message. */ api_tls_Session *session; @@ -1582,6 +1617,16 @@ static int script(void) { api_Meter_add(last, 4); printf("field lent %llu\n", (unsigned long long)api_Meter_add(last, 1)); api_Meter_free(last); + /* An optional field that is not Clone, lent as `Some` of a handle. */ + api_Meter *spare = api_Meters_spare_get(lender); + printf("spare %s\n", spare != NULL ? "true" : "false"); + api_Meter *fresh = api_Meter_default(); + api_Meters_spare_set(lender, fresh); + api_Meter_free(fresh); + spare = api_Meters_spare_get(lender); + api_Meter_add(spare, 5); + printf("spare lent %llu\n", (unsigned long long)api_Meter_add(spare, 1)); + api_Meter_free(spare); api_Meters_free(lender); /* One lent from a handle that is not Sync, on one thread at a time. */ api_Tallies *tallies = api_Tallies_new(); @@ -1783,6 +1828,19 @@ static int script(void) { } printf("]\n"); api_vec_string_free(greetings); + api_vec_Shape shapes_both = api_Shape_BOTH(); + printf("both ["); + for (size_t i = 0; i < shapes_both.len; i++) { + print(i == 0 ? "" : ", ", api_Shape_debug(&shapes_both.ptr[i]), ""); + } + api_vec_Shape_free(shapes_both); + api_vec_u32 primes = api_PRIMES(); + printf("] primes ["); + for (size_t i = 0; i < primes.len; i++) { + printf("%s%u", i == 0 ? "" : ", ", primes.ptr[i]); + } + printf("]\n"); + api_vec_u32_free(primes); api_Point trail_points[] = {{.x = 1, .y = 2}, {.x = 3, .y = 4}}; api_buf trail_names[] = {str("a"), str("b")}; api_Trail *trail = diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 42af6bbc1..e209729da 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -983,6 +983,30 @@ int script() { chain.push_back(api::certify("a")); chain.push_back(api::certify("bc")); std::printf("%llu\n", ull(api::chain_len(std::move(chain)))); + // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. + print("resolver ", api::resolved(api::resolver("r1")), "\n"); + auto codecs = api::Codecs::new_(); + std::printf("codecs %u\n", unsigned(codecs.ids())); + auto listed = codecs.list_get(); + std::vector reversed; + reversed.push_back(std::move(listed[1])); + reversed.push_back(std::move(listed[0])); + codecs.list_set(std::move(reversed)); + std::printf("codecs reversed %u\n", unsigned(codecs.ids())); + // A standard library value no type maps, in a handle. + auto failure = api::failure("boom"); + print("failure ", api::failure_message(failure), " "); + print("", api::failure_kind(std::move(failure)), "\n"); + // Iterators, passed as the arrays of their items. + std::printf("sum_all %u\n", unsigned(api::sum_all({1, 2, 3}))); + std::vector weighed; + weighed.push_back(api::Counter::new_("w", 3)); + std::printf("weigh_all %llu\n", ull(api::weigh_all_Counter(std::move(weighed)))); + std::printf("offered_len %llu\n", ull(api::offered_len({"h3", "moq-00"}))); + print("join_words ", api::join_words({"a", "b", "c"}), "\n"); + // Bytes that must be `'static`, interned. + print("der ", api::Der::from_slice("der").bytes(), "\n"); + print("der again ", api::Der::from_slice("der").bytes(), "\n"); auto session = api::resume("h3", 60); print("resume ", session.value().alpn(), " "); std::printf("%u\n", unsigned(session.value().lifetime().seconds)); @@ -997,6 +1021,12 @@ int script() { auto last = meters.last_get(); last.add(4); std::printf("field lent %llu\n", ull(last.add(1))); + // An optional field that is not Clone, lent as `Some` of a handle. + std::printf("spare %s\n", meters.spare_get() ? "true" : "false"); + meters.spare_set(api::Meter::default_()); + auto spare = meters.spare_get(); + spare->add(5); + std::printf("spare lent %llu\n", ull(spare->add(1))); auto tallies = api::Tallies::new_(); tallies.first().bump(); std::printf("tallied %u\n", tallies.first().bump()); @@ -1144,6 +1174,17 @@ int script() { std::printf("] greetings "); print_strings(api::GREETINGS()); std::printf("\n"); + auto both = api::Shape_BOTH(); + std::printf("both ["); + for (std::size_t i = 0; i < both.size(); i++) { + print(i == 0 ? "" : ", ", api::Shape_debug(both[i]), ""); + } + std::printf("] primes ["); + auto primes = api::PRIMES(); + for (std::size_t i = 0; i < primes.size(); i++) { + std::printf("%s%u", i == 0 ? "" : ", ", unsigned(primes[i])); + } + std::printf("]\n"); api::Trail trail = api::Trail::new_({api::Point{1, 2}, api::Point{3, 4}}, {"a", "b"}); auto points = trail.points(); std::printf("trail ["); diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 5117369a9..884bdf35a 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -616,6 +616,27 @@ Future script() async { final certLen = api.certLen(cert); print('cert $certLen ${text(api.certDer(cert))} ${api.chainLen([api.certify(utf8.encode('a')), api.certify(utf8.encode('bc'))])}'); config.close(); + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print('resolver ${api.resolved(api.resolver('r1'))}'); + final codecs = api.Codecs(); + print('codecs ${codecs.ids()}'); + codecs.listSet(codecs.listGet.reversed.toList()); + print('codecs reversed ${codecs.ids()}'); + codecs.close(); + // A standard library value no type maps, in a handle. + final failure = api.failure('boom'); + print('failure ${api.failureMessage(failure)} ${api.failureKind(failure)}'); + // Iterators, passed as the arrays of their items. + print('sum_all ${api.sumAll([1, 2, 3])}'); + print('weigh_all ${api.weighAllCounter([api.Counter('w', 3)])}'); + print('offered_len ${api.offeredLen([utf8.encode('h3'), utf8.encode('moq-00')])}'); + print('join_words ${api.joinWords(['a', 'b', 'c'])}'); + // Bytes that must be `'static`, interned. + for (final label in ['der', 'der again']) { + final der = api.Der.fromSlice(utf8.encode('der')); + print('$label ${text(der.bytes())}'); + der.close(); + } final session = api.resume('h3', 60); print('resume ${session.alpn()} ${session.lifetime().seconds}'); session.close(); @@ -635,6 +656,13 @@ Future script() async { lastMeter.add(4); print('field lent ${lastMeter.add(1)}'); lastMeter.close(); + // An optional field that is not Clone, lent as `Some` of a handle. + print('spare ${meters.spareGet != null}'); + meters.spareSet(api.Meter.default_()); + final spare = meters.spareGet!; + spare.add(5); + print('spare lent ${spare.add(1)}'); + spare.close(); meters.close(); final tallies = api.Tallies(); tallies.first().bump(); @@ -711,6 +739,7 @@ Future script() async { _ => throw ArgumentError(v), }).join(', ')}]'; print('shapes ${debugs(api.Shape.ALL)} greetings ${quoted(api.GREETINGS)}'); + print('both ${debugs(api.Shape.BOTH)} primes ${api.PRIMES}'); final trail = api.Trail([const api.Point(x: 1, y: 2), const api.Point(x: 3, y: 4)], ['a', 'b']); print('trail ${debugs(trail.points())} ${debugs(trail.labels())}'); // Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 612207184..4ed037925 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -732,6 +732,28 @@ func script() { cert := api.Certify(rt.NewBytes([]byte("der"))) certLen := must(api.CertLen(cert)) fmt.Printf("cert %d %s %d\n", certLen, must(api.CertDer(cert)).Copy(), must(api.ChainLen([]*tls.Cert{api.Certify(rt.NewBytes([]byte("a"))), api.Certify(rt.NewBytes([]byte("bc")))}))) + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + fmt.Printf("resolver %s\n", must(api.Resolved(api.Resolver("r1")))) + codecs := api.NewCodecs() + fmt.Printf("codecs %d\n", must(codecs.Ids())) + listed := must(codecs.ListGet()) + ok(codecs.ListSet([]*tls.Codec{listed[1], listed[0]})) + fmt.Printf("codecs reversed %d\n", must(codecs.Ids())) + codecs.Close() + // A standard library value no type maps, in a handle. + failure := api.Failure("boom") + fmt.Printf("failure %s %s\n", must(api.FailureMessage(failure)), must(api.FailureKind(failure))) + // Iterators, passed as the arrays of their items. + fmt.Printf("sum_all %d\n", api.SumAll([]uint32{1, 2, 3})) + fmt.Printf("weigh_all %d\n", must(api.WeighAllCounter([]*api.Counter{api.NewCounter("w", 3)}))) + fmt.Printf("offered_len %d\n", api.OfferedLen([]rt.Bytes{rt.NewBytes([]byte("h3")), rt.NewBytes([]byte("moq-00"))})) + fmt.Printf("join_words %s\n", api.JoinWords([]string{"a", "b", "c"})) + // Bytes that must be `'static`, interned. + for _, label := range []string{"der", "der again"} { + der := api.DerFromSlice(rt.NewBytes([]byte("der"))) + fmt.Printf("%s %s\n", label, must(der.Bytes()).Copy()) + der.Close() + } session := must(api.Resume("h3", 60)) fmt.Printf("resume %s %d\n", must(session.Alpn()), must(session.Lifetime()).Seconds) session.Close() @@ -747,6 +769,12 @@ func script() { lastMeter := must(meters.LastGet()) _ = must(lastMeter.Add(4)) fmt.Printf("field lent %d\n", must(lastMeter.Add(1))) + // An optional field that is not Clone, lent as `Some` of a handle. + fmt.Printf("spare %t\n", must(meters.SpareGet()) != nil) + ok(meters.SpareSet(api.MeterDefault())) + spare := must(meters.SpareGet()) + _ = must(spare.Add(5)) + fmt.Printf("spare lent %d\n", must(spare.Add(1))) tallies := api.NewTallies() _ = must(must(tallies.First()).Bump()) fmt.Printf("tallied %d\n", must(must(tallies.First()).Bump())) @@ -838,6 +866,7 @@ func script() { // Slices, passed in and returned as clones, and the socket address of each family. fmt.Printf("shapes %s greetings %s\n", list(api.ShapeALL(), func(s api.Shape) string { return shapes[s] }), list(api.GREETINGS(), quoted)) + fmt.Printf("both %s primes %s\n", list(api.ShapeBOTH(), func(s api.Shape) string { return shapes[s] }), list(api.PRIMES(), func(n uint32) string { return fmt.Sprint(n) })) trail := api.NewTrail([]api.Point{{X: 1, Y: 2}, {X: 3, Y: 4}}, []string{"a", "b"}) point := func(p api.Point) string { return p.GoString() } labeled := func(l api.Label) string { return l.GoString() } diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 0edc62359..22150ebbc 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -536,6 +536,24 @@ fun script() { val cert = certify(Bytes("der".encodeToByteArray())) val certLen = certLen(cert) println("cert $certLen ${certDer(cert).text()} ${chainLen(listOf(certify(Bytes("a".encodeToByteArray())), certify(Bytes("bc".encodeToByteArray()))))}") + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + println("resolver ${resolved(resolver("r1"))}") + Codecs.new().use { codecs -> + println("codecs ${codecs.ids()}") + codecs.listSet(codecs.listGet.reversed()) + println("codecs reversed ${codecs.ids()}") + } + // A standard library value no type maps, in a handle. + val failure = failure("boom") + println("failure ${failureMessage(failure)} ${failureKind(failure)}") + // Iterators, passed as the arrays of their items. + println("sum_all ${sumAll(listOf(1u, 2u, 3u))}") + println("weigh_all ${weighAllCounter(listOf(Counter.new("w", 3u)))}") + println("offered_len ${offeredLen(listOf(Bytes("h3".encodeToByteArray()), Bytes("moq-00".encodeToByteArray())))}") + println("join_words ${joinWords(listOf("a", "b", "c"))}") + // Bytes that must be `'static`, interned. + Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der ${it.bytes().text()}") } + Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der again ${it.bytes().text()}") } resume("h3", 60u).use { session -> println("resume ${session.alpn()} ${session.lifetime().seconds}") } try { resume("", 60u) @@ -553,6 +571,13 @@ fun script() { last.add(4uL) println("field lent ${last.add(1uL)}") } + // An optional field that is not Clone, lent as `Some` of a handle. + println("spare ${meters.spareGet != null}") + meters.spareSet(Meter.default()) + meters.spareGet!!.use { spare -> + spare.add(5uL) + println("spare lent ${spare.add(1uL)}") + } } Tallies.new().use { tallies -> tallies.first().use { it.bump() } @@ -625,6 +650,7 @@ fun script() { // Slices, passed in and returned as clones, and the socket address of each family. println("shapes ${Shape.ALL.joinToString(", ", "[", "]") { it.debug() }} greetings ${GREETINGS.joinToString(", ", "[", "]") { "\"$it\"" }}") + println("both ${Shape.BOTH.joinToString(", ", "[", "]") { it.debug() }} primes ${PRIMES.joinToString(", ", "[", "]")}") Trail.new(listOf(Point(1, 2), Point(3, 4)), listOf("a", "b")).use { trail -> println("trail ${trail.points().joinToString(", ", "[", "]") { it.debug() }} ${trail.labels().joinToString(", ", "[", "]") { it.debug() }}") // Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 9dddc1058..9e9f1d092 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -623,6 +623,23 @@ async def polls(): print(f"secure {api.alpn_lent(config)} {api.alpn(config.clone())}") cert = api.certify(b"der") print(f"cert {api.cert_len(cert)} {text(api.cert_der(cert))} {api.chain_len([api.certify(b'a'), api.certify(b'bc')])}") + # Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print(f"resolver {api.resolved(api.resolver('r1'))}") + codecs = api.Codecs.new() + print(f"codecs {codecs.ids()}") + codecs.list_set(list(reversed(codecs.list_get))) + print(f"codecs reversed {codecs.ids()}") + # A standard library value no type maps, in a handle. + failure = api.failure("boom") + print(f"failure {api.failure_message(failure)} {api.failure_kind(failure)}") + # Iterators, passed as the arrays of their items. + print(f"sum_all {api.sum_all(iter([1, 2, 3]))}") + print(f"weigh_all {api.weigh_all_counter([api.Counter.new('w', 3)])}") + print(f"offered_len {api.offered_len([b'h3', b'moq-00'])}") + print(f"join_words {api.join_words(['a', 'b', 'c'])}") + # Bytes that must be `'static`, interned. + print(f"der {text(api.Der.from_slice(b'der').bytes())}") + print(f"der again {text(api.Der.from_slice(b'der').bytes())}") session = api.resume("h3", 60) print(f"resume {session.alpn()} {session.lifetime().seconds}") try: @@ -638,6 +655,13 @@ async def polls(): lent_last = meters.last_get lent_last.add(4) print(f"field lent {lent_last.add(1)}") + # An optional field that is not Clone, lent as `Some` of a handle. + print(f"spare {str(meters.spare_get is not None).lower()}") + meters.spare_set(api.Meter.default()) + spare = meters.spare_get + assert spare is not None + spare.add(5) + print(f"spare lent {spare.add(1)}") tallies = api.Tallies.new() tallies.first().bump() print(f"tallied {tallies.first().bump()}") @@ -700,6 +724,7 @@ async def polls(): # Slices, passed in and returned as clones, and the socket address of each family. print(f"shapes {debugs(api.Shape.ALL)} greetings {quoted(api.GREETINGS)}") + print(f"both {debugs(api.Shape.BOTH)} primes {list(api.PRIMES)}") trail = api.Trail.new([api.Point(1, 2), api.Point(3, 4)], ["a", "b"]) print(f"trail {debugs(trail.points())} {debugs(trail.labels())}") # Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index f45068437..e4e3bb5af 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -711,6 +711,30 @@ func script() { chain.append(certify(Bytes("a".utf8))) chain.append(certify(Bytes("bc".utf8))) print("cert \(certLength) \(der) \(chainLen(chain))") + // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. + print("resolver \(resolved(resolver("r1")))") + var codecs = Codecs.new() + print("codecs \(codecs.ids())") + var listed = codecs.listGet + var reversed = UniqueArray() + reversed.append(listed.remove(at: 1)) + reversed.append(listed.remove(at: 0)) + codecs.listSet(reversed) + print("codecs reversed \(codecs.ids())") + // A standard library value no type maps, in a handle. + let failed = failure("boom") + let message = failureMessage(failed) + print("failure \(message) \(failureKind(failed))") + // Iterators, passed as the arrays of their items. + print("sum_all \(sumAll([1, 2, 3]))") + var weighed = UniqueArray() + weighed.append(Counter.new("w", 3)) + print("weigh_all \(weighAllCounter(weighed))") + print("offered_len \(offeredLen([Bytes("h3".utf8), Bytes("moq-00".utf8)]))") + print("join_words \(joinWords(["a", "b", "c"]))") + // Bytes that must be `'static`, interned. + print("der \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") + print("der again \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") let session = try! resume("h3", 60) print("resume \(session.alpn()) \(session.lifetime().seconds)") do { @@ -729,6 +753,17 @@ func script() { let last = meters.lastGet _ = last.add(4) print("field lent \(last.add(1))") + // An optional field that is not Clone, lent as `Some` of a handle. + var hasSpare = false + if let _ = meters.spareGet { + hasSpare = true + } + print("spare \(hasSpare)") + meters.spareSet(Meter.default()) + if let spare = meters.spareGet { + _ = spare.add(5) + print("spare lent \(spare.add(1))") + } let tallies = Tallies.new() _ = tallies.first().bump() print("tallied \(tallies.first().bump())") @@ -790,6 +825,7 @@ func script() { // Slices, passed in and returned as clones, and the socket address of each family. print("shapes \(Shape.ALL) greetings \(GREETINGS)") + print("both \(Shape.BOTH) primes \(PRIMES)") var trail = Trail.new([Point(x: 1, y: 2), Point(x: 3, y: 4)], ["a", "b"]) print("trail \(trail.points()) \(trail.labels())") // Returned iterators, each collected at the call: drained labels are gone after. diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 877cae2c3..1dac08c77 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2023,6 +2023,8 @@ fn relative_target() { "- `handover`: type C never holds `tls::held::Handoff`", "- `Unnamed`: generic type no export instantiates", "- `blame`: type C never holds `tls::held::Invalid`", + // A type parameter only another crate's trait bounds, which no export implements. + "- `pump`: bound no type C holds meets `tls::held::Stream`", // An exclude that names what exports, by its generic or instance path or as a field, // even where a method of the field's name is refused. "## Excluded by the config, though it exports", diff --git a/quest/m1/ffi-export/not-send.md b/quest/m1/ffi-export/not-send.md index 4ccccf05e..c6153843c 100644 --- a/quest/m1/ffi-export/not-send.md +++ b/quest/m1/ffi-export/not-send.md @@ -6,7 +6,10 @@ thread that made it: a call, poll, or drop from another thread never runs Rust code on that value there. Three of moq's own are refused for it at moq `ffcb7cd9`: `clock::Entered`, `clock::Rng`, and `catalog::Guard` -([#675](https://github.com/kixel-ai/rust2/pull/675)). Proven per language by a fixture +([#675](https://github.com/kixel-ai/rust2/pull/675)). At moq's `main` (`a11a584`, measured on 2026-11-14 in +[#802](https://github.com/kixel-ai/rust2/pull/802)), moq-tokio's `server::Listener::accept_with` +is a fourth: its future borrows `&self` of a `Listener` that is not `Sync`, through a +`FuturesUnordered` of boxed futures that are not, so the future is not `Send`. Proven per language by a fixture type holding an `Rc`, called, awaited, and dropped from a second thread. ## Plan @@ -17,6 +20,8 @@ such object, which costs two thread handoffs a call even from a single-threaded such as Python's event loop; keeping the refusal, as the small-shapes quest had it. The maintainer: an assert is fine "where a language has no concept of something being thread local". +On 2026-11-14, at [#802](https://github.com/kixel-ai/rust2/pull/802)'s pick, the maintainer kept +`server::Listener::accept_with` in this quest: ✅ keep (rejected: drop). - The handle records its owner thread, and each call compares it: no atomics, so it costs less than a `Sync` type's borrow. The wrong thread diff --git a/quest/m1/ffi-refusals/README.md b/quest/m1/ffi-refusals/README.md index abd4153d9..15f9153be 100644 --- a/quest/m1/ffi-refusals/README.md +++ b/quest/m1/ffi-refusals/README.md @@ -79,7 +79,9 @@ Decided with the maintainer on 2026-11-12, in the quest audit: `NonZero`, which exports, the rest of the errors at moq's main (exported since by rules for another crate's value, a borrowing future of a function that is not `async`, and an object field that is not `Clone`), and - [what the excludes still hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md); + what the excludes still hide at moq's main, exported since but for + [`IpAddr`](/quest/m1/ffi-refusals/ip-addr.md) and `server::Listener::accept_with`, which + [not-send](/quest/m1/ffi-export/not-send.md) owns; `just ffi census` fails on an exclude that names what exports. The bump is then only the bump. The types refused for not being `Send` (`clock::Entered`, `clock::Rng`, `catalog::Guard`) clear with [not-send](/quest/m1/ffi-export/not-send.md). diff --git a/quest/m1/ffi-refusals/ip-addr.md b/quest/m1/ffi-refusals/ip-addr.md new file mode 100644 index 000000000..4237d86b0 --- /dev/null +++ b/quest/m1/ffi-refusals/ip-addr.md @@ -0,0 +1,29 @@ +# [S] IpAddr crosses by family + +## Goal + +`std::net::IpAddr`, `Ipv4Addr`, and `Ipv6Addr` export in every binding, as `SocketAddr` +already does: its IP's bytes and whether it is IPv6, with no port. moq-tokio's +`quic::demux::Datagram::local` is the one item at moq's `main` (`a11a584`, measured on +2026-11-14 in [#802](https://github.com/kixel-ai/rust2/pull/802)) refused for it, and the +census lists no `IpAddr` refusal there. + +## Plan + +Decided with the maintainer on 2026-11-13, in +[moq-excluded](https://github.com/kixel-ai/rust2/pull/802)'s Plan: ✅ `IpAddr` crosses as +`SocketAddr` already does, by family. #802 split it out, since it is a new IR type +through the glue and all seven generators, apart from that quest's collector rules. +The maintainer kept this quest on 2026-11-14, at #802's pick: ✅ keep (rejected: drop). + +- A new `_ip_addr` C struct of 16 bytes and an `is_v6` flag, `SocketAddr`'s + without the port, and each binding's own address type where it is exact, as each maps + `SocketAddr` today (Kotlin `InetAddress`, Python `ipaddress`, Swift, Go `netip.Addr`, + Dart `InternetAddress`, C++). Recommended: reuse each binding's `SocketAddr` mapping of + the IP for the address and drop the port, so one family check covers both. +- `Ipv4Addr` and `Ipv6Addr` cross as that struct too; one of the other family passed in + aborts, as `SocketAddrV4` does. +- Prove it in the api fixture's transcript in all seven languages, both families, in and + out. + +Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/moq-excluded.md b/quest/m1/ffi-refusals/moq-excluded.md deleted file mode 100644 index 1e3a4267b..000000000 --- a/quest/m1/ffi-refusals/moq-excluded.md +++ /dev/null @@ -1,58 +0,0 @@ -# [M] What the excludes hide at moq's main - -## Goal - -Each construct `just ffi census ` still refuses at moq's `main` behind an -exclude in `ffi/moq/ffi.toml` exports by a rule, or is left out as what C can never hold, -beyond `NonZero`, which exports, and the types -[not-send](/quest/m1/ffi-export/not-send.md) exports. Measured on 2026-11-13 at moq -`98e54e7`, with #721's reach of other crates' types and the rules for another crate's -value, a non-`async` function's borrowing future, and a lent object field in place: 23 -items beyond not-send's, 13 of them in crates #721 newly reaches. - -## Plan - -[The epic](/quest/m1/ffi-refusals/README.md)'s decisions apply: rust2 asks moq for no -source change, and what C can never hold is left out and listed. Measure again first. - -The maintainer kept this quest on 2026-11-13 and accepted each recommendation below as its plan. - -- `std::io::Error` taken by value (`accept::Failure::classify`, `accept::Health::failed`) - and `std::net::IpAddr` (`quic::demux::Datagram::local`). Decided: `IpAddr` crosses - as `SocketAddr` already does, by family; `io::Error` as an opaque handle, as another - crate's value now is, with the standard library no longer exempt. -- Trait objects: `quic::Controller`'s `Arc` - field and `tls::Serve::resolver`'s `Arc`. - Decided: an opaque handle to the `Arc`, as another crate's `Arc` already is. -- Generic parameters: `server::Request::within` (`impl Future`), - `websocket::Listener::with_protocols` (`impl IntoIterator>`), - `tcp::TlsAcceptor::offered` (`impl Iterator`), and `tcp::TlsAcceptor::accept` (an IO - stream). Decided: `AsRef` items as strings and an `Iterator` parameter as the - array of its items, as returns already are; a foreign future as #705's is; the IO - stream left out as what C can never hold, since no export returns one. -- `server::Config::websocket`, a borrowed `Option` of a listener that is not `Clone`. - Decided: lent as `Some` of a handle, as a bare field now is. -- `server::Listener::accept_with`'s future is not `Send`. Left out today as what C can - never hold, since it takes a `qmux::Session` no export returns once the excludes go; - confirm the census lists it so. - -- Reached since #721 exports other crates' types with their API: rustls's - `ClientConfig` fields of `Arc` (5) and `client::Resumption::store`, under the - trait-object decision above. Four more constructs, decided by the maintainer on 2026-11-13: - - A `'static` borrow parameter (`CertificateDer::from_slice`, `Der::from_slice`): - ✅ exported by interning by content (rejected: left out and listed). The binding keeps - one process-wide table keyed by the bytes' contents; the first call with given bytes - copies them into a leaked Rust allocation, and later calls with equal bytes reuse it. - Never key by C's pointer, which C may free or reuse. The generated docs on such a - parameter say memory grows with each distinct value and is never freed. This is sound - for a shared `&'static [u8]`: the copy is immutable and never freed, and equal bytes - differ only by address. Refuse with a span any other `'static` borrow, such as a - `&'static mut` (interning would alias it) or a non-byte element type. - - `rustls::ConfigBuilder`, both by value and behind an `Arc`: - ✅ left out and listed (rejected: a handle everywhere). - - `qmux::Session::connect` and `accept`, bounded by qmux's `Transport`: ✅ left out and - listed (rejected: a callback interface). - - `moq_sock::demux::Discard::ALL` (`[Discard; 4]`): ✅ crosses as the `Vec` of its - elements, as a returned slice does (rejected: left out). - -Public API: the generated API of each item that newly exports. diff --git a/quest/m1/ffi-refusals/no-config.md b/quest/m1/ffi-refusals/no-config.md index c483171da..9b9653380 100644 --- a/quest/m1/ffi-refusals/no-config.md +++ b/quest/m1/ffi-refusals/no-config.md @@ -30,5 +30,5 @@ that passes them). ## Required - [The moq pin bump](/quest/m1/ffi-refusals/moq-pin.md) - the pin is at moq's `main`, where the census is taken -- [What the excludes hide at moq's main](/quest/m1/ffi-refusals/moq-excluded.md) - exports the constructs the census still refuses there behind an exclude +- [`IpAddr`](/quest/m1/ffi-refusals/ip-addr.md) - exports `quic::demux::Datagram::local`, the last item moq's main refuses beyond not-send's - [Not Send](/quest/m1/ffi-export/not-send.md) - exports the three types the census still refuses for not being `Send`