diff --git a/ffi/README.md b/ffi/README.md index a7579ff7d..2ddee82b1 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -39,9 +39,16 @@ exclude = ["track::Producer::poll_closed"] "session::Stats" = "session_stats_snapshot" # Another package exported into the same library, which the package builds with: its -# own `exclude` and `rename`, by paths from its crate root. +# own `exclude`, `rename`, and `instances`, by paths from its crate root. [crates.moq-pattern] exclude = ["Patterns::iter"] + +# The instances a generic type exports at, by its path, and their C names without the +# prefix. An argument is `()`, a primitive, `String`, or an exported type by its path +# from its package's name in snake case, itself an instance if generic. Trailing +# arguments left out take their defaults. +[crates.moq-mux.instances] +"catalog::Producer" = "catalog_producer" ``` ## Rules @@ -57,6 +64,7 @@ export's, and adds nothing; another crate's type is refused. | an enum whose fields map, with no `Drop` of its own | a C enum without fields, or a struct of a tag and a union | | any other type, if `Send` | an object: an opaque handle to an `Arc`, freed with `_free` | | a type whose only generic parameters are lifetimes, such as `Path<'a>` | an object holding its `'static` form | +| a generic type, at each instance `instances` names | that instance as any other type, with each method whose impl and own bounds it meets; any other instance is refused | | a `pub` field of an object | a getter returning a copy | | a `pub` trait | a callback interface: a table of C functions and their data | | `fn` and inherent `pub` methods | functions named through their type | @@ -72,7 +80,7 @@ export's, and adds nothing; another crate's type is refused. | `Option` | a null handle or buffer, or `_option_` | | a `pub const` | a `#define` if a `bool` or integer, else a function returning it | | `impl Into`, `impl AsRef` | `X` | -| another type parameter | the first of `String`, `Bytes`, and `Vec` meeting its bounds, or a foreign implementation of its one exported trait | +| another type parameter | the first of `String`, `Bytes`, and `Vec` meeting its bounds, a foreign implementation of its one exported trait, or, as an argument of a generic type, the one argument of a named instance that meets its bounds and makes each generic type the signature names a named instance | A record or enum holds only values and `Copy` handles: one with a field that does not map, or that holds itself, is an object instead, and the census lists it. A borrowed return is @@ -110,7 +118,11 @@ refused, and the census counts why. Joining loses where segments split, and every export shares the prefix, so every C name is registered, and two items claiming one is a compile error at both spans, fixed by a `rename`: moq-net's `session::Stats` and `Session::stats` are both - `moq_session_stats`. + `moq_session_stats`. An instance is named by `instances`, and its methods through + that name. An `exclude` of a method by the generic type's path leaves it out of every + instance, and by the instance's path (`"Producer::stats"`) + out of that one; a `rename` of a method by the generic type's path names it at every + instance. ## IR @@ -127,7 +139,8 @@ the runtime the glue includes is [`runtime/rt.rs`](runtime/rt.rs). `--census dir` exports nothing. It writes `.md` for each exported package, which counts what exports and ranks every refusal by construct and by the type it names, lists each refused item at its span, and ends with the `exclude` list that exports the -rest. It ignores the config's `exclude`. +rest, and the refused instances to drop from `instances`. It ignores the config's +`exclude`, and reads its `instances`. ## Tests diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index a9cc83183..f045fb4f8 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -9,8 +9,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Context, Poll, Wake, Waker}; use api_lib::{ - Channel, Counter, Event, LIMIT, Log, Logger, Message, Name, Node, Point, Registry, Shape, Size, Stamp, Tally, - Window, + Channel, Counter, Event, LIMIT, Log, Logger, Message, Name, Node, Pair, Point, Registry, Shape, Size, Stack, Stamp, + Tally, Window, }; use bytes::Bytes; @@ -198,6 +198,36 @@ fn main() { let size = area.size(); println!("area {} {} {}", size.width, size.height, area.pixels()); + let pair = Pair { left: 2u32, right: 5 }; + let swapped = pair.swap(); + println!( + "pair {} {} sum {} {pair:?} {}", + swapped.left, + swapped.right, + pair.sum(), + pair == swapped + ); + println!("even {} {}", pair.even(), Pair { left: 7u32, right: 7 }.even()); + let sized = Pair { + left: Size { width: 1, height: 2 }, + right: 3u8, + }; + let flipped = sized.swap(); + println!("sized {} {} {flipped:?}", flipped.left, flipped.right.width); + let beside = Pair { left: 258u32, right: 9 }.beside(sized.left); + println!("beside {} {beside:?}", beside.left); + let mut stack = Stack::new(); + for (i, name) in ["a", "b"].into_iter().enumerate() { + stack.push(Counter::new(name, i as u64 + 1)); + } + let top = stack.pop().map(|c| c.get()); + println!( + "stack {} {top:?} {} {}", + stack.depth(), + stack.pop().is_some(), + stack.pop().is_none() + ); + let token = api_lib::Token::new(7); println!("token {} dropped {}", token.id, api_lib::dropped()); drop(token); diff --git a/ffi/fixtures/api/ffi.toml b/ffi/fixtures/api/ffi.toml index 31fc01185..46a878747 100644 --- a/ffi/fixtures/api/ffi.toml +++ b/ffi/fixtures/api/ffi.toml @@ -1,7 +1,16 @@ package = "api-fixture" prefix = "api" -# The list's tail is not `Clone`, so its getter has no copy to return. -exclude = ["Node::next"] +# The list's tail is not `Clone`, so its getter has no copy to return, and one instance +# leaves out a method the others keep. +exclude = ["Node::next", "Pair::swap"] + +# Generic types at the instances C uses, each with its C name: `Pair` is +# `Pair`, and `swap` returns each `Pair` of a `Size` as the other. +[instances] +"Pair" = "pair" +"Pair" = "size_pair" +"Pair" = "pair_size" +"Stack" = "counters" # Exported into the same library: `grow` names its types. [crates.dep-fixture] diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index a7838933f..d0bc70410 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -484,6 +484,72 @@ pub fn describe(event: &Event) -> String { format!("{event:?}") } +/// Two values: a generic record, which exports at each instance the config names. Its +/// second parameter defaults to its first, as an instance may leave it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pair { + pub left: L, + pub right: R, +} + +impl Pair { + /// The pair swapped: another instance, unless both are of one type. + pub fn swap(&self) -> Pair { + Pair { + left: self.right, + right: self.left, + } + } + + /// Whether the sides are equal: a method of only the instances whose sides compare. + pub fn even(&self) -> bool + where + L: PartialEq, + { + self.left == self.right + } +} + +/// An impl of one instance, whose methods no other instance has. +impl Pair { + pub fn sum(&self) -> u32 { + self.left + self.right + } + + /// The left value as a byte, beside `right`: the one instance that names the result + /// fills the type parameter, with `dep_fixture::Size`. + pub fn beside(&self, right: T) -> Pair { + Pair { + left: self.left as u8, + right, + } + } +} + +/// A stack: a generic object, at an instance of objects, whose handles move in and out. +#[derive(Debug, Default)] +pub struct Stack { + items: Vec, +} + +impl Stack { + pub fn new() -> Self { + Self { items: Vec::new() } + } + + pub fn push(&mut self, item: T) { + self.items.push(item); + } + + pub fn pop(&mut self) -> Option { + self.items.pop() + } + + pub fn depth(&self) -> usize { + self.items.len() + } +} + /// An area grown by `by` on each side: another export's types, across crates. pub fn grow(area: &dep::Area, by: u32) -> dep::Area { let size = area.size(); diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 7766a0a42..6d5a664d8 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -8,11 +8,18 @@ fixtures/reject/src/lib.rs:113:2: rust2-ffi: cannot export method `Text::replace fixtures/reject/src/lib.rs:118:2: rust2-ffi: cannot export method `Text::later`: returned object that borrows `impl std::future::Future>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:125:1: rust2-ffi: cannot export fn `either`: reference inside a parameter `std::option::Option<&str>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:130:1: rust2-ffi: cannot export struct `Lease`: object no export returns; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:149:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:14: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:158:1: rust2-ffi: cannot export fn `unnamed`: instance the config does not name `reject_fixture::Cell`; exclude it in the config to leave it out + fixtures/reject/src/lib.rs:149:1: note: `Cell` exports only at the instances the config names +fixtures/reject/src/lib.rs:163:1: rust2-ffi: cannot export fn `fill`: generic parameter of several instances `u16, u32`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:168:1: rust2-ffi: cannot export struct `Bounded`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:168:1: rust2-ffi: instance `Bounded` in the config exports nothing: `reject_fixture::Bounded` needs `std::string::String: std::marker::Copy` +fixtures/reject/src/lib.rs:171:1: rust2-ffi: cannot export instance `Holder>`: type argument the config cannot spell `std::option::Option`; drop it from the config's `instances` +fixtures/reject/src/lib.rs:176:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:19: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:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out fixtures/reject/src/lib.rs:31: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:36:1: rust2-ffi: instance `Opaque` in the config exports nothing: `reject_fixture::Opaque` takes no type arguments fixtures/reject/src/lib.rs:40: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:45:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out fixtures/reject/src/lib.rs:49:1: rust2-ffi: cannot export macro `noop`: macro; exclude it in the config to leave it out @@ -28,3 +35,4 @@ fixtures/reject/src/lib.rs:92:1: rust2-ffi: cannot export fn `retext`: 'static b fixtures/reject/src/lib.rs:92:15: note: `'a` is `'static`, as a handle outlives every call fixtures/reject/src/lib.rs:97: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:9:1: rust2-ffi: cannot export fn `pair`: tuple; exclude it in the config to leave it out +no span: rust2-ffi: instance `Missing` in the config exports nothing: `reject_fixture::Missing` names no exported struct or enum diff --git a/ffi/fixtures/reject/ffi.toml b/ffi/fixtures/reject/ffi.toml index 9786be3b0..8da2efc3e 100644 --- a/ffi/fixtures/reject/ffi.toml +++ b/ffi/fixtures/reject/ffi.toml @@ -3,5 +3,15 @@ prefix = "reject" # An exclusion leaves an item out, so nothing refuses it. exclude = ["Excluded"] +# Instances that cannot export: an unmet bound, a default argument no key can spell, a +# type that is not generic, and a path that names nothing. `Cell` and `Cell` export, and nothing else of `Cell` does. +[instances] +"Bounded" = "bounded" +"Cell" = "cell_u16" +"Cell" = "cell" +"Holder" = "holder" +"Missing" = "missing" +"Opaque" = "opaque_u8" + # Another export, whose `Size` claims the same C name as this one's. [crates.dep-fixture] diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 41cdbb8b1..2ad4bbe7a 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -145,5 +145,32 @@ pub fn measure(size: dep::Size) -> dep::Area { dep::Area::new(size) } +/// A generic type the config names at `u32` alone. +pub struct Cell(T); + +impl Cell { + pub fn new(value: T) -> Self { + Self(value) + } +} + +/// An instance the config does not name. +pub fn unnamed(cell: Cell) -> u8 { + cell.0 +} + +/// A type parameter both instances of `Cell` could fill. +pub fn fill(value: T) -> Cell { + Cell(value) +} + +/// A generic type whose bound the config's instance does not meet. +pub struct Bounded(pub T); + +/// A generic type whose default argument is a type no instance key can spell. +pub struct Holder> { + pub value: T, +} + /// Another crate's item that is no export, so nothing names it. pub use std::collections::HashSet; diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index a95f847db..d236545b7 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -326,7 +326,9 @@ exclude = [ [crates.hang] exclude = [ - "Catalog", + "Catalog::from_reader", + "Catalog::media", + "Catalog::subscribe", "catalog::Archive::store", "catalog::Archive::timelines", "catalog::Audio::enabled", @@ -368,6 +370,11 @@ exclude = [ "timeline::RecordExt", ] +# The catalog moq-ffi reads, with moq-mux's untyped extension. The rule's name, +# `moq_catalog`, would make its accessors, such as `audio`, the `catalog` module's types. +[crates.hang.instances] +"Catalog" = "hang_catalog" + [crates.hang.rename] # The rule names this and moq-net's `Error` alike. "Error" = "hang_error" @@ -392,60 +399,63 @@ exclude = [ "binary::Consumer::poll_next", "binary::Snapshot", "binary::Stream", - "catalog::Config", "catalog::Consumer", "catalog::Entry", "catalog::Guard", "catalog::IntoRendition", - "catalog::Producer", + "catalog::Producer::audio", + "catalog::Producer::binary_snapshot", + "catalog::Producer::binary_stream", + "catalog::Producer::is_claimed", + "catalog::Producer::json_snapshot", + "catalog::Producer::json_stream", + "catalog::Producer::modify", + "catalog::Producer::mutate", + "catalog::Producer::stats", + "catalog::Producer::text", + "catalog::Producer::track", + "catalog::Producer::video", "catalog::RenditionConfig", - "catalog::Reserved", + "catalog::Reserved::audio", + "catalog::Reserved::text", + "catalog::Reserved::track", + "catalog::Reserved::video", "catalog::Select", "catalog::Stream", - "catalog::Timebase", "catalog::hang::CatalogExt", - "catalog::hang::Consumer", "catalog::hang::Extra::get", "catalog::hang::Extra::iter", "catalog::hang::Extra::remove", "catalog::hang::Extra::set", "catalog::msf::Consumer", "codec::aac::Config::parse", - "codec::aac::Import", "codec::annexb::NalIterator", "codec::annexb::build_prefix", "codec::annexb::find_start_code", "codec::annexb::from_length_prefixed", "codec::annexb::length_prefixed_to_annexb", "codec::av1::Error", - "codec::av1::Import", + "codec::av1::Import::decode", "codec::av1::Split::decode", "codec::av1::Split::flush", "codec::flac::Config", - "codec::flac::Import", "codec::h264::Avcc::pps", "codec::h264::Avcc::sps", "codec::h264::Export", - "codec::h264::Import", + "codec::h264::Import::decode", "codec::h264::Split::decode", "codec::h264::Split::flush", "codec::h265::Export", "codec::h265::Hvcc::pps", "codec::h265::Hvcc::sps", "codec::h265::Hvcc::vps", - "codec::h265::Import", + "codec::h265::Import::decode", "codec::h265::Split::decode", "codec::h265::Split::flush", - "codec::mp3::Import", "codec::opus::Config::parse", - "codec::opus::Import", "codec::opus::Mapping::new", "codec::opus::mapping::Config", - "codec::vp8::Import", - "codec::vp9::Import", - "container::Consumer", "container::Container", - "container::GroupConsumer", "container::InvalidEnd", "container::MissingKeyframe", "container::Producer", @@ -472,25 +482,36 @@ exclude = [ "container::ts::Mpegts::tracks", "container::ts::MultipleProgramsError", "container::ts::Passthrough", - "container::ts::Programs", + "container::ts::Programs::decode", + "container::ts::Programs::finish", "container::ts::Track::descriptors", "container::ts::stats::Export::streams", "container::ts::stats::Snapshot::streams", "follow::Event", "follow::Instances", - "import::Container", - "import::Track", - "import::TrackStream", "json::Consumer", "json::Snapshot", "json::Stream", - "select::Broadcast::retain", "timeline::Consumer", "timeline::Entry", "timeline::Event", "timeline::Producer::push", ] +# Each at the one type moq-ffi uses it at: the untyped catalog extension, or the hang +# container a catalog entry names. +[crates.moq-mux.instances] +# `Config<()>` is the default, which `with_catalog` makes the extension's. +"catalog::Config<()>" = "catalog_config" +"catalog::Config" = "catalog_config_extra" +"catalog::Producer" = "catalog_producer" +"catalog::Reserved" = "catalog_reserved" +"catalog::Timebase" = "catalog_timebase" +"catalog::hang::Consumer" = "catalog_hang_consumer" +"container::Consumer" = "container_consumer" +"container::GroupConsumer" = "container_group_consumer" +"import::Container" = "import_container" + [crates.moq-mux.rename] # The rule names these and moq-net's `Error` and hang's `container::Frame` alike. "Error" = "mux_error" diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 284e972cd..8f3271cf4 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -73,6 +73,8 @@ pub struct Abi<'a> { /// C names for Rust paths, each starting with its crate's name, in place of the /// rule's: an item's, and its methods' through it. rename: &'a BTreeMap, + /// Each instance's C name, without the prefix, which its members are named through. + instances: HashMap, /// The renamed paths some name went through. renamed: std::cell::RefCell>, /// Each `Option` struct by C name, with `T`. @@ -86,11 +88,12 @@ pub struct Abi<'a> { } impl<'a> Abi<'a> { - pub fn new(api: &'a Api, prefix: &str, rename: &'a BTreeMap) -> Self { + pub fn new(api: &'a Api, prefix: &str, rename: &'a BTreeMap, instances: &[(Type, String)]) -> Self { let mut abi = Self { api, prefix: prefix.to_string(), rename, + instances: instances.iter().cloned().collect(), renamed: Default::default(), options: BTreeMap::new(), ranges: BTreeMap::new(), @@ -138,15 +141,35 @@ impl<'a> Abi<'a> { } pub fn record(&self, i: usize) -> String { - self.name(&self.api.records[i].path) + self.type_name(Type::Record(i), &self.api.records[i].path) } pub fn enumeration(&self, i: usize) -> String { - self.name(&self.api.enums[i].path) + self.type_name(Type::Enum(i), &self.api.enums[i].path) } pub fn object(&self, i: usize) -> String { - self.name(&self.api.objects[i].path) + self.type_name(Type::Object(i), &self.api.objects[i].path) + } + + /// A type's C name: an instance's as the config names it, else its path's. + fn type_name(&self, ty: Type, path: &[String]) -> String { + match self.instances.get(&ty) { + Some(name) => format!("{}_{name}", self.prefix), + None => self.name(path), + } + } + + /// A function's C name: a method's through its type's, unless renamed itself. + fn function_name(&self, function: &Function, owner: Option<&Ty>) -> String { + let owner = match owner { + Some(Ty::Struct(name) | Ty::Enum(name) | Ty::Handle { name, .. }) => name, + _ => return self.name(&function.path), + }; + match self.rename.contains_key(&function.path.join("::")) { + true => self.name(&function.path), + false => format!("{owner}_{}", snake(function.name())), + } } pub fn callback(&self, i: usize) -> String { @@ -251,7 +274,7 @@ impl<'a> Abi<'a> { /// The C signature of `function`, a method of the type named `owner` if it has one. pub fn export(&self, function: &Function, owner: Option<&Ty>) -> Export { - let name = self.name(&function.path); + let name = self.function_name(function, owner); let mut params = Vec::new(); if let (Some(receiver), Some(owner)) = (function.receiver, owner) { let ty = match owner { @@ -259,7 +282,8 @@ impl<'a> Abi<'a> { name: name.clone(), constant: receiver == Receiver::Ref || (receiver == Receiver::Owned - && self.api.objects.iter().any(|o| o.copy && &self.name(&o.path) == name)), + && (0..self.api.objects.len()) + .any(|i| self.api.objects[i].copy && &self.object(i) == name)), }, // A value's receiver is read through a pointer, and never changed. value => Ty::In(Box::new(value.clone())), @@ -370,7 +394,7 @@ impl<'a> Abi<'a> { let mut functions: Vec<(&Function, Option)> = Vec::new(); for (i, record) in api.records.iter().enumerate() { let name = self.record(i); - let what = format!("struct `{}`", record.path.join("::")); + let what = format!("struct `{}`", api.rust(&record.path, &record.args)); self.claim_traits(&name, &what, record.span, record.traits, true); self.claim(name.clone(), what, record.span); types.extend(record.fields.iter().map(|f| &f.ty)); @@ -378,7 +402,7 @@ impl<'a> Abi<'a> { } for (i, e) in api.enums.iter().enumerate() { let name = self.enumeration(i); - let what = format!("enum `{}`", e.path.join("::")); + let what = format!("enum `{}`", api.rust(&e.path, &e.args)); let upper = name.to_uppercase(); for variant in &e.variants { self.claim( @@ -405,7 +429,7 @@ impl<'a> Abi<'a> { } for (i, object) in api.objects.iter().enumerate() { let name = self.object(i); - let what = format!("type `{}`", object.path.join("::")); + let what = format!("type `{}`", api.rust(&object.path, &object.args)); self.claim(format!("{name}_free"), what.clone(), object.span); self.claim_traits(&name, &what, object.span, object.traits, false); self.claim(name.clone(), what, object.span); diff --git a/ffi/src/c.rs b/ffi/src/c.rs index b31252c46..72f1e8912 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -183,7 +183,7 @@ impl Header<'_> { for (i, record) in api.records.iter().enumerate() { let name = abi.record(i); - self.line(format!("/* {} */", record.path.join("::")).trim_end()); + self.line(format!("/* {} */", abi.api.rust(&record.path, &record.args)).trim_end()); self.value_functions(&name, Ty::Struct(name.clone()), record.traits, true); let owner = Ty::Struct(name.clone()); for method in &record.methods { @@ -197,7 +197,7 @@ impl Header<'_> { if e.methods.is_empty() && !has(e.traits) && e.plain() { continue; } - self.line(format!("/* {} */", e.path.join("::"))); + self.line(format!("/* {} */", abi.api.rust(&e.path, &e.args))); self.value_functions(&name, ty.clone(), e.traits, !e.plain()); for method in &e.methods { self.function(method, Some(&ty)); @@ -206,7 +206,7 @@ impl Header<'_> { } for (i, object) in api.objects.iter().enumerate() { let name = abi.object(i); - let docs = format!("{}\n\n{}", object.path.join("::"), object.docs); + let docs = format!("{}\n\n{}", abi.api.rust(&object.path, &object.args), object.docs); self.line(comment(docs.trim(), "").trim_end()); self.line(format!("void {name}_free({name} *self);")); let t = object.traits; diff --git a/ffi/src/census.rs b/ffi/src/census.rs index 9e251041e..07d430045 100644 --- a/ffi/src/census.rs +++ b/ffi/src/census.rs @@ -40,7 +40,7 @@ pub fn render(api: &Api, collected: &Report, top: bool, clashes: &[Clash], at: & }; let _ = writeln!(out, "| {name} | {exported} | {refused} | {share} |"); }; - row("Types", types, refused(&["struct", "enum", "union"])); + row("Types", types, refused(&["struct", "enum", "union", "instance"])); row("Functions", functions, refused(&["fn"])); row( "Methods and fields of exported types", @@ -139,13 +139,22 @@ pub fn render(api: &Api, collected: &Report, top: bool, clashes: &[Clash], at: & false => format!("[crates.{}]\n", collected.package), }; let _ = writeln!(out, "```toml\n{table}exclude = ["); - let mut paths: Vec<&str> = collected.refusals.iter().map(|r| r.path.as_str()).collect(); + // An instance is left out by not naming it. + let (instances, items): (Vec<&Refusal>, Vec<&Refusal>) = + collected.refusals.iter().partition(|r| r.kind == "instance"); + let mut paths: Vec<&str> = items.iter().map(|r| r.path.as_str()).collect(); paths.sort(); paths.dedup(); for path in paths { let _ = writeln!(out, " \"{path}\","); } let _ = writeln!(out, "]\n```"); + if !instances.is_empty() { + let _ = writeln!(out, "\nand names none of these in `instances`:\n"); + for refusal in instances { + let _ = writeln!(out, "- `{}`", refusal.path); + } + } } // A clash names each claimant by its Rust path, which starts with its crate's name. let claims = |what: &str| what.contains(&format!("`{}::", collected.krate)); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 25ba6b225..8f45375a1 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4,15 +4,16 @@ //! refused with its span. An export names another's types across crates; another crate's //! type is refused. Nothing is opted in by attribute and nothing is skipped silently: the //! config's `exclude` is the only way to leave an item out, and `#[doc(hidden)]` items, -//! which are no part of the documented API, are listed in the census. +//! which are no part of the documented API, are listed in the census. A generic type +//! exports at each instance the config's `instances` names, and only there. -use std::collections::VecDeque; +use std::collections::{BTreeMap, VecDeque}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{Obligation, ObligationCause}; -use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypingEnv}; +use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt, TypingEnv}; use rustc_span::{Span, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -54,6 +55,8 @@ pub struct Collected { pub api: Api, /// Each export's, in the order given. pub reports: Vec, + /// Each instance the config names that exports, and its C name without the prefix. + pub instances: Vec<(Type, String)>, } /// An exported crate. @@ -64,6 +67,8 @@ pub struct Crate<'a> { pub package: &'a str, /// Paths from its root the config leaves out. pub exclude: &'a [String], + /// The instances the config names, by type, with their C names. + pub instances: &'a BTreeMap, } /// What collection found in one exported crate, by paths from its root. @@ -84,6 +89,9 @@ pub struct Report { pub aliases: Vec, /// Re-exports of another export's items, which name that export's. pub reexports: Vec, + /// Instances the config names that name no type, each with why, and where the type + /// it names is. + pub unresolved: Vec<(String, String, Option)>, } /// How an exported crate's type is exported, once decided. @@ -96,11 +104,41 @@ enum Decl { Refused(Why), } +/// A type or trait the export declares: an item, or a type with type parameters at one +/// instance, by its arguments with lifetimes erased. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +struct Key<'tcx> { + def_id: DefId, + args: Option>, +} + +/// A type the export declares, and how it names it. +#[derive(Clone)] +struct Site<'tcx> { + key: Key<'tcx>, + /// Its generic arguments as exported, each lifetime `'static`. + args: ty::GenericArgsRef<'tcx>, + /// Its item's path, which names its members in the IR. + path: Path, + /// Its path with an instance's arguments, which reports name it and its members by. + shown: Path, +} + +/// An instance the config names. +#[derive(Clone)] +struct Instance<'tcx> { + site: Site<'tcx>, + /// Its C name, without the prefix. + name: String, +} + struct Collector<'tcx> { tcx: TyCtxt<'tcx>, /// Each `pub` item and its shortest path, in the order the walk met them. items: Vec<(DefId, Path)>, - decls: rustc_data_structures::fx::FxHashMap, + decls: rustc_data_structures::fx::FxHashMap, Decl>, + /// The instances the config names, in its order. + instances: Vec>, /// The exported crates, the configured one first, and what collection found in each. crates: Vec, reports: Vec, @@ -114,7 +152,7 @@ struct Collector<'tcx> { bound: Option, range_bounds: Option, /// Objects no export returns, refused. - orphans: rustc_data_structures::fx::FxHashSet, + orphans: rustc_data_structures::fx::FxHashSet>, api: Api, } @@ -163,8 +201,10 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { excluded: c.exclude.iter().map(|path| (path.clone(), 0)).collect(), aliases: Vec::new(), reexports: Vec::new(), + unresolved: Vec::new(), }) .collect(), + instances: Vec::new(), left_out: Default::default(), impls: Default::default(), bytes, @@ -181,13 +221,26 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { }, }; c.walk(); + c.resolve(crates); c.declare(); c.define(); let more = c.orphans(); if more.is_empty() { + let instances = (c.instances.iter()) + .filter_map(|instance| { + let ty = match c.decls.get(&instance.site.key)? { + Decl::Record(i) => Type::Record(*i), + Decl::Enum(i) => Type::Enum(*i), + Decl::Object(i) => Type::Object(*i), + Decl::Callback(_) | Decl::Refused(_) => return None, + }; + Some((ty, instance.name.clone())) + }) + .collect(); return Collected { api: c.api, reports: c.reports, + instances, }; } orphans.extend(more); @@ -208,11 +261,15 @@ impl<'tcx> Collector<'tcx> { self.crates.contains(&krate) } - /// Whether the config excludes `path`, counting the exclusion. + /// Whether the config excludes `path`, counting the exclusion. A member of an instance + /// is left out by its instance's path or its type's, which leaves it out of each. fn exclude(&mut self, path: &[String]) -> bool { + let generic: Vec<&str> = path[1..].iter().map(|s| s.split('<').next().unwrap_or(s)).collect(); + let generic = generic.join("::"); let (report, joined) = self.report(path); for (excluded, count) in &mut report.excluded { - if joined == *excluded || joined.starts_with(&format!("{excluded}::")) { + let covers = |path: &str| path == excluded || path.starts_with(&format!("{excluded}::")); + if covers(&joined) || covers(&generic) { *count += 1; return true; } @@ -220,6 +277,195 @@ impl<'tcx> Collector<'tcx> { false } + /// Whether a type or trait takes type or const parameters: a type that does exports + /// only at the instances the config names. + fn typed(&self, def_id: DefId) -> bool { + (self.tcx.generics_of(def_id).own_params.iter()) + .any(|p| p.name != rustc_span::kw::SelfUpper && !matches!(p.kind, ty::GenericParamDefKind::Lifetime)) + } + + /// The key of `def_id` at `args`: an instance's, if it takes type parameters. + fn key(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Key<'tcx> { + let args = self.typed(def_id).then(|| self.tcx.erase_and_anonymize_regions(args)); + Key { def_id, args } + } + + /// How the type `def_id` is exported at `args`. + fn decl(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Option<&Decl> { + self.decls.get(&self.key(def_id, args)) + } + + /// How a trait is exported. + fn trait_decl(&self, def_id: DefId) -> Option<&Decl> { + self.decls.get(&Key { def_id, args: None }) + } + + /// The types an item declares: itself, or each instance the config names of it. + fn sites(&self, def_id: DefId, path: &Path) -> Vec> { + let instances: Vec> = (self.instances.iter()) + .filter(|instance| instance.site.key.def_id == def_id) + .map(|instance| instance.site.clone()) + .collect(); + match instances.is_empty() { + true => vec![Site { + key: Key { def_id, args: None }, + args: statics(self.tcx, def_id), + path: path.clone(), + shown: path.clone(), + }], + false => instances, + } + } + + /// The type a site declares. + fn site_ty(&self, site: &Site<'tcx>) -> Ty<'tcx> { + self.tcx + .type_of(site.key.def_id) + .instantiate(self.tcx, site.args) + .skip_norm_wip() + } + + /// A type as an instance's key spells it, each export's by its path in the IR. + fn spell(&self, ty: Ty<'tcx>) -> String { + let tcx = self.tcx; + match ty.kind() { + ty::Tuple(list) if list.is_empty() => "()".to_string(), + ty::Adt(adt, _) if tcx.lang_items().string() == Some(adt.did()) => "String".to_string(), + ty::Adt(adt, args) => { + let path = match self.items.iter().find(|(def_id, _)| *def_id == adt.did()) { + Some((_, path)) => path.join("::"), + None => tcx.def_path_str(adt.did()), + }; + let args: Vec = args.types().map(|ty| self.spell(ty)).collect(); + match args.is_empty() { + true => path, + false => format!("{path}<{}>", args.join(", ")), + } + } + _ => ty.to_string(), + } + } + + /// Resolve the instances each export's config names, noting each that names no type. + fn resolve(&mut self, crates: &[Crate<'_>]) { + let tcx = self.tcx; + for krate in crates { + for (key, name) in krate.instances { + let instance = crate::config::TypeName::parse(key) + .map_err(|why| (why, None)) + .and_then(|mut parsed| { + parsed.path.insert(0, krate.root.clone()); + let ty = self.instance_ty(&parsed)?; + let ty::Adt(adt, args) = *ty.kind() else { + unreachable!("an instance's type is a struct or enum") + }; + let span = Some(tcx.def_span(adt.did())); + if !self.typed(adt.did()) { + return Err(("its type takes no type parameters".to_string(), span)); + } + let key = self.key(adt.did(), args); + if let Some(other) = self.instances.iter().find(|i| i.site.key == key) { + let other = other.site.shown[1..].join("::"); + return Err((format!("it is the instance `{other}` names"), span)); + } + let path = parsed.path; + let spelled: Vec = args.types().map(|ty| self.spell(ty)).collect(); + let mut shown = path.clone(); + let last = shown.last_mut().expect("a path has a segment"); + *last = format!("{last}<{}>", spelled.join(", ")); + Ok(Instance { + site: Site { key, args, path, shown }, + name: name.clone(), + }) + }); + match instance { + Ok(instance) => self.instances.push(instance), + Err((why, span)) => { + let (report, _) = self.report(std::slice::from_ref(&krate.root)); + report.unresolved.push((key.clone(), why, span)); + } + } + } + } + } + + /// The type an instance's key names: `()`, a primitive, `String`, or an exported + /// struct or enum, each lifetime `'static`, with its arguments' defaults filled in and + /// its bounds met. + fn instance_ty(&self, name: &crate::config::TypeName) -> Result, (String, Option)> { + let tcx = self.tcx; + let joined = name.path.join("::"); + let primitive = match joined.as_str() { + "" => Some(tcx.types.unit), + "bool" => Some(tcx.types.bool), + "char" => Some(tcx.types.char), + "u8" => Some(tcx.types.u8), + "u16" => Some(tcx.types.u16), + "u32" => Some(tcx.types.u32), + "u64" => Some(tcx.types.u64), + "usize" => Some(tcx.types.usize), + "i8" => Some(tcx.types.i8), + "i16" => Some(tcx.types.i16), + "i32" => Some(tcx.types.i32), + "i64" => Some(tcx.types.i64), + "isize" => Some(tcx.types.isize), + "f32" => Some(tcx.types.f32), + "f64" => Some(tcx.types.f64), + "String" => { + (tcx.lang_items().string()).map(|string| Ty::new_adt(tcx, tcx.adt_def(string), ty::List::empty())) + } + _ => None, + }; + if let Some(ty) = primitive { + return match name.args.is_empty() { + true => Ok(ty), + false => Err((format!("`{joined}` takes no type arguments"), None)), + }; + } + let def_id = (self.items.iter()) + .find(|(_, path)| path.join("::") == joined) + .map(|(def_id, _)| *def_id) + .filter(|&def_id| matches!(tcx.def_kind(def_id), DefKind::Struct | DefKind::Enum)) + .ok_or_else(|| (format!("`{joined}` names no exported struct or enum"), None))?; + let span = Some(tcx.def_span(def_id)); + let mut given = name.args.iter(); + let mut args: Vec> = Vec::new(); + for param in &tcx.generics_of(def_id).own_params { + let arg = match param.kind { + ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(), + ty::GenericParamDefKind::Const { .. } => { + return Err((format!("`{joined}` takes a const parameter"), span)); + } + ty::GenericParamDefKind::Type { .. } => match given.next() { + Some(arg) => self.instance_ty(arg)?.into(), + None => match param.default_value(tcx) { + Some(default) => default.instantiate(tcx, &args[..]).skip_norm_wip(), + None => return Err((format!("`{joined}` needs an argument for `{}`", param.name), span)), + }, + }, + }; + args.push(arg); + } + if given.next().is_some() { + let count = args.iter().filter(|arg| arg.as_type().is_some()).count(); + let takes = match count { + 0 => "no type arguments".to_string(), + n => format!("at most {n} type arguments"), + }; + return Err((format!("`{joined}` takes {takes}"), span)); + } + let args = tcx.mk_args(&args); + let (infcx, env) = tcx.infer_ctxt().build_with_typing_env(TypingEnv::fully_monomorphized()); + for clause in tcx.clauses_of(def_id).instantiate(tcx, args).clauses { + let clause = clause.skip_norm_wip(); + let obligation = Obligation::new(tcx, ObligationCause::dummy(), env, clause); + if !infcx.predicate_must_hold_modulo_regions(&obligation) { + return Err((format!("`{joined}` needs `{clause}`"), span)); + } + } + Ok(Ty::new_adt(tcx, tcx.adt_def(def_id), args)) + } + fn refuse(&mut self, path: &[String], kind: &'static str, span: Span, why: Vec) { let (report, path) = self.report(path); report.refusals.push(Refusal { path, kind, span, why }); @@ -306,131 +552,196 @@ impl<'tcx> Collector<'tcx> { } } - /// Decide how each type and trait is exported, before any signature names one: a - /// struct whose fields are all `pub`, or an enum, is a value if its fields map, and - /// any other type is an object. + /// Decide how each type and trait is exported, before any signature names one. fn declare(&mut self) { let tcx = self.tcx; - for (def_id, _) in self.items.clone() { - let params = &tcx.generics_of(def_id).own_params; - let generic = params.iter().any(|p| p.name != rustc_span::kw::SelfUpper); - let lifetimes = params - .iter() - .all(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime)); - let decl = match tcx.def_kind(def_id) { - DefKind::Union => Decl::Refused(why("union", "")), - // Held by a handle that outlives any call, it is the form that borrows nothing. - DefKind::Struct | DefKind::Enum if generic && lifetimes => self.object(def_id), - DefKind::Struct | DefKind::Enum | DefKind::Trait if generic => Decl::Refused(why("generic type", "")), - // A value is copied across and lowered into memory C frees, so its own `Drop` - // would run when Rust lets go of it, not when C does. - DefKind::Struct | DefKind::Enum if tcx.adt_destructor(def_id).is_some() => self.object(def_id), - DefKind::Struct => { - let variant = tcx.adt_def(def_id).non_enum_variant(); - let record = !variant.fields.is_empty() - && variant.fields.iter().all(|f| f.vis.is_public()) - && !variant.is_field_list_non_exhaustive(); - match record { - true => Decl::Record(0), - false => self.object(def_id), - } - } - DefKind::Enum if tcx.adt_def(def_id).variants().is_empty() => { - Decl::Refused(why("enum without variants", "")) + for (def_id, path) in self.items.clone() { + if !matches!( + tcx.def_kind(def_id), + DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait + ) { + continue; + } + for site in self.sites(def_id, &path) { + let decl = self.declare_site(&site); + self.decls.insert(site.key, decl); + } + } + // An instance holds its arguments, so it exports only if each does. + loop { + self.settle(); + let mut changed = false; + for instance in self.instances.clone() { + let site = &instance.site; + if !matches!(self.decls.get(&site.key), Some(Decl::Refused(_)) | None) + && let Err(why) = self.args(site) + { + self.decls.insert(site.key, Decl::Refused(why)); + changed = true; } - DefKind::Enum => Decl::Enum(0), - DefKind::Trait => Decl::Callback(0), - _ => continue, - }; - self.decls.insert(def_id, decl); + } + if !changed { + break; + } } - self.settle(); // A trait whose methods do not map is refused before any signature takes it. for (def_id, path) in self.items.clone() { - if matches!(self.decls.get(&def_id), Some(Decl::Callback(_))) + if matches!(self.trait_decl(def_id), Some(Decl::Callback(_))) && let Err(why) = self.callback(def_id, &path) { let first = why.into_iter().next().expect("a refusal has a reason"); - self.decls.insert(def_id, Decl::Refused(first)); + self.decls.insert(Key { def_id, args: None }, Decl::Refused(first)); } } // Number each kind in item order, with placeholders filled in by `define`. for (def_id, path) in self.items.clone() { let span = tcx.def_span(def_id); let docs = docs(tcx, def_id); - let Some(decl) = self.decls.get_mut(&def_id) else { - continue; - }; - let api = &mut self.api; - match decl { - Decl::Record(i) => { - *i = api.records.len(); - api.records.push(Record { - path, - span, - docs, - fields: Vec::new(), - tuple: false, - methods: Vec::new(), - traits: Traits::default(), - }); - } - Decl::Enum(i) => { - *i = api.enums.len(); - api.enums.push(Enum { - path, - span, - docs, - variants: Vec::new(), - exhaustive: true, - methods: Vec::new(), - traits: Traits::default(), - }); - } - Decl::Object(i) => { - *i = api.objects.len(); - let sync = implements(tcx, def_id, sym::Sync); - let copy = implements(tcx, def_id, sym::Copy); - let lifetimes = tcx.generics_of(def_id).own_counts().lifetimes; - api.objects.push(Object { - path, - span, - docs, - sync, - copy, - lifetimes, - methods: Vec::new(), - traits: Traits::default(), - }); + for site in self.sites(def_id, &path) { + let Some(decl) = self.decls.get_mut(&site.key) else { + continue; + }; + let api = &mut self.api; + let (path, docs) = (site.path, docs.clone()); + match decl { + Decl::Record(i) => { + *i = api.records.len(); + api.records.push(Record { + path, + args: Vec::new(), + span, + docs, + fields: Vec::new(), + tuple: false, + methods: Vec::new(), + traits: Traits::default(), + }); + } + Decl::Enum(i) => { + *i = api.enums.len(); + api.enums.push(Enum { + path, + args: Vec::new(), + span, + docs, + variants: Vec::new(), + exhaustive: true, + methods: Vec::new(), + traits: Traits::default(), + }); + } + Decl::Object(i) => { + *i = api.objects.len(); + let ty = tcx.type_of(def_id).instantiate(tcx, site.args).skip_norm_wip(); + let sync = implements(tcx, ty, def_id, sym::Sync); + let copy = implements(tcx, ty, def_id, sym::Copy); + let lifetimes = tcx.generics_of(def_id).own_counts().lifetimes; + api.objects.push(Object { + path, + args: Vec::new(), + span, + docs, + sync, + copy, + lifetimes, + methods: Vec::new(), + traits: Traits::default(), + }); + } + Decl::Callback(i) => { + *i = api.callbacks.len(); + api.callbacks.push(Callback { + path, + span, + docs, + methods: Vec::new(), + }); + } + Decl::Refused(_) => {} } - Decl::Callback(i) => { - *i = api.callbacks.len(); - api.callbacks.push(Callback { - path, - span, - docs, - methods: Vec::new(), - }); + } + } + } + + /// How a type or trait is exported: a struct whose fields are all `pub`, or an enum, + /// is a value if its fields map, and any other type is an object. + fn declare_site(&self, site: &Site<'tcx>) -> Decl { + let tcx = self.tcx; + let def_id = site.key.def_id; + let instance = site.key.args.is_some(); + let params = &tcx.generics_of(def_id).own_params; + let generic = params.iter().any(|p| p.name != rustc_span::kw::SelfUpper); + let lifetimes = params + .iter() + .any(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime)); + match tcx.def_kind(def_id) { + DefKind::Union => Decl::Refused(why("union", "")), + // Held by a handle that outlives any call, it is the form that borrows nothing. + DefKind::Struct | DefKind::Enum if lifetimes && (instance || !self.typed(def_id)) => self.object(site), + DefKind::Struct | DefKind::Enum | DefKind::Trait if generic && !instance => { + Decl::Refused(why("generic type", "")) + } + // A value is copied across and lowered into memory C frees, so its own `Drop` + // would run when Rust lets go of it, not when C does. + DefKind::Struct | DefKind::Enum if tcx.adt_destructor(def_id).is_some() => self.object(site), + DefKind::Struct => { + let variant = tcx.adt_def(def_id).non_enum_variant(); + let record = !variant.fields.is_empty() + && variant.fields.iter().all(|f| f.vis.is_public()) + && !variant.is_field_list_non_exhaustive(); + match record { + true => Decl::Record(0), + false => self.object(site), } - Decl::Refused(_) => {} } + DefKind::Enum if tcx.adt_def(def_id).variants().is_empty() => { + Decl::Refused(why("enum without variants", "")) + } + DefKind::Enum => Decl::Enum(0), + _ => Decl::Callback(0), } } + /// An instance's type arguments, each of which must export as one the config can + /// spell: a default may name any type. + fn args(&self, site: &Site<'tcx>) -> Result, Why> { + (site.args.types()) + .map(|ty| { + let arg = match ty.kind() { + ty::Tuple(list) if list.is_empty() => Type::Unit, + _ => self.ty(ty, Pos::Behind)?, + }; + match arg { + Type::Unit + | Type::Bool + | Type::Int(_) + | Type::F32 + | Type::F64 + | Type::Char + | Type::String + | Type::Record(_) + | Type::Enum(_) + | Type::Object(_) => Ok(arg), + _ => Err(why("type argument the config cannot spell", self.spell(ty))), + } + }) + .collect() + } + /// An object, if the type can move across threads. Shared borrows of one that is not /// `Sync` are exclusive. - fn object(&self, def_id: DefId) -> Decl { - if self.orphans.contains(&def_id) { + fn object(&self, site: &Site<'tcx>) -> Decl { + if self.orphans.contains(&site.key) { return Decl::Refused(why("object no export returns", "")); } - match implements(self.tcx, def_id, sym::Send) { + match implements(self.tcx, self.site_ty(site), site.key.def_id, sym::Send) { true => Decl::Object(0), false => Decl::Refused(why("object not Send", "")), } } /// The objects C can never hold a handle to: no export it can call returns one. - fn orphans(&self) -> Vec { + fn orphans(&self) -> Vec> { let api = &self.api; let types = (api.objects.iter().enumerate()).map(|(i, o)| (Type::Object(i), &o.methods, o.traits)); let types = types.chain((api.records.iter().enumerate()).map(|(i, r)| (Type::Record(i), &r.methods, r.traits))); @@ -471,8 +782,8 @@ impl<'tcx> Collector<'tcx> { } self.decls .iter() - .filter_map(|(&def_id, decl)| match decl { - Decl::Object(i) if !held[*i] => Some(def_id), + .filter_map(|(&key, decl)| match decl { + Decl::Object(i) if !held[*i] => Some(key), _ => None, }) .collect() @@ -482,20 +793,20 @@ impl<'tcx> Collector<'tcx> { fn settle(&mut self) { loop { let mut changed = false; - for (def_id, path) in self.items.clone() { - if !matches!(self.decls.get(&def_id), Some(Decl::Record(_) | Decl::Enum(_))) { + for site in self.all_sites() { + if !matches!(self.decls.get(&site.key), Some(Decl::Record(_) | Decl::Enum(_))) { continue; } - let fields = match self.recursive(def_id) { + let fields = match self.recursive(&site) { true => Err(vec![why("recursive value", "")]), - false => self.fields(def_id).map(|_| ()), + false => self.fields(&site).map(|_| ()), }; if let Err(why) = fields { let first = why.into_iter().next().expect("a refusal has a reason"); - let (report, rest) = self.report(&path); + let (report, rest) = self.report(&site.shown); report.opaque.push((rest, first)); - let decl = self.object(def_id); - self.decls.insert(def_id, decl); + let decl = self.object(&site); + self.decls.insert(site.key, decl); changed = true; } } @@ -505,32 +816,43 @@ impl<'tcx> Collector<'tcx> { } } + /// Every type and trait the export declares, in item order. + fn all_sites(&self) -> Vec> { + (self.items.iter()) + .filter(|(def_id, _)| { + matches!( + self.tcx.def_kind(*def_id), + DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait + ) + }) + .flat_map(|(def_id, path)| self.sites(*def_id, path)) + .collect() + } + /// Whether a value holds itself, through other values, an `Option`, or a `Box`: C /// holds each value in place, so it cannot. - fn recursive(&self, start: DefId) -> bool { + fn recursive(&self, start: &Site<'tcx>) -> bool { let tcx = self.tcx; let mut seen = rustc_data_structures::fx::FxHashSet::default(); - let mut stack = vec![start]; - while let Some(def_id) = stack.pop() { - let adt = tcx.adt_def(def_id); - let identity = ty::GenericArgs::identity_for_item(tcx, def_id); - for field in adt.all_fields() { - for arg in field.ty(tcx, identity).skip_norm_wip().walk() { + let mut stack = vec![(start.key.def_id, start.args)]; + while let Some((def_id, args)) = stack.pop() { + for field in tcx.adt_def(def_id).all_fields() { + for arg in field.ty(tcx, args).skip_norm_wip().walk() { let Some(ty) = arg.as_type() else { continue; }; - let ty::Adt(inner, _) = ty.kind() else { + let ty::Adt(inner, inner_args) = ty.kind() else { continue; }; - let did = inner.did(); - if !matches!(self.decls.get(&did), Some(Decl::Record(_) | Decl::Enum(_))) { + let key = self.key(inner.did(), inner_args); + if !matches!(self.decls.get(&key), Some(Decl::Record(_) | Decl::Enum(_))) { continue; } - if did == start { + if key == start.key { return true; } - if seen.insert(did) { - stack.push(did); + if seen.insert(key) { + stack.push((inner.did(), inner_args)); } } } @@ -539,10 +861,10 @@ impl<'tcx> Collector<'tcx> { } /// A struct's or enum's variants, with their fields mapped. - fn fields(&self, def_id: DefId) -> Result, Vec> { + fn fields(&self, site: &Site<'tcx>) -> Result, Vec> { let tcx = self.tcx; - let adt = tcx.adt_def(def_id); - let identity = ty::GenericArgs::identity_for_item(tcx, def_id); + let adt = tcx.adt_def(site.key.def_id); + let identity = site.args; let mut errs = Vec::new(); let mut variants = Vec::new(); let discriminants: Vec = match adt.is_enum() { @@ -585,84 +907,97 @@ impl<'tcx> Collector<'tcx> { for (def_id, path) in self.items.clone() { let span = tcx.def_span(def_id); let kind = tcx.def_kind(def_id); - match self.decls.get(&def_id).cloned() { - Some(Decl::Refused(why)) => { + if !matches!(kind, DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait) { + match kind { + DefKind::Fn => match self.function(def_id, path.clone(), None, None) { + Ok(function) => self.api.functions.push(function), + Err(why) => self.refuse(&path, "fn", span, why), + }, + DefKind::Const => { + if let Some(getter) = self.constant_item(def_id, path, None) { + self.api.functions.push(getter); + } + } + _ => {} + } + continue; + } + for site in self.sites(def_id, &path) { + let decl = self.decls.get(&site.key).cloned(); + if let Some(Decl::Refused(why)) = decl { let kind = match kind { + _ if site.key.args.is_some() => "instance", DefKind::Trait => "trait", DefKind::Enum => "enum", DefKind::Union => "union", _ => "struct", }; - self.refuse(&path, kind, span, vec![why]); - } - Some(Decl::Record(index)) => { - let variants = self.fields(def_id).expect("settled"); - let variant = variants.into_iter().next().expect("a struct has a variant"); - let (methods, traits) = self.methods(def_id, &path); - let record = &mut self.api.records[index]; - record.fields = variant.fields; - record.tuple = variant.tuple; - record.methods = methods; - record.traits = traits; - } - Some(Decl::Enum(index)) => { - let variants = self.fields(def_id).expect("settled"); - let exhaustive = !tcx.adt_def(def_id).is_variant_list_non_exhaustive(); - let (methods, traits) = self.methods(def_id, &path); - let e = &mut self.api.enums[index]; - e.variants = variants; - e.exhaustive = exhaustive; - e.methods = methods; - e.traits = traits; - } - Some(Decl::Object(index)) => { - let (mut methods, traits) = self.methods(def_id, &path); - if kind == DefKind::Struct { - methods.splice(0..0, self.getters(def_id, &path)); - } - let object = &mut self.api.objects[index]; - object.methods = methods; - object.traits = traits; + self.refuse(&site.shown, kind, span, vec![why]); + continue; } - Some(Decl::Callback(index)) => { + if let Some(Decl::Callback(index)) = decl { self.api.callbacks[index].methods = self.callback(def_id, &path).expect("settled"); + continue; } - None => match kind { - DefKind::Fn => match self.function(def_id, path.clone(), None) { - Ok(function) => self.api.functions.push(function), - Err(why) => self.refuse(&path, "fn", span, why), - }, - DefKind::Const => { - if let Some(getter) = self.constant_item(def_id, path) { - self.api.functions.push(getter); + let args = self.args(&site).expect("settled"); + match decl { + Some(Decl::Record(index)) => { + let variants = self.fields(&site).expect("settled"); + let variant = variants.into_iter().next().expect("a struct has a variant"); + let (methods, traits) = self.methods(&site); + let record = &mut self.api.records[index]; + record.args = args; + record.fields = variant.fields; + record.tuple = variant.tuple; + record.methods = methods; + record.traits = traits; + } + Some(Decl::Enum(index)) => { + let variants = self.fields(&site).expect("settled"); + let exhaustive = !tcx.adt_def(def_id).is_variant_list_non_exhaustive(); + let (methods, traits) = self.methods(&site); + let e = &mut self.api.enums[index]; + e.args = args; + e.variants = variants; + e.exhaustive = exhaustive; + e.methods = methods; + e.traits = traits; + } + Some(Decl::Object(index)) => { + let (mut methods, traits) = self.methods(&site); + if kind == DefKind::Struct { + methods.splice(0..0, self.getters(&site)); } + let object = &mut self.api.objects[index]; + object.args = args; + object.methods = methods; + object.traits = traits; } _ => {} - }, + } } } } /// A getter for each `pub` field of a struct exported as an object, returning a copy. - fn getters(&mut self, def_id: DefId, path: &[String]) -> Vec { + fn getters(&mut self, site: &Site<'tcx>) -> Vec { let tcx = self.tcx; - let identity = statics(tcx, def_id); let mut getters = Vec::new(); - for field in &tcx.adt_def(def_id).non_enum_variant().fields { + for field in &tcx.adt_def(site.key.def_id).non_enum_variant().fields { if !field.vis.is_public() { continue; } - let mut getter = path.to_vec(); - getter.push(field.name.to_string()); - if self.exclude(&getter) { + let name = field.name.to_string(); + let shown = [&site.shown[..], std::slice::from_ref(&name)].concat(); + if self.exclude(&shown) { continue; } let span = tcx.def_span(field.did); - let ty = field.ty(tcx, identity).skip_norm_wip(); + let ty = field.ty(tcx, site.args).skip_norm_wip(); // Read through `&self`, so returned as a copy, as a borrowed return is. match self.ty(Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty), Pos::Return) { Ok(ty) => getters.push(Function { - path: getter, + path: [&site.path[..], &[name]].concat(), span, docs: docs(tcx, field.did), receiver: Some(Receiver::Ref), @@ -673,22 +1008,24 @@ impl<'tcx> Collector<'tcx> { eager: false, access: Access::Field, }), - Err(why) => self.refuse(&getter, "field", span, vec![why]), + Err(why) => self.refuse(&shown, "field", span, vec![why]), } } getters } - /// A type's inherent `pub` methods, and the std traits it implements. - fn methods(&mut self, def_id: DefId, path: &[String]) -> (Vec, Traits) { + /// A type's inherent `pub` methods, from each impl that applies to it, and the std + /// traits it implements. + fn methods(&mut self, site: &Site<'tcx>) -> (Vec, Traits) { let tcx = self.tcx; + let def_id = site.key.def_id; let mut methods = Vec::new(); let mut refused = Vec::new(); - let self_ty = tcx - .type_of(def_id) - .instantiate(tcx, statics(tcx, def_id)) - .skip_norm_wip(); + let self_ty = self.site_ty(site); for &imp in tcx.inherent_impls(def_id) { + let Some(parent) = self.impl_args(imp, self_ty) else { + continue; + }; for item in tcx.associated_items(imp).in_definition_order() { let (ty::AssocKind::Fn { name, .. } | ty::AssocKind::Const { name, .. }) = item.kind else { continue; @@ -696,24 +1033,34 @@ impl<'tcx> Collector<'tcx> { if !tcx.visibility(item.def_id).is_public() { continue; } - let mut method = path.to_vec(); - method.push(name.to_string()); - if self.exclude(&method) { + let method = [&site.path[..], &[name.to_string()]].concat(); + let shown = [&site.shown[..], &[name.to_string()]].concat(); + if self.exclude(&shown) { continue; } if tcx.is_doc_hidden(item.def_id) { - let (report, rest) = self.report(&method); + let (report, rest) = self.report(&shown); report.hidden.push(rest); continue; } + // As an impl whose bounds fail, a method whose own bounds fail at the + // instance is none of its methods. + if !self.applies(item.def_id, parent) { + continue; + } let span = tcx.def_span(item.def_id); if let ty::AssocKind::Const { .. } = item.kind { - methods.extend(self.constant_item(item.def_id, method)); + // An instance's constant is read in Rust, named through the instance. + let parent = site.key.args.map(|_| parent); + methods.extend(self.constant_item(item.def_id, shown, parent).map(|mut getter| { + getter.path = method; + getter + })); continue; } - match self.function(item.def_id, method.clone(), Some(self_ty)) { + match self.function(item.def_id, method, Some(self_ty), Some(parent)) { Ok(function) => methods.push(function), - Err(why) => refused.push((method, span, why)), + Err(why) => refused.push((shown, span, why)), } } } @@ -755,6 +1102,47 @@ impl<'tcx> Collector<'tcx> { (methods, traits) } + /// The arguments an inherent impl applies to `self_ty` at, if it does: its type + /// parameters as `self_ty` fixes them, its lifetimes as they are, and its bounds met. + fn impl_args(&self, imp: DefId, self_ty: Ty<'tcx>) -> Option> { + let tcx = self.tcx; + let mut args = ty::GenericArgs::identity_for_item(tcx, imp).to_vec(); + let pattern = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + if !matches(tcx, pattern, self_ty, &mut args) { + return None; + } + let args = tcx.mk_args(&args); + let env = TypingEnv::post_analysis(tcx, imp); + let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); + let holds = tcx.clauses_of(imp).instantiate(tcx, args).clauses.iter().all(|clause| { + let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause.skip_norm_wip()); + infcx.predicate_must_hold_modulo_regions(&obligation) + }); + holds.then_some(args) + } + + /// Whether an impl item's bounds hold with the impl's parameters at `parent`. A bound on + /// the item's own type parameters is the choice of a type for each. + fn applies(&self, item: DefId, parent: ty::GenericArgsRef<'tcx>) -> bool { + let tcx = self.tcx; + let mut args = ty::GenericArgs::identity_for_item(tcx, item).to_vec(); + args[..parent.len()].copy_from_slice(parent); + let args = tcx.mk_args(&args); + let env = TypingEnv::post_analysis(tcx, item); + let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); + tcx.clauses_of(item) + .instantiate(tcx, args) + .clauses + .iter() + .all(|clause| { + let clause = clause.skip_norm_wip(); + clause.has_non_region_param() || { + let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause); + infcx.predicate_must_hold_modulo_regions(&obligation) + } + }) + } + /// A trait's required methods, as a callback interface. fn callback(&mut self, def_id: DefId, path: &[String]) -> Result, Vec> { let tcx = self.tcx; @@ -787,7 +1175,7 @@ impl<'tcx> Collector<'tcx> { } let mut method = path.to_vec(); method.push(name.to_string()); - match self.function(item.def_id, method, Some(self_ty)) { + match self.function(item.def_id, method, Some(self_ty), None) { Ok(function) if function.future => errs.push(why("async trait method", name.to_string())), Ok(function) if !function.params.iter().all(|p| foreign_arg(&p.ty)) @@ -817,12 +1205,19 @@ impl<'tcx> Collector<'tcx> { } } - /// A function or method's signature, with its type parameters chosen. - fn function(&self, def_id: DefId, path: Path, self_ty: Option>) -> Result> { + /// A function or method's signature, with its type parameters chosen: a method's + /// receiver is `self_ty`, at its impl's `parent` arguments. + fn function( + &self, + def_id: DefId, + path: Path, + self_ty: Option>, + parent: Option>, + ) -> Result> { let tcx = self.tcx; let mut errs = Vec::new(); self.impls.borrow_mut().clear(); - let args = self.instantiate(def_id, self_ty)?; + let args = self.instantiate(def_id, parent)?; let env = TypingEnv::post_analysis(tcx, def_id); let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(); let (statics, lifetimes) = self.borrows(def_id, sig.skip_binder()); @@ -926,24 +1321,31 @@ impl<'tcx> Collector<'tcx> { } } - /// The generic arguments a function is exported with: its parent's own (a trait's - /// `Self`), lifetimes as they are, which [`Self::borrows`] decides, and each type + /// The generic arguments a function is exported with: its parent's (an impl's at the + /// instance, or a trait's `Self`, which stays a parameter, as the trait is the + /// callback), lifetimes as they are, which [`Self::borrows`] decides, and each type /// parameter by the rules in [`Self::choose`]. - fn instantiate(&self, def_id: DefId, self_ty: Option>) -> Result, Vec> { + fn instantiate( + &self, + def_id: DefId, + parent: Option>, + ) -> Result, Vec> { let tcx = self.tcx; let generics = tcx.generics_of(def_id); let identity = ty::GenericArgs::identity_for_item(tcx, def_id); let mut errs = Vec::new(); let mut args: Vec> = identity.to_vec(); - let parent = generics.parent_count; - // A trait method's `Self` stays a parameter: the trait is the callback. - let _ = self_ty; + let count = generics.parent_count; + if let Some(parent) = parent { + args[..count].copy_from_slice(parent); + } + let base = args.clone(); for (i, arg) in identity.iter().enumerate() { match arg.kind() { - _ if i < parent => {} + _ if i < count => {} GenericArgKind::Lifetime(_) => {} GenericArgKind::Const(_) => errs.push(why("const generic", "")), - GenericArgKind::Type(param) => match self.choose(def_id, param) { + GenericArgKind::Type(param) => match self.choose(def_id, param, &base) { Ok(ty) => args[i] = ty.into(), // The parameter stays, and `ty` maps it to the foreign implementation. Err(Why { @@ -965,10 +1367,10 @@ impl<'tcx> Collector<'tcx> { /// The type a type parameter is exported as: `X` for `impl Into` or /// `impl AsRef`, else the first of `String`, `Bytes`, and `Vec` meeting its /// bounds. - fn choose(&self, def_id: DefId, param: Ty<'tcx>) -> Result, Why> { + fn choose(&self, def_id: DefId, param: Ty<'tcx>, base: &[ty::GenericArg<'tcx>]) -> Result, Why> { let tcx = self.tcx; let clauses = tcx.clauses_of(def_id); - let identity = clauses.instantiate_identity(tcx); + let identity = clauses.instantiate(tcx, tcx.mk_args(base)); let bounds: Vec<_> = identity .clauses .iter() @@ -1015,21 +1417,24 @@ impl<'tcx> Collector<'tcx> { } } let env = TypingEnv::post_analysis(tcx, def_id); - for candidate in candidates { + let ty::Param(p) = param.kind() else { + unreachable!("a generic type argument is a parameter"); + }; + // The arguments with `param` as `candidate`, if its bounds hold there. + let at = |candidate: Ty<'tcx>| { let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); - let mut args: Vec> = ty::GenericArgs::identity_for_item(tcx, def_id).to_vec(); - let ty::Param(p) = param.kind() else { - unreachable!("a generic type argument is a parameter"); - }; + let mut args = base.to_vec(); args[p.index as usize] = candidate.into(); - let instantiated = clauses.instantiate(tcx, tcx.mk_args(&args)); - let holds = instantiated.clauses.iter().all(|clause| { - let clause = clause.skip_norm_wip(); - let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause); + let args = tcx.mk_args(&args); + let holds = clauses.instantiate(tcx, args).clauses.iter().all(|clause| { + let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause.skip_norm_wip()); infcx.predicate_must_hold_modulo_regions(&obligation) }); + holds.then_some(args) + }; + for &candidate in &candidates { // `impl Into>` takes a `String` too, which maps where `Arc` does not. - if holds && self.ty(candidate, Pos::Param).is_ok() { + if at(candidate).is_some() && self.ty(candidate, Pos::Param).is_ok() { return Ok(candidate); } } @@ -1037,7 +1442,7 @@ impl<'tcx> Collector<'tcx> { let local: Vec<_> = bounds .iter() .map(|b| b.def_id()) - .filter(|tr| matches!(self.decls.get(tr), Some(Decl::Callback(_)))) + .filter(|tr| matches!(self.trait_decl(*tr), Some(Decl::Callback(_)))) .collect(); let sized = [tcx.lang_items().sized_trait(), tcx.lang_items().meta_sized_trait()]; let names: Vec = bounds @@ -1045,9 +1450,59 @@ impl<'tcx> Collector<'tcx> { .filter(|b| !sized.contains(&Some(b.def_id()))) .map(|b| tcx.def_path_str(b.def_id())) .collect(); - match local.as_slice() { - [_] => Err(why("callback bound", names.join(" + "))), - _ => Err(why("generic parameter", names.join(" + "))), + if let [_] = local.as_slice() { + return Err(why("callback bound", names.join(" + "))); + } + // Else, for a parameter of an exported type the signature names, the one argument of + // an instance the config names that meets its bounds, and makes each exported type + // the signature names an instance the config names. + let exported = |ty: Ty<'tcx>| match ty.kind() { + ty::Adt(adt, args) if self.exported(adt.did().krate) && self.typed(adt.did()) => Some((adt.did(), args)), + _ => None, + }; + // Each type the signature names, with what a returned future resolves to. + let spelled = |args: ty::GenericArgsRef<'tcx>| { + let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(); + let sig = tcx.instantiate_bound_regions_with_erased(sig); + let output = self.future_output(sig.output(), env); + let types: Vec> = (sig.inputs_and_output.iter().chain(output)) + .flat_map(|ty| ty.walk()) + .filter_map(|arg| arg.as_type()) + .collect(); + types + }; + let mut found: Vec> = Vec::new(); + let argument = spelled(tcx.mk_args(base)) + .into_iter() + .filter_map(exported) + .any(|(_, args)| args.iter().any(|arg| arg.walk().any(|a| a == param.into()))); + for instance in self.instances.iter().filter(|_| argument) { + for candidate in instance.site.args.types() { + let erased = tcx.erase_and_anonymize_regions(candidate); + if found.iter().any(|&f| tcx.erase_and_anonymize_regions(f) == erased) { + continue; + } + let Some(args) = at(candidate) else { + continue; + }; + let named = spelled(args).into_iter().filter_map(exported).all(|(adt, args)| { + matches!( + self.decl(adt, args), + Some(Decl::Record(_) | Decl::Enum(_) | Decl::Object(_)) + ) + }); + if named { + found.push(candidate); + } + } + } + match found.as_slice() { + [one] => Ok(*one), + [] => Err(why("generic parameter", names.join(" + "))), + _ => { + let found: Vec = found.iter().map(|&ty| self.spell(ty)).collect(); + Err(why("generic parameter of several instances", found.join(", "))) + } } } @@ -1068,7 +1523,7 @@ impl<'tcx> Collector<'tcx> { .iter() .any(|&item| tcx.is_diagnostic_item(item, tr)) || [tcx.lang_items().sized_trait(), tcx.lang_items().meta_sized_trait()].contains(&Some(tr)); - match self.decls.get(&tr) { + match self.trait_decl(tr) { Some(Decl::Callback(i)) if callback.is_none() => callback = Some(*i), _ if met => {} _ => return None, @@ -1186,7 +1641,7 @@ impl<'tcx> Collector<'tcx> { for ty in ty.walk().filter_map(|arg| arg.as_type()) { match ty.kind() { ty::Ref(region, ..) => lent.push(*region), - ty::Adt(adt, args) if matches!(self.decls.get(&adt.did()), Some(Decl::Object(_))) => { + ty::Adt(adt, args) if matches!(self.decl(adt.did(), args), Some(Decl::Object(_))) => { held.extend(args.regions()) } // An `impl Future` holds what its bounds name, as an `async fn` its output. @@ -1256,8 +1711,9 @@ 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() { - ty::Adt(adt, _) => { - matches!(self.decls.get(&adt.did()), Some(Decl::Object(_))) && !implements(tcx, adt.did(), sym::Copy) + ty::Adt(adt, args) => { + matches!(self.decl(adt.did(), args), Some(Decl::Object(_))) + && !implements(tcx, ty, adt.did(), sym::Copy) } _ => false, }) @@ -1286,27 +1742,38 @@ impl<'tcx> Collector<'tcx> { } /// A constant: a C constant if a `bool` or integer, or else a function returning it, - /// which the caller adds. - fn constant_item(&mut self, def_id: DefId, path: Path) -> Option { + /// which the caller adds. One of an instance's impl, at its `parent` arguments, is + /// always a function, as its value may differ by instance. + fn constant_item( + &mut self, + def_id: DefId, + path: Path, + parent: Option>, + ) -> Option { let tcx = self.tcx; let span = tcx.def_span(def_id); - let why = match self.constant(def_id) { - Ok(value) => { - self.api.constants.push(Constant { - path, - span, - docs: docs(tcx, def_id), - value, - }); - return None; + let ty = match parent { + Some(parent) => tcx.type_of(def_id).instantiate(tcx, parent).skip_norm_wip(), + None => { + let why = match self.constant(def_id) { + Ok(value) => { + self.api.constants.push(Constant { + path, + span, + docs: docs(tcx, def_id), + value, + }); + return None; + } + Err(why) => why, + }; + if why.construct != "constant type" { + self.refuse(&path, "const", span, vec![why]); + return None; + } + tcx.type_of(def_id).instantiate_identity().skip_norm_wip() } - Err(why) => why, }; - let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip(); - if why.construct != "constant type" { - self.refuse(&path, "const", span, vec![why]); - return None; - } match self.ty(ty, Pos::Return) { Ok(ok) => Some(Function { path, @@ -1447,22 +1914,35 @@ impl<'tcx> Collector<'tcx> { } else if !self.exported(did.krate) { return Err(why("foreign type", strip_args(tcx, did))); } else { - match self.decls.get(&did) { + let key = self.key(did, args); + // An instance is named as its key would spell it. + let name = match key.args { + Some(_) => self.spell(ty), + None => tcx.def_path_str(did), + }; + match self.decls.get(&key) { Some(Decl::Record(i)) => Type::Record(*i), Some(Decl::Enum(i)) => Type::Enum(*i), // A value holds only values, and handles it can copy. - Some(Decl::Object(_)) if pos == Pos::Field && !implements(tcx, did, sym::Copy) => { - return Err(why("object in a value", tcx.def_path_str(did))); + Some(Decl::Object(_)) if pos == Pos::Field && !implements(tcx, ty, did, sym::Copy) => { + return Err(why("object in a value", name)); } Some(Decl::Object(i)) => Type::Object(*i), - Some(Decl::Refused(_)) => return Err(why("refused type", tcx.def_path_str(did))), + Some(Decl::Refused(_)) => return Err(why("refused type", name)), Some(Decl::Callback(_)) | None => { - let construct = self - .left_out - .get(&did) - .copied() - .unwrap_or("type not reachable from the crate root"); - return Err(why(construct, tcx.def_path_str(did))); + if let Some(construct) = self.left_out.get(&did) { + return Err(why(construct, name)); + } + if key.args.is_none() { + return Err(why("type not reachable from the crate root", name)); + } + let mut why = why("instance the config does not name", name); + let note = format!( + "`{}` exports only at the instances the config names", + strip_args(tcx, did) + ); + why.note = Some((tcx.def_span(did), note)); + return Err(why); } } } @@ -1494,7 +1974,7 @@ impl<'tcx> Collector<'tcx> { /// A trait object of one of the crate's traits, as a foreign implementation. /// A foreign implementation crosses only into Rust, as a parameter. fn dynamic(&self, principal: Option, form: Dyn, ty: Ty<'tcx>, pos: Pos) -> Result { - match principal.and_then(|tr| self.decls.get(&tr)) { + match principal.and_then(|tr| self.trait_decl(tr)) { Some(Decl::Callback(i)) if pos == Pos::Param => Ok(Type::Callback(*i, form)), _ => Err(why("trait object", ty.to_string())), } @@ -1636,9 +2116,8 @@ fn docs(tcx: TyCtxt<'_>, def_id: DefId) -> String { lines.join("\n").trim().to_string() } -/// Whether the local type `def_id` implements the std trait `item`. -fn implements(tcx: TyCtxt<'_>, def_id: DefId, item: rustc_span::Symbol) -> bool { - let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip(); +/// Whether `ty`, the type `def_id` at some arguments, implements the std trait `item`. +fn implements<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, def_id: DefId, item: rustc_span::Symbol) -> bool { let Some(tr) = tcx.get_diagnostic_item(item) else { return false; }; @@ -1648,6 +2127,35 @@ fn implements(tcx: TyCtxt<'_>, def_id: DefId, item: rustc_span::Symbol) -> bool infcx.type_implements_trait(tr, [ty], env).must_apply_modulo_regions() } +/// Whether `ty` is an instance of an impl's self type `pattern`, binding each of the +/// impl's type parameters in `args`, which starts as its identity. An instance's +/// arguments are never references or tuples but `()`, so structure decides it; lifetimes +/// stay as the impl names them. +fn matches<'tcx>(tcx: TyCtxt<'tcx>, pattern: Ty<'tcx>, ty: Ty<'tcx>, args: &mut [ty::GenericArg<'tcx>]) -> bool { + match (pattern.kind(), ty.kind()) { + (ty::Param(param), _) => { + let slot = &mut args[param.index as usize]; + match slot.as_type() == Some(pattern) { + true => { + *slot = ty.into(); + true + } + false => { + slot.as_type().map(|bound| tcx.erase_and_anonymize_regions(bound)) + == Some(tcx.erase_and_anonymize_regions(ty)) + } + } + } + (ty::Adt(a, pattern_args), ty::Adt(b, ty_args)) if a.did() == b.did() => { + (pattern_args.iter().zip(ty_args.iter())).all(|(p, t)| match (p.as_type(), t.as_type()) { + (Some(p), Some(t)) => matches(tcx, p, t, args), + _ => true, + }) + } + _ => tcx.erase_and_anonymize_regions(pattern) == tcx.erase_and_anonymize_regions(ty), + } +} + /// A type's own generic arguments as it is exported: its lifetimes `'static`. fn statics<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::GenericArgsRef<'tcx> { ty::GenericArgs::for_item(tcx, def_id, |param, _| match param.kind { diff --git a/ffi/src/config.rs b/ffi/src/config.rs index 9c9043db0..b45248765 100644 --- a/ffi/src/config.rs +++ b/ffi/src/config.rs @@ -23,14 +23,21 @@ pub struct Config { /// named through its new name. #[serde(default)] pub rename: BTreeMap, + /// Generic types exported at instances, each with its C name, without the prefix: + /// `"Stack" = "size_stack"`. The type's path is from the crate + /// root, as every key's; each argument is `()`, a primitive, `String`, or an exported + /// type by its path from its package's name in snake case, itself an instance if + /// generic. Trailing arguments left out take their defaults. + #[serde(default)] + pub instances: BTreeMap, /// Other packages exported into the same library, each a dependency of `package`, by /// name: an export names another's types across crates. #[serde(default)] pub crates: BTreeMap, } -/// What leaves another export's items out, and renames them, as `exclude` and `rename` -/// do the package's. +/// What leaves another export's items out, renames them, and names its instances, as +/// `exclude`, `rename`, and `instances` do the package's. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct Items { @@ -38,6 +45,8 @@ pub struct Items { pub exclude: Vec, #[serde(default)] pub rename: BTreeMap, + #[serde(default)] + pub instances: BTreeMap, } impl Config { @@ -51,6 +60,10 @@ impl Config { config.package )); } + let tables = std::iter::once(&config.instances).chain(config.crates.values().map(|items| &items.instances)); + for key in tables.flat_map(BTreeMap::keys) { + TypeName::parse(key).map_err(|err| format!("{}: instance `{key}`: {err}", path.display()))?; + } Ok(config) } @@ -60,6 +73,76 @@ impl Config { } } +/// A type as an instance's key spells it: a path and its generic arguments, or `()` when +/// the path is empty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TypeName { + pub path: Vec, + pub args: Vec, +} + +impl TypeName { + /// The type `text` spells, or why it spells none. + pub fn parse(text: &str) -> Result { + let mut rest = text; + let name = Self::parse_from(&mut rest)?; + match rest.trim_start() { + "" => Ok(name), + extra => Err(format!("unexpected `{extra}`")), + } + } + + /// The type `rest` starts with, which it advances past. + fn parse_from(rest: &mut &str) -> Result { + fn eat(rest: &mut &str, token: &str) -> bool { + *rest = rest.trim_start(); + let found = rest.starts_with(token); + if found { + *rest = &rest[token.len()..]; + } + found + } + if eat(rest, "(") { + return match eat(rest, ")") { + true => Ok(Self { + path: Vec::new(), + args: Vec::new(), + }), + false => Err("a tuple other than `()`".to_string()), + }; + } + let mut path = Vec::new(); + loop { + *rest = rest.trim_start(); + let len = rest + .find(|c: char| !(c.is_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + let ident = &rest[..len]; + if ident.is_empty() || ident.starts_with(|c: char| c.is_ascii_digit()) { + return Err(format!("expected a path at `{rest}`")); + } + path.push(ident.to_string()); + *rest = &rest[len..]; + if !eat(rest, "::") { + break; + } + } + let mut args = Vec::new(); + if eat(rest, "<") { + loop { + args.push(Self::parse_from(rest)?); + if eat(rest, ">") { + break; + } + if !eat(rest, ",") { + return Err(format!("expected `,` or `>` at `{rest}`")); + } + } + } + Ok(Self { path, args }) + } +} + /// An export's package, as the CLI resolves it for the wrapper. pub struct Package { pub name: String, diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index fb7a6982a..9bf4e862a 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -103,7 +103,7 @@ impl Callbacks for Export { renames.insert(format!("{}::{path}", report.krate), name.clone()); } } - let abi = Abi::new(&collected.api, &self.config.prefix(), &renames); + let abi = Abi::new(&collected.api, &self.config.prefix(), &renames, &collected.instances); for key in abi.unused_renames() { let (krate, path) = key.split_once("::").expect("a rename starts with its crate"); tcx.dcx().err(format!( @@ -111,6 +111,22 @@ impl Callbacks for Export { self.table(&collected, krate) )); } + for report in &collected.reports { + for (key, why, span) in &report.unresolved { + let message = format!( + "rust2-ffi: instance `{key}` in {} exports nothing: {why}", + self.table(&collected, &report.krate) + ); + match span { + Some(span) => { + tcx.dcx().struct_span_err(*span, message).emit(); + } + None => { + tcx.dcx().err(message); + } + }; + } + } let written = match &self.output { Output::Census(dir) => collected.reports.iter().enumerate().try_for_each(|(i, report)| { let text = census::render(&collected.api, report, i == 0, &abi.clashes, &|span| at(tcx, span)); @@ -128,10 +144,15 @@ impl Callbacks for Export { false => format!("{} `{}`", why.construct, why.detail), }) .collect(); + // An instance is left out by not naming it. + let fix = match refusal.kind { + "instance" => format!("drop it from {table}'s `instances`"), + _ => format!("exclude it in {table} to leave it out"), + }; let mut err = tcx.dcx().struct_span_err( refusal.span, format!( - "rust2-ffi: cannot export {} `{}`: {}; exclude it in {table} to leave it out", + "rust2-ffi: cannot export {} `{}`: {}; {fix}", refusal.kind, refusal.path, reasons.join("; ") @@ -225,16 +246,17 @@ impl Export { Output::Census(_) => &[], Output::Dir(_) => self.items(package).0, }, + instances: self.items(package).2, }); } Some(crates) } - /// The config's `exclude` and `rename` for `package`. - fn items(&self, package: &str) -> (&[String], &BTreeMap) { + /// The config's `exclude`, `rename`, and `instances` for `package`. + fn items(&self, package: &str) -> (&[String], &BTreeMap, &BTreeMap) { match self.config.crates.get(package) { - Some(items) => (&items.exclude, &items.rename), - None => (&self.config.exclude, &self.config.rename), + Some(items) => (&items.exclude, &items.rename, &items.instances), + None => (&self.config.exclude, &self.config.rename, &self.config.instances), } } diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index bca9009b2..dd6014c77 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -21,27 +21,6 @@ fn dependency(krate: &str) -> String { format!("{krate}_export") } -/// The Rust spelling of a type a callback's method takes or returns. -fn rust(ty: &Type) -> String { - match ty { - Type::Unit => "()".to_string(), - Type::Bool => "bool".to_string(), - Type::Int(int) => int.rust().to_string(), - Type::F32 => "f32".to_string(), - Type::F64 => "f64".to_string(), - Type::Char => "char".to_string(), - Type::Str => "str".to_string(), - Type::String => "::std::string::String".to_string(), - Type::Slice => "[u8]".to_string(), - Type::Vec => "::std::vec::Vec".to_string(), - Type::Bytes => "::bytes::Bytes".to_string(), - Type::Duration => "::std::time::Duration".to_string(), - Type::Option(inner) => format!("Option<{}>", rust(inner)), - Type::Ref(Mutability::Not, inner) => format!("&{}", rust(inner)), - other => unreachable!("a callback never takes {other:?}"), - } -} - /// The crate that builds the C ABI. pub struct Crate<'a> { pub abi: &'a Abi<'a>, @@ -135,11 +114,41 @@ impl Gen<'_> { /// An object's Rust type: its lifetimes `'static`, as the handle holds it. fn object_path(&self, i: usize) -> String { - let object = &self.abi.api.objects[i]; - let path = self.path(&object.path); - match object.lifetimes { - 0 => path, - n => format!("{path}<{}>", vec!["'static"; n].join(", ")), + self.rust(&Type::Object(i)) + } + + /// The Rust spelling of a type a callback's method takes or returns, or a type + /// argument: a type with its instance's arguments, and an object's lifetimes `'static`. + fn rust(&self, ty: &Type) -> String { + let api = self.abi.api; + let generic = |path: &[String], lifetimes: usize, args: &[Type]| { + let path = self.path(path); + let mut params = vec!["'static".to_string(); lifetimes]; + params.extend(args.iter().map(|arg| self.rust(arg))); + match params.is_empty() { + true => path, + false => format!("{path}::<{}>", params.join(", ")), + } + }; + match ty { + Type::Unit => "()".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::F32 => "f32".to_string(), + Type::F64 => "f64".to_string(), + Type::Char => "char".to_string(), + Type::Str => "str".to_string(), + Type::String => "::std::string::String".to_string(), + Type::Slice => "[u8]".to_string(), + Type::Vec => "::std::vec::Vec".to_string(), + Type::Bytes => "::bytes::Bytes".to_string(), + Type::Duration => "::std::time::Duration".to_string(), + Type::Option(inner) => format!("Option<{}>", self.rust(inner)), + Type::Ref(Mutability::Not, inner) => format!("&{}", self.rust(inner)), + Type::Record(i) => generic(&api.records[*i].path, 0, &api.records[*i].args), + Type::Enum(i) => generic(&api.enums[*i].path, 0, &api.enums[*i].args), + Type::Object(i) => generic(&api.objects[*i].path, api.objects[*i].lifetimes, &api.objects[*i].args), + other => unreachable!("no callback or type argument is {other:?}"), } } @@ -359,7 +368,7 @@ impl Gen<'_> { constant: false, }; for method in &object.methods { - self.function(method, Some((&owner, Some(i)))); + self.function(method, Some((&owner, Type::Object(i)))); } } for function in &api.functions { @@ -441,7 +450,7 @@ impl Gen<'_> { fn record(&mut self, i: usize) { let record = &self.abi.api.records[i]; let name = self.abi.record(i); - let path = self.path(&record.path); + let path = self.rust(&Type::Record(i)); let ty = Type::Record(i); let mut fields = String::new(); for (n, field) in record.fields.iter().enumerate() { @@ -506,14 +515,14 @@ impl Gen<'_> { self.value_traits(&name, &path, &ty, record.traits); let owner = Ty::Struct(name.clone()); for method in &record.methods { - self.function(method, Some((&owner, None))); + self.function(method, Some((&owner, ty.clone()))); } } fn enumeration(&mut self, i: usize) { let e = &self.abi.api.enums[i]; let name = self.abi.enumeration(i); - let path = self.path(&e.path); + let path = self.rust(&Type::Enum(i)); let ty = Type::Enum(i); let wildcard = match e.exhaustive { true => "", @@ -646,7 +655,7 @@ impl Gen<'_> { self.value_traits(&name, &path, &ty, e.traits); let owner = self.abi.ty(&ty); for method in &e.methods { - self.function(method, Some((&owner, None))); + self.function(method, Some((&owner, ty.clone()))); } } @@ -677,7 +686,7 @@ impl Gen<'_> { .params .iter() .enumerate() - .map(|(n, p)| format!("p{n}: {}", rust(&p.ty))) + .map(|(n, p)| format!("p{n}: {}", self.rust(&p.ty))) .collect(); let args: Vec = std::iter::once("self.0.data".to_string()) .chain( @@ -692,7 +701,7 @@ impl Gen<'_> { methods, "\tfn {method_name}({receiver}{}) -> {} {{\n\t\tlet w = \"{name}_vtable.{method_name}\";\n\t\tlet f = unsafe {{ (*self.0.vtable).{method_name} }}.unwrap_or_else(|| rt::fail(w, \"the function is null\"));\n\t\tlet result = unsafe {{ f({}) }};\n\t\t{}\n\t}}\n", params.iter().map(|p| format!(", {p}")).collect::(), - rust(&method.ok), + self.rust(&method.ok), args.join(", "), self.lift(&method.ok, "result"), ); @@ -836,10 +845,9 @@ impl Gen<'_> { } } - /// An exported function, a method of `owner` if it has one: its C type, and the - /// object it belongs to, if any. - fn function(&mut self, function: &Function, owner: Option<(&Ty, Option)>) { - let export = self.abi.export(function, owner.map(|(ty, _)| ty)); + /// An exported function, a method of `owner` if it has one: its C type, and its type. + fn function(&mut self, function: &Function, owner: Option<(&Ty, Type)>) { + let export = self.abi.export(function, owner.as_ref().map(|(ty, _)| *ty)); let name = export.call.name.clone(); // An eager call borrows its arguments only for the call, as a synchronous one does. let future = function.future && !function.eager; @@ -847,24 +855,23 @@ impl Gen<'_> { let mut args = Vec::new(); let mut params = Vec::new(); let mut c_params = export.call.params.iter(); - let receiver_ty = owner.zip(function.receiver); - if let Some(((owner_ty, object), receiver)) = receiver_ty { + let receiver_ty = owner.as_ref().zip(function.receiver); + if let Some(((_, owner_type), receiver)) = &receiver_ty { let (_, c_ty) = c_params.next().expect("a method takes self"); params.push(format!("this: {}", self.rs(c_ty))); - match object { - Some(i) => { + match owner_type { + Type::Object(i) => { let ty = match receiver { - Receiver::Ref => Type::Ref(Mutability::Not, Box::new(Type::Object(i))), - Receiver::Mut => Type::Ref(Mutability::Mut, Box::new(Type::Object(i))), - Receiver::Owned => Type::Object(i), + Receiver::Ref => Type::Ref(Mutability::Not, Box::new(Type::Object(*i))), + Receiver::Mut => Type::Ref(Mutability::Mut, Box::new(Type::Object(*i))), + Receiver::Owned => Type::Object(*i), }; let (stmt, arg) = self.arg(&ty, "this", "a_self", future); stmts.push(stmt); args.push(arg); } - None => { - let value = self.value_type(owner_ty); - stmts.push(format!("let a_self = {};", self.lift(&value, "unsafe { *this }"))); + value => { + stmts.push(format!("let a_self = {};", self.lift(value, "unsafe { *this }"))); args.push(match receiver { Receiver::Owned => "a_self".to_string(), _ => "&a_self".to_string(), @@ -878,15 +885,8 @@ impl Gen<'_> { stmts.push(stmt); args.push(arg); } - let callee = match owner { - Some((_, object)) => { - let (owner_path, method) = function.path.split_at(function.path.len() - 1); - let owner_path = match object { - Some(i) => self.object_path(i), - None => self.path(owner_path), - }; - format!("<{owner_path}>::{}", method[0]) - } + let callee = match &owner { + Some((_, owner_type)) => format!("<{}>::{}", self.rust(owner_type), function.name()), None => self.path(&function.path), }; let call = match function.access { @@ -949,20 +949,4 @@ impl Gen<'_> { params.join(", "), )); } - - /// The IR type of a value's C type, for its receiver. - fn value_type(&self, ty: &Ty) -> Type { - let api = self.abi.api; - let name = match ty { - Ty::Struct(name) | Ty::Enum(name) => name, - other => unreachable!("a value's receiver is {other:?}"), - }; - if let Some(i) = (0..api.records.len()).find(|&i| &self.abi.record(i) == name) { - return Type::Record(i); - } - let i = (0..api.enums.len()) - .find(|&i| &self.abi.enumeration(i) == name) - .expect("a value is a record or enum"); - Type::Enum(i) - } } diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 69455670c..87645d36a 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -16,6 +16,38 @@ pub struct Api { pub constants: Vec, } +impl Api { + /// A type's Rust path with its instance's arguments, such as + /// `moq_mux::catalog::Producer`. + pub fn rust(&self, path: &Path, args: &[Type]) -> String { + let path = path.join("::"); + match args { + [] => path, + args => { + let args: Vec = args.iter().map(|arg| self.arg(arg)).collect(); + format!("{path}<{}>", args.join(", ")) + } + } + } + + /// A type argument, as [`Self::rust`] spells it. + fn arg(&self, ty: &Type) -> String { + match ty { + Type::Unit => "()".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::F32 => "f32".to_string(), + Type::F64 => "f64".to_string(), + Type::Char => "char".to_string(), + Type::String => "String".to_string(), + Type::Record(i) => self.rust(&self.records[*i].path, &self.records[*i].args), + Type::Enum(i) => self.rust(&self.enums[*i].path, &self.enums[*i].args), + Type::Object(i) => self.rust(&self.objects[*i].path, &self.objects[*i].args), + other => unreachable!("no type argument is {other:?}"), + } + } +} + /// A Rust path: its export's package name in snake case, unique among the exports, then /// the path from that crate's root, such as `["moq_net", "track", "Producer", "append_group"]`. pub type Path = Vec; @@ -23,6 +55,8 @@ pub type Path = Vec; /// A struct whose fields are all `pub`: a value, copied across. pub struct Record { pub path: Path, + /// The type arguments of the instance it is, empty unless the type is generic. + pub args: Vec, pub span: Span, pub docs: String, pub fields: Vec, @@ -43,6 +77,7 @@ pub struct Field { /// enumeration. pub struct Enum { pub path: Path, + pub args: Vec, pub span: Span, pub docs: String, pub variants: Vec, @@ -71,6 +106,7 @@ impl Enum { /// an `Arc`, whose receivers borrow it as Rust's do, checked at run time. pub struct Object { pub path: Path, + pub args: Vec, pub span: Span, pub docs: String, /// Whether it is `Sync`: if not, `&self` borrows it on one thread at a time. @@ -172,7 +208,7 @@ pub enum Literal { } /// A type as the API uses it, in the exact form the Rust side takes or returns. -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Type { Unit, Bool, @@ -210,14 +246,14 @@ pub enum Type { Tuple(Vec), } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Mutability { Not, Mut, } /// How a parameter takes a foreign implementation of a trait. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Dyn { /// A type parameter or `impl Trait`, given the foreign type. Impl, diff --git a/ffi/tests/api.c b/ffi/tests/api.c index c6a38daac..393d006c7 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -301,6 +301,38 @@ static int script(void) { printf("area %u %u %llu\n", size.width, size.height, (unsigned long long)api_area_pixels(area)); api_area_free(area); + /* Generic types, each at the instances the config names under their own names. */ + api_pair pair = {.left = 2, .right = 5}; + api_pair swapped = api_pair_swap(&pair); + printf("pair %u %u sum %u ", swapped.left, swapped.right, api_pair_sum(&pair)); + print("", api_pair_debug(&pair), " "); + printf("%s\n", api_pair_eq(&pair, &swapped) ? "true" : "false"); + api_pair twins = {.left = 7, .right = 7}; + printf("even %s %s\n", api_pair_even(&pair) ? "true" : "false", api_pair_even(&twins) ? "true" : "false"); + api_size_pair sizes = {.left = {.width = 1, .height = 2}, .right = 3}; + api_pair_size flipped = api_size_pair_swap(&sizes); + printf("sized %u %u ", flipped.left, flipped.right.width); + print("", api_pair_size_debug(&flipped), "\n"); + api_pair byte = {.left = 258, .right = 9}; + api_pair_size beside = api_pair_beside(&byte, sizes.left); + printf("beside %u ", beside.left); + print("", api_pair_size_debug(&beside), "\n"); + api_counters *stack = api_counters_new(); + const char *names[] = {"a", "b"}; + for (int i = 0; i < 2; i++) { + api_counter *pushed = api_counter_new(str(names[i]), (uint64_t)i + 1); + api_counters_push(stack, pushed); + api_counter_free(pushed); + } + api_counter *top = api_counters_pop(stack); + printf("stack %zu Some(%llu)", api_counters_depth(stack), (unsigned long long)api_counter_get(top)); + api_counter_free(top); + api_counter *next = api_counters_pop(stack); + printf(" %s", next != NULL ? "true" : "false"); + api_counter_free(next); + printf(" %s\n", api_counters_pop(stack) == NULL ? "true" : "false"); + api_counters_free(stack); + /* Its Drop runs when C frees the handle, not before. */ api_token *token = api_token_new(7); printf("token %u dropped %u\n", api_token_id(token), api_dropped()); diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index d79d4b8ab..7d8ee85fc 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -150,6 +150,7 @@ fn reject() { let at = |i: usize| { lines[i + 1..] .iter() + .take_while(|l| !l.starts_with("error") && !l.starts_with("warning") && !l.starts_with("note: ")) .find_map(|l| l.trim_start().strip_prefix("--> ")) .unwrap_or("no span") }; diff --git a/quest/m1/README.md b/quest/m1/README.md index 175fc1311..4ea0f357f 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -18,6 +18,5 @@ are folded into the [exporter's](/quest/m1/ffi-export.md). The - [Waiting: publish the UniFFI fork](/quest/m1/uniffi-release.md) - the fork publishes to crates.io under `rust2-*` names, once the maintainer decides it should - [Exporter](/quest/m1/ffi-export.md) - moq's bindings exported from its crates' `pub` API, replacing the fork -- [Export instances of generic types](/quest/m1/ffi-generic.md) - a generic type exports at the instances the config names - [Land main through quest land](/quest/m1/land.md) - every queued PR lands as one tested batch through the shared gate - [Bump quest to quest land](/quest/m1/land-bump.md) - condition: kixelated/quest ships `quest land`; then bump the flake input diff --git a/quest/m1/ffi-export.md b/quest/m1/ffi-export.md index a397baaf9..159a28807 100644 --- a/quest/m1/ffi-export.md +++ b/quest/m1/ffi-export.md @@ -26,6 +26,11 @@ census refuses and what moq waits on: - moq-clock's C names (`moq_now`, `moq_origin`) wait for its merge into kio. - A field and a method of one name, such as moq-tokio's `Backoff::initial`, claim one C name that `rename` cannot split, so [the config](/ffi/moq/ffi.toml) excludes both. + - The generic types moq-ffi's media API uses export at their instances + ([kixelated/rust2#103](https://github.com/kixelated/rust2/pull/103)). Left: + `catalog::Producer`'s `json_*` and `binary_*` producers take a type parameter no rule + picks, `Producer::modify` returns a borrowing `Guard`, and `DEFAULT_NAME` sits on + `hang::Catalog<()>`, an instance the config does not name. - **Driving**: sessions and origins run a `Driver` polled with a time and a `kio::Waiter`. Decide between exporting that poll, a generated thread that drives it, or moq-tokio's runtime helpers. diff --git a/quest/m1/ffi-generic.md b/quest/m1/ffi-generic.md deleted file mode 100644 index 16733a781..000000000 --- a/quest/m1/ffi-generic.md +++ /dev/null @@ -1,20 +0,0 @@ -# [M] Export instances of generic types - -## Goal - -The [exporter](/ffi/README.md) exports a generic type at the instances the config names, -such as `catalog::Producer`, so moq-ffi's media API that uses each at one -type exports from moq-mux and hang. - -## Plan - -Found by [#94](https://github.com/kixelated/rust2/pull/94) on 2026-10-27: refused generic -types block about 67 of moq-ffi's partly covered items, mostly in moq-mux -(`catalog::Producer`, `container::Consumer`). moq-ffi uses each at one type. - -- Name each instance in [the config](/ffi/moq/ffi.toml), with the C name it exports - under, and refuse with a span any signature that reaches a generic type at an instance - the config does not name. -- Report each export's census and the coverage of moq-ffi's API before and after. - -Public API: the exporter's config and the C names it emits.