diff --git a/ffi/MIGRATE.md b/ffi/MIGRATE.md index 72be195a1..752e6f1ff 100644 --- a/ffi/MIGRATE.md +++ b/ffi/MIGRATE.md @@ -14,3 +14,14 @@ `detail`) and every variant's payload name (`_`, even without fields) join the names the naming rule claims, so an exported item named one clashes: give it another name with a `rename`. +- The `instances` key is gone, top-level and under `[crates.*]`, and a config that has + it fails to parse: delete it. A generic item exports at the instances it infers from + its defaults, its inherent impls, its exports' implementations of the traits bounding + it, and the signatures that name it. Exclude an instance by its path, such as + `"Pair"`, to leave it out. +- An instance's C name is no longer the config's. It is the generic item's name, then + the last segment of each argument's, with more segments only where two instances would + share a name: `catalog::Producer` is `moq_catalog_producer_extra`, + and `Counter::seeded` at `polar::Point` beside `Point` is + `api_counter_seeded_polar_point`. An instance an upstream change adds can lengthen + another's name. diff --git a/ffi/README.md b/ffi/README.md index b21b8089b..a937eff45 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -41,18 +41,9 @@ 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`, `rename`, and `instances`, by paths from its crate root. +# own `exclude` and `rename`, 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. A generic function or method's key names the -# argument of each of its type parameters, an `impl Trait` one by its argument's name. -[crates.moq-mux.instances] -"catalog::Producer" = "catalog_producer" -"catalog::Producer::binary_stream(config: moq_mux::binary::Config)" = "catalog_producer_binary_stream" ``` ## Rules @@ -68,8 +59,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 generic function or method, at each instance `instances` names | that instance in place of the rules below, at each instance of its type; one whose bounds fail, or that nothing exported reaches, is refused | +| a generic type, at each instance it infers | 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 | | a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce`, which no lifetime bound or return lets outlive the call | a C function and its `void *` data, which Rust calls only during the call; any other closure is refused | @@ -87,7 +77,16 @@ 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, 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 | +| another type parameter | the first of `String`, `Bytes`, and `Vec` meeting its bounds, or a foreign implementation of its one exported trait; else an instance of the function at each type the exports implement a trait bounding it for, as `&X` where that meets its bounds too, so C keeps its handle, and, as an argument of a generic type, at each argument of an instance that meets its bounds and makes each generic type the signature names an instance | + +A generic type infers the instances it exports at, with no config: the one at its +defaults, if each type parameter has one; the one each inherent impl is of, such as +`impl Pair`; each choice, for each parameter, among its default and the types the +exports implement a trait bounding it for, one of the exports', which are `()`, a +primitive, `String`, or an exported type; and each instance a signature or field names, +once that is all its export refuses, which may name more. An instance that holds an +instance of a type inside it, such as `Cell>`, is refused, as it could name +ever deeper ones. 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 @@ -138,11 +137,22 @@ refused, and the census counts why. 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`. So are a field and the method of its name, as moq-tokio's - `Backoff::initial`; `field@Backoff::initial` names the field. An instance is named by `instances`, and a type instance's - 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. + `Backoff::initial`; `field@Backoff::initial` names the field. + + An instance is named by its generic item's name, then each argument but those at their + defaults after the last that is not, so the instance at its defaults is named as the + item. Each argument takes the last segment of its C name, such as `extra` for moq-mux's + `catalog::hang::Extra`, so `catalog::Producer` is + `moq_catalog_producer_extra`. Where two instances of one item would still share a name, + each argument that tells them apart takes one more segment at a time, until they + differ: the api fixture's `Counter::seeded` is `api_counter_seeded_point` at its + `Point`, and `api_counter_seeded_polar_point` at `polar::Point`. The names depend on + every instance the item exports at, so one an upstream change adds can lengthen another's + name. A type instance's methods are named through it, and a function instance appends + its arguments' names, a reference's by what it borrows. An `exclude` of a type or method + by the generic type's path leaves it out of every instance, and by the instance's path + (`"catalog::Producer::stats"`) out of that one; a + `rename` by the generic item's path renames each of its instances. ## C++ @@ -199,8 +209,7 @@ names and signatures, so [`src/c.rs`](src/c.rs), [`src/cpp.rs`](src/cpp.rs), and `--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, and the refused instances to drop from `instances`. It ignores the config's -`exclude`, and reads its `instances`. +rest. It ignores the config's `exclude`. ## Tests diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index d9d429126..6d78e56d4 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -233,10 +233,7 @@ fn main() { pair == swapped ); println!("even {} {}", pair.even(), Pair { left: 7u32, right: 7 }.even()); - let sized = Pair { - left: Size { width: 1, height: 2 }, - right: 3u8, - }; + let sized = api_lib::tag(Size { width: 1, height: 2 }, 3); let flipped = sized.swap(); println!("sized {} {} {flipped:?}", flipped.left, flipped.right.width); let beside = Pair { left: 258u32, right: 9 }.beside(sized.left); @@ -254,12 +251,34 @@ fn main() { ); let from_point = Counter::seeded("p", Point { x: -3, y: 4 }); let from_size = Counter::seeded("s", Size { width: 5, height: 6 }); + let from_counter = Counter::seeded("c", &from_point); + let from_polar = Counter::seeded("q", api_lib::polar::Point { turns: 1, distance: 2 }); println!( - "seeded {} {} past {} seeds {}", + "seeded {} {} {} {} past {} seeds {}", from_point.get(), from_size.get(), - stack.depth_past(Point { x: 1, y: 2 }), - api_lib::seeds::(Size { width: 2, height: 3 }) + from_counter.get(), + from_polar.get(), + stack.depth_past(&Point { x: 1, y: 2 }), + api_lib::seeds::(&Size { width: 2, height: 3 }) + ); + + println!("weigh {}", api_lib::weigh(Point { x: -1, y: 2 })); + let left = api_lib::Left { + value: api_lib::Right { value: 1u8 }, + }; + let right = api_lib::Right { + value: api_lib::Left { value: 2u8 }, + }; + println!( + "cross {} outer {}", + api_lib::cross(left, right), + api_lib::Outer::new(4).get() + ); + println!( + "kept {} boxed {}", + api_lib::kept(Point { x: 1, y: -2 }), + api_lib::BOXED.value ); let token = api_lib::Token::new(7); diff --git a/ffi/fixtures/api/ffi.toml b/ffi/fixtures/api/ffi.toml index 80c123bf7..c972c5cf8 100644 --- a/ffi/fixtures/api/ffi.toml +++ b/ffi/fixtures/api/ffi.toml @@ -3,29 +3,22 @@ prefix = "api" # The list's tail is not `Clone`, so its getter has no copy to return, one instance leaves # out a method the others keep, `Seed` is generic, so no callback implements it, and # `field@` leaves out a field alone where a method takes its path, as `Retry`'s and -# `Slot`'s do. `Slot` has no such method, so its path alone names its field. -exclude = ["Node::next", "Pair::swap", "Seed", "Slot::value", "field@Retry::delay", "field@Slot::value"] +# `Slot`'s do. `Slot` has no such method, so its path alone names its field. A +# function instance is left out by its path, as `depth_past` at `polar::Point` is. +exclude = [ + "Node::next", + "Pair::swap", + "Seed", + "Slot::value", + "field@Retry::delay", + "field@Slot::value", + "Stack::depth_past", +] # The field `Retry::limit`, whose name its method takes. [rename] "field@Retry::limit" = "retry_limit_setting" -# 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" -"Slot" = "byte_slot" -"Slot" = "slot" -# Generic functions and methods likewise, each type parameter by name, an `impl Trait` one -# by its argument's, in any order. -"Counter::seeded(from: api_fixture::Point)" = "counter_seeded_point" -"Counter::seeded(from: dep_fixture::Size)" = "counter_seeded_size" -"Stack::depth_past(from: api_fixture::Point)" = "counters_depth_past_point" -"seeds(from: dep_fixture::Size, T: api_fixture::Point)" = "seeds" - # Exported into the same library: `grow` names its types. [crates.dep-fixture] exclude = ["HashSet"] diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 22acbe364..d5e2d706a 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -592,8 +592,8 @@ 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. +/// Two values: a generic record, which exports at each instance it infers. Its second +/// parameter defaults to its first, as an instance's name leaves it. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Pair { pub left: L, @@ -618,14 +618,14 @@ impl Pair { } } -/// An impl of one instance, whose methods no other instance has. +/// An impl of one instance, whose methods no other instance has, and which infers it. 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`. + /// fills the type parameter, with `dep_fixture::Size`, and names this instance. pub fn beside(&self, right: T) -> Pair { Pair { left: self.left as u8, @@ -634,9 +634,15 @@ impl Pair { } } -/// A stack: a generic object, at an instance of objects, whose handles move in and out. +/// A size tagged with a byte: a signature that names an instance, which infers it, and +/// its `swap` the other way around. +pub fn tag(size: Size, tag: u8) -> Pair { + Pair { left: size, right: tag } +} + +/// A stack: a generic object, at its default of objects, whose handles move in and out. #[derive(Debug, Default)] -pub struct Stack { +pub struct Stack { items: Vec, } @@ -664,11 +670,93 @@ impl Stack { } /// What a [`Counter`] can start from: generic, so no foreign implementation takes it, and a -/// parameter it bounds exports at each instance the config names. +/// parameter it bounds exports at each type the exports implement it for, by reference, +/// which also implements it, so C keeps its handle. pub trait Seed { fn seed(&self) -> T; } +/// A weight, implemented for `Point` and for `&Point` apart, which both choose `&Point`: +/// one instance of a parameter it bounds. +impl Seed for Point { + fn seed(&self) -> u32 { + self.x.unsigned_abs() + self.y.unsigned_abs() + } +} + +impl Seed for &Point { + fn seed(&self) -> u32 { + Seed::::seed(*self) + } +} + +/// Two generic records whose instances name each other, as `Left>` and +/// `Right>` do: each instance is named without the other's name. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Left { + pub value: T, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Right { + pub value: T, +} + +/// The sum of what each holds inside. +pub fn cross(left: Left>, right: Right>) -> u8 { + left.value.value + right.value.value +} + +/// A handle made only by an impl of an instance holding another, which nothing else +/// names: inferring the outer instance infers the inner one. +pub struct Outer(T); + +impl Outer> { + pub fn new(value: u8) -> Self { + Self(Inner { value }) + } + + pub fn get(&self) -> u8 { + self.0.value + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Inner { + pub value: T, +} + +/// `from`'s seed, which outlives the call, so a reference to a value C passes cannot be +/// it: each instance takes its value. +pub fn kept(from: impl Seed + 'static) -> u64 { + from.seed() +} + +/// A generic record only a constant names, which infers its instance. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Boxed { + pub value: T, +} + +pub const BOXED: Boxed = Boxed { value: 42 }; + +/// `from`'s weight. +pub fn weigh(from: impl Seed) -> u32 { + from.seed() +} + +impl> Seed for &S { + fn seed(&self) -> u64 { + (**self).seed() + } +} + +impl Seed for Counter { + fn seed(&self) -> u64 { + self.value + } +} + impl Seed for Point { fn seed(&self) -> u64 { u64::from(self.x.unsigned_abs()) + u64::from(self.y.unsigned_abs()) @@ -681,8 +769,26 @@ impl Seed for Size { } } +/// A second `Point`, whose last segment clashes with the crate root's: an instance named +/// by it takes its module too, and one named by the other keeps the shorter name. +pub mod polar { + /// A point by its angle in turns and its distance from the origin. + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Point { + pub turns: u8, + pub distance: u32, + } + + impl super::Seed for Point { + fn seed(&self) -> u64 { + u64::from(self.turns) + u64::from(self.distance) + } + } +} + impl Counter { - /// A counter named `name` at `from`'s seed: an `impl Trait` argument, at two instances. + /// A counter named `name` at `from`'s seed: an `impl Trait` argument, at an instance + /// for each implementation. pub fn seeded(name: &str, from: impl Seed) -> Counter { Counter::new(name, from.seed()) } @@ -722,3 +828,8 @@ impl Slot { u16::from(self.value) * 2 } } + +/// A wide slot: a signature that names `Slot`, which infers it. +pub fn wide(value: u32) -> Slot { + Slot::new(value) +} diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 8069a33cc..2229dda24 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -8,30 +8,25 @@ 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:1: rust2-ffi: cannot export instance `Cell>`: Vec `std::string::String`; 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:180:1: rust2-ffi: cannot export fn `copied(T: String)`: unmet bound of the instance `std::string::String: std::marker::Copy`; drop it from the config's `instances` -fixtures/reject/src/lib.rs:180:1: rust2-ffi: instance `copied()` in the config exports nothing: it needs an argument for `T` -fixtures/reject/src/lib.rs:180:1: rust2-ffi: instance `copied(U: u8)` in the config exports nothing: `U` is none of its type parameters `T` -fixtures/reject/src/lib.rs:186:2: rust2-ffi: instance `Bounded::get(U: u64)` in the config exports nothing: nothing exported reaches it -fixtures/reject/src/lib.rs:192:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:159:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:165:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:178:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:183: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:186:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; 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:207:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C - fixtures/reject/src/lib.rs:199:2: note: field `reject_fixture::Limit::max` is here -fixtures/reject/src/lib.rs:213:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:218:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:235:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:201:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C + fixtures/reject/src/lib.rs:193:2: note: field `reject_fixture::Limit::max` is here +fixtures/reject/src/lib.rs:207:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:217:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs: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 @@ -47,7 +42,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 -fixtures/reject/src/lib.rs:9:1: rust2-ffi: instance `pair(T: u8)` in the config exports nothing: it takes no type parameters -no span: rust2-ffi: instance `Missing` in the config exports nothing: `reject_fixture::Missing` names no exported struct or enum -no span: rust2-ffi: instance `missing(T: u8)` in the config exports nothing: `missing` names no exported function or method no span: rust2-ffi: rename `field@Limit::min` in the config names nothing exported diff --git a/ffi/fixtures/reject/ffi.toml b/ffi/fixtures/reject/ffi.toml index 08c941106..f989b49a4 100644 --- a/ffi/fixtures/reject/ffi.toml +++ b/ffi/fixtures/reject/ffi.toml @@ -1,30 +1,11 @@ package = "reject-fixture" prefix = "reject" -# An exclusion leaves an item out, so nothing refuses it. -exclude = ["Excluded"] +# An exclusion leaves an item or an instance out, so nothing refuses it. +exclude = ["Cell", "Excluded"] # A field that is none: `min` names nothing of `Limit`. [rename] "field@Limit::min" = "limit_min" -# 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" -# Function instances that cannot export: an unmet bound, a name that is none of its type -# parameters, one left out, a function that is not generic, a method nothing exported -# reaches, and a path that names nothing. -"copied(T: String)" = "copied_string" -"copied(U: u8)" = "copied_u8" -"copied()" = "copied" -"pair(T: u8)" = "pair_u8" -"Bounded::get(U: u64)" = "bounded_get" -"missing(T: u8)" = "missing_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 9872e826b..dca98f6a2 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -145,7 +145,7 @@ pub fn measure(size: dep::Size) -> dep::Area { dep::Area::new(size) } -/// A generic type the config names at `u32` alone. +/// A generic type, which exports at the instances its exports name. pub struct Cell(T); impl Cell { @@ -154,40 +154,34 @@ impl Cell { } } -/// An instance the config does not name. -pub fn unnamed(cell: Cell) -> u8 { +impl Cell { + /// An instance holding an instance of its own type, which could name ever deeper ones. + pub fn nest(self) -> Cell> { + Cell(self) + } +} + +/// An instance the config excludes. +pub fn excluded_cell(cell: Cell) -> u16 { cell.0 } -/// A type parameter both instances of `Cell` could fill. -pub fn fill(value: T) -> Cell { - Cell(value) +/// An instance whose type argument is no value or handle, so it cannot name it. +pub fn listed(cell: Cell>) -> usize { + cell.0.len() } -/// A generic type whose bound the config's instance does not meet. -pub struct Bounded(pub T); +/// A const-generic type, whose const argument the IR cannot carry. +pub struct Fixed(pub u8); -/// A generic type whose default argument is a type no instance key can spell. -pub struct Holder> { - pub value: T, +/// An instance of it, which a signature names. +pub fn fixed() -> Fixed<2> { + Fixed(2) } /// Another crate's item that is no export, so nothing names it. pub use std::collections::HashSet; -/// A generic function whose bound one of the config's instances does not meet, and whose -/// type parameter others misname. -pub fn copied(value: T) -> T { - value -} - -impl Bounded { - /// A generic method of a type that exports at no instance, so nothing reaches it. - pub fn get>(&self) -> U { - U::from(self.0) - } -} - /// A borrowed waker: one crosses only into Rust, which keeps it. pub fn lend(waker: &std::task::Waker) { waker.wake_by_ref(); diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index b39f94b29..8ee7e5425 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -14,7 +14,6 @@ exclude = [ "Consume", "DecodeError", "Driver", - "Error::from_transport", "Hops::as_slice", "Hops::iter", "IntoBytes", @@ -59,7 +58,6 @@ exclude = [ "stats::Snapshot::traffic", "stats::TrafficEntry", "time::Driver", - "time::run", "track::Fetching", "track::Resolving", "track::Subscribing", @@ -96,11 +94,6 @@ exclude = [ "varint::encode_quic", ] -# A consumer moves in, as C makes one from its producer. -[crates.moq-net.instances] -"Client::with_publisher(publish: moq_net::origin::Consumer)" = "client_with_publisher" -"Server::with_publisher(publish: moq_net::origin::Consumer)" = "server_with_publisher" - [crates.moq-net.rename] # The rule makes both this type and `Session::stats` `moq_session_stats`. "session::Stats" = "session_stats_snapshot" @@ -304,11 +297,6 @@ exclude = [ "worker::Workers::local_addr", ] -# As moq-net's, which these pass the consumer to. -[crates.moq-tokio.instances] -"Client::with_publisher(publish: moq_net::origin::Consumer)" = "tokio_client_with_publisher" -"server::Request::with_publisher(publish: moq_net::origin::Consumer)" = "server_request_with_publisher" - [crates.moq-tokio.rename] # The rule names these and moq-net's `Client`, `Server`, and `Error` alike. "Client" = "tokio_client" @@ -327,7 +315,6 @@ exclude = [ [crates.hang] exclude = [ "Catalog::from_reader", - "Catalog::media", "Catalog::subscribe", "catalog::Archive::store", "catalog::Archive::timelines", @@ -370,12 +357,10 @@ 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 makes its accessors, such as `audio`, the `catalog` module's types: +# `moq_catalog_audio`. +"Catalog" = "hang_catalog" # The rule names this and moq-net's `Error` alike. "Error" = "hang_error" # The rule makes both these enums and the `kind` methods of `AudioCodec` and `VideoCodec` @@ -402,7 +387,6 @@ exclude = [ "catalog::Guard", "catalog::IntoRendition", "catalog::Producer::audio", - "catalog::Producer::is_claimed", "catalog::Producer::json_snapshot", "catalog::Producer::json_stream", "catalog::Producer::modify", @@ -422,7 +406,6 @@ exclude = [ "catalog::hang::Extra::iter", "catalog::hang::Extra::remove", "catalog::hang::Extra::set", - "catalog::msf::Consumer", "codec::aac::Config::parse", "codec::annexb::NalIterator", "codec::annexb::build_prefix", @@ -455,11 +438,9 @@ exclude = [ "container::MissingKeyframe", "container::Producer", "container::flv::Export", - "container::flv::Import", "container::fmp4::Export", "container::fmp4::Fragmenter::push", "container::fmp4::Fragmenter::push_group", - "container::fmp4::Import", "container::fmp4::Muxer::fragment", "container::fmp4::Muxer::read", "container::fmp4::Wire::new", @@ -467,7 +448,6 @@ exclude = [ "container::fmp4::mp4_atom", "container::mkv::Error", "container::mkv::Export", - "container::mkv::Import", "container::ts::Catalog", "container::ts::Export", "container::ts::Follower", @@ -476,7 +456,6 @@ exclude = [ "container::ts::Mpegts::si", "container::ts::Mpegts::tracks", "container::ts::MultipleProgramsError", - "container::ts::Passthrough", "container::ts::Programs::decode", "container::ts::Programs::finish", "container::ts::Track::descriptors", @@ -487,29 +466,10 @@ exclude = [ "json::Consumer", "json::Snapshot", "json::Stream", - "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" -# The binary producers moq-ffi's flate tracks publish through, at the config C builds. -"catalog::Producer::binary_snapshot(config: moq_mux::binary::Config)" = "catalog_producer_binary_snapshot" -"catalog::Producer::binary_stream(config: moq_mux::binary::Config)" = "catalog_producer_binary_stream" -"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/moq/moq.c b/ffi/moq/moq.c index 1854c0ece..6fa284343 100644 --- a/ffi/moq/moq.c +++ b/ffi/moq/moq.c @@ -37,10 +37,10 @@ static int is(moq_buf buf, const char *s) { /* The catalog `mutate` lends for its call, which lists the binary track: counts it in * data. */ -static void lists_state(void *data, moq_hang_catalog *catalog) { +static void lists_state(void *data, moq_hang_catalog_extra *catalog) { moq_buf json; moq_hang_error *hang_err = NULL; - CHECK(moq_hang_catalog_to_json(catalog, &json, &hang_err)); + CHECK(moq_hang_catalog_extra_to_json(catalog, &json, &hang_err)); for (size_t i = 0; i + 5 <= json.len; i++) { if (memcmp(json.ptr + i, "state", 5) == 0) { (*(int *)data)++; @@ -227,14 +227,12 @@ int main(void) { CHECK(moq_origin_driver_poll(driver, now, waiter, &deadline, &err)); moq_instant_free(deadline); moq_instant_free(now); - /* A client publishes the origin through moq-net's generic `with_publisher`, which a - * consumer moves into. */ + /* A client publishes the origin through moq-net's generic `with_publisher`, at each + * type that implements its bound, by reference, so C keeps its handle. */ moq_client *client = moq_client_new(); - moq_origin_consumer *published = moq_origin_producer_consume(origin); - moq_client *publishing = moq_client_with_publisher(client, published); + moq_client *publishing = moq_client_with_publisher_producer(client, origin); CHECK(publishing != NULL); moq_client_free(publishing); - moq_origin_consumer_free(published); moq_client_free(client); int before = wakes; moq_origin_producer_free(origin); @@ -276,32 +274,33 @@ int main(void) { mux_err = NULL; /* A binary track the catalog lists, published through moq-mux's generic - * `binary_snapshot` at the config C builds. */ + * `binary_snapshot` at the config C builds, by a catalog at moq-mux's untyped + * extension, each instance named by the last segment of each argument. */ moq_broadcast_info *listed = moq_broadcast_info_new(); moq_broadcast_producer *publisher = moq_broadcast_info_produce(listed); moq_broadcast_info_free(listed); moq_catalog_config *catalog_config = moq_catalog_config_default(); - moq_hang_catalog *hang = moq_hang_catalog_default(); - moq_catalog_config_extra *extra = moq_catalog_config_with_catalog(catalog_config, hang); + moq_hang_catalog_extra *hang = moq_hang_catalog_extra_default(); + moq_catalog_config_extra *extra = moq_catalog_config_with_catalog_extra(catalog_config, hang); moq_catalog_config_free(catalog_config); - moq_hang_catalog_free(hang); - moq_catalog_producer *catalog = NULL; - CHECK(moq_catalog_producer_new(publisher, extra, &catalog, &mux_err)); + moq_hang_catalog_extra_free(hang); + moq_catalog_producer_extra *catalog = NULL; + CHECK(moq_catalog_producer_extra_new(publisher, extra, &catalog, &mux_err)); moq_catalog_config_extra_free(extra); moq_track_producer *state = NULL; CHECK(moq_broadcast_producer_create_track(publisher, str("state"), NULL, &state, &err)); moq_binary_config *binary = moq_binary_config_default(); moq_binary_snapshot *snapshot = NULL; - CHECK(moq_catalog_producer_binary_snapshot(catalog, state, binary, &snapshot, &mux_err)); + CHECK(moq_catalog_producer_extra_binary_snapshot_config(catalog, state, binary, &snapshot, &mux_err)); moq_binary_config_free(binary); moq_track_producer_free(state); CHECK(is(moq_binary_snapshot_name(snapshot), "state")); CHECK(moq_binary_snapshot_update(snapshot, str("latest"), &mux_err)); int listed_state = 0; - CHECK(moq_catalog_producer_mutate(catalog, lists_state, &listed_state, &mux_err)); + CHECK(moq_catalog_producer_extra_mutate(catalog, lists_state, &listed_state, &mux_err)); CHECK(listed_state == 1); moq_binary_snapshot_free(snapshot); - moq_catalog_producer_free(catalog); + moq_catalog_producer_extra_free(catalog); moq_broadcast_producer_free(publisher); /* moq-tokio's terminal connect errors, which moq-net's `Error` shares no names with. */ diff --git a/ffi/moq/moq.cpp b/ffi/moq/moq.cpp index b0f725f5a..782c214e8 100644 --- a/ffi/moq/moq.cpp +++ b/ffi/moq/moq.cpp @@ -144,9 +144,9 @@ int main() { moq::waiter waiter = moq::waiter::new_(waker); CHECK(driver.poll(moq::now(), waiter)); { - // A client publishes the origin through moq-net's generic `with_publisher`, which a - // consumer moves into. - moq::client publishing = moq::client::new_().with_publisher(origin.consume()); + // A client publishes the origin through moq-net's generic `with_publisher`, at each + // type that implements its bound, by reference, so C++ keeps its handle. + moq::client publishing = moq::client::new_().with_publisher_producer(origin); (void)publishing; } int before = wakes; @@ -173,19 +173,21 @@ int main() { CHECK(!truncated && !truncated.error().to_string().empty()); // A binary track the catalog lists, published through moq-mux's generic - // `binary_snapshot` at the config C++ builds. + // `binary_snapshot` at the config C++ builds, by a catalog at moq-mux's untyped + // extension, each instance named by the last segment of each argument. { moq::broadcast_producer publisher = moq::broadcast_info::new_().produce(); - moq::catalog_config_extra extra = moq::catalog_config::default_().with_catalog(moq::hang_catalog::default_()); - auto catalog = moq::catalog_producer::new_(publisher, std::move(extra)); + moq::catalog_config_extra extra = + moq::catalog_config::default_().with_catalog_extra(moq::hang_catalog_extra::default_()); + auto catalog = moq::catalog_producer_extra::new_(publisher, std::move(extra)); CHECK(catalog); auto state = publisher.create_track("state", std::nullopt); CHECK(state); - auto snapshot = catalog->binary_snapshot(std::move(*state), moq::binary_config::default_()); + auto snapshot = catalog->binary_snapshot_config(std::move(*state), moq::binary_config::default_()); CHECK(snapshot && is(snapshot->name(), "state")); CHECK(snapshot->update("latest")); int listed_state = 0; - CHECK(catalog->mutate([&](moq::hang_catalog &lent) { + CHECK(catalog->mutate([&](moq::hang_catalog_extra &lent) { auto json = lent.to_json(); CHECK(json); if (json && json.value().str().find("state") != std::string_view::npos) { diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 59c24bfe7..39bce0545 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -71,16 +71,20 @@ pub struct Export { pub future: Option<(String, Sig, Sig)>, } +/// The suffix naming each instance of a generic item, by its arguments. +type Suffixes = HashMap, String>; + pub struct Abi<'a> { pub api: &'a Api, pub prefix: String, /// 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 generic item's instances, by whether it is a function and its C name, with + /// the suffix that names each by its arguments. + suffixes: std::cell::RefCell>, /// Each `Option` struct by C name, with `T`. pub options: BTreeMap, /// Each range, bound, and pair of bounds struct by C name, with its type. @@ -92,13 +96,13 @@ pub struct Abi<'a> { } impl<'a> Abi<'a> { - pub fn new(api: &'a Api, prefix: &str, rename: &'a BTreeMap, instances: &[(Type, String)]) -> Self { + pub fn new(api: &'a Api, prefix: &str, rename: &'a BTreeMap) -> Self { let mut abi = Self { api, prefix: prefix.to_string(), rename, - instances: instances.iter().cloned().collect(), renamed: Default::default(), + suffixes: Default::default(), options: BTreeMap::new(), ranges: BTreeMap::new(), names: HashMap::new(), @@ -110,23 +114,28 @@ impl<'a> Abi<'a> { /// The C name for a Rust path, which starts with its crate's name. pub fn name(&self, path: &[String]) -> String { - let mut name = self.prefix.clone(); + std::iter::once(self.prefix.clone()) + .chain(self.segments(path)) + .collect::>() + .join("_") + } + + /// The segments of a Rust path's C name after the prefix: a renamed part as one, then + /// each segment past it in snake case. + fn segments(&self, path: &[String]) -> Vec { + let mut segments = Vec::new(); let mut rest = &path[1..]; for len in (2..=path.len()).rev() { let key = path[..len].join("::"); if let Some(renamed) = self.rename.get(&key) { self.renamed.borrow_mut().insert(key); - name.push('_'); - name.push_str(renamed); + segments.push(renamed.clone()); rest = &path[len..]; break; } } - for segment in rest { - name.push('_'); - name.push_str(&snake(segment)); - } - name + segments.extend(rest.iter().map(|segment| snake(segment))); + segments } /// The config's renames that name nothing exported. @@ -145,32 +154,84 @@ impl<'a> Abi<'a> { } pub fn record(&self, i: usize) -> String { - self.type_name(Type::Record(i), &self.api.records[i].path) + self.type_instance(&self.api.records[i].path, &self.api.records[i].args) } pub fn enumeration(&self, i: usize) -> String { - self.type_name(Type::Enum(i), &self.api.enums[i].path) + self.type_instance(&self.api.enums[i].path, &self.api.enums[i].args) } pub fn object(&self, i: usize) -> String { - self.type_name(Type::Object(i), &self.api.objects[i].path) + self.type_instance(&self.api.objects[i].path, &self.api.objects[i].args) } - /// 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), - } + /// The C name of the instance of the type at `path` at `args`, among the type's every + /// instance, whichever kind each is. + fn type_instance(&self, path: &[String], args: &[Type]) -> String { + let api = self.api; + self.instance(false, self.name(path), args, || { + let records = api.records.iter().map(|r| (&r.path, &r.args)); + let enums = api.enums.iter().map(|e| (&e.path, &e.args)); + let objects = api.objects.iter().map(|o| (&o.path, &o.args)); + (records.chain(enums).chain(objects)) + .filter(|(other, _)| other[..] == *path) + .map(|(_, args)| args.clone()) + .collect() + }) + } + + /// An instance's C name: its generic item's, `name`, then the suffix naming `args` + /// apart from the arguments of the item's other instances, which `group` lists. + fn instance(&self, function: bool, name: String, args: &[Type], group: impl FnOnce() -> Vec>) -> String { + if args.is_empty() { + return name; + } + let key = (function, name); + if let Some(suffix) = self.suffixes.borrow().get(&key).and_then(|suffixes| suffixes.get(args)) { + return format!("{}_{suffix}", key.1); + } + let group = group(); + let forms: Vec>> = (group.iter()) + .map(|args| args.iter().map(|arg| self.arg_forms(arg)).collect()) + .collect(); + let suffixes: Suffixes = group.into_iter().zip(shortest(&forms)).collect(); + let suffix = suffixes[args].clone(); + self.suffixes.borrow_mut().insert(key.clone(), suffixes); + format!("{}_{suffix}", key.1) + } + + /// The names an instance's argument `ty` may take, shortest first: a type's path's + /// last segment, then its own arguments' names, lengthened in step until whole, then + /// its path's segments, one more at a time. They read only `ty` itself, never another + /// instance's name, so two items whose instances name each other, as `A>` and + /// `B>`, name each without the other. + fn arg_forms(&self, ty: &Type) -> Vec { + let (path, args) = match ty { + Type::Record(i) => (&self.api.records[*i].path, &self.api.records[*i].args), + Type::Enum(i) => (&self.api.enums[*i].path, &self.api.enums[*i].args), + Type::Object(i) => (&self.api.objects[*i].path, &self.api.objects[*i].args), + Type::Ref(_, inner) | Type::Box(inner) => return self.arg_forms(inner), + ty => return vec![self.key(ty)], + }; + let segments = self.segments(path); + let nested: Vec> = args.iter().map(|arg| self.arg_forms(arg)).collect(); + let steps = nested.iter().map(Vec::len).max().unwrap_or(1); + let form = |len: usize, step: usize| { + std::iter::once(segments[segments.len() - len..].join("_")) + .chain(nested.iter().map(|forms| forms[step.min(forms.len() - 1)].clone())) + .collect::>() + .join("_") + }; + let mut forms: Vec = (0..steps).map(|step| form(1, step)).collect(); + forms.extend((2..=segments.len()).map(|len| form(len, steps - 1))); + forms.dedup(); + forms } - /// A function's C name: an instance's as the config names it, else a method's through - /// its type's, unless renamed itself. A field is renamed by `field@` and its path, or - /// by its path unless a method or constant takes it. + /// A function's C name: a method's through its type's, unless renamed itself, then + /// each argument of the instance it is. A field is renamed by `field@` and its path, + /// or by its path unless a method or constant takes it. fn function_name(&self, function: &Function, owner: Option<&Ty>) -> String { - if let Some(instance) = &function.instance { - return format!("{}_{}", self.prefix, instance.name); - } let path = function.path.join("::"); let shared = match function.access { Access::Field { shared } => { @@ -183,14 +244,34 @@ impl<'a> Abi<'a> { } _ => false, }; + let name = match owner { + Some(Ty::Struct(owner) | Ty::Enum(owner) | Ty::Handle { name: owner, .. }) + if shared || !self.rename.contains_key(&path) => + { + format!("{owner}_{}", snake(function.name())) + } + _ => self.name(&function.path), + }; + let Some(instance) = &function.instance else { + return name; + }; let owner = match owner { - Some(Ty::Struct(name) | Ty::Enum(name) | Ty::Handle { name, .. }) => name, - _ => return self.name(&function.path), + Some(Ty::Struct(owner) | Ty::Enum(owner) | Ty::Handle { name: owner, .. }) => Some(owner.as_str()), + _ => None, }; - match !shared && self.rename.contains_key(&path) { - true => self.name(&function.path), - false => format!("{owner}_{}", snake(function.name())), - } + self.instance(true, name, &instance.named, || { + let api = self.api; + let records = (0..api.records.len()).map(|i| (Some(self.record(i)), &api.records[i].methods)); + let enums = (0..api.enums.len()).map(|i| (Some(self.enumeration(i)), &api.enums[i].methods)); + let objects = (0..api.objects.len()).map(|i| (Some(self.object(i)), &api.objects[i].methods)); + let free = std::iter::once((None, &api.functions)); + (records.chain(enums).chain(objects).chain(free)) + .filter(|(other, _)| other.as_deref() == owner) + .flat_map(|(_, functions)| functions) + .filter(|other| other.path == function.path) + .filter_map(|other| other.instance.as_ref().map(|instance| instance.named.clone())) + .collect() + }) } pub fn callback(&self, i: usize) -> String { @@ -212,11 +293,13 @@ impl<'a> Abi<'a> { format!("{}_{}", self.prefix, self.key(ty)) } - /// A type's name within the prefix, for naming the structs built from it. + /// A type's name within the prefix, for naming the structs and instances built from it. fn key(&self, ty: &Type) -> String { let strip = |name: String| name[self.prefix.len() + 1..].to_string(); match ty { + Type::Unit => "unit".to_string(), Type::Bool => "bool".to_string(), + Type::String => "string".to_string(), Type::Int(int) => int.rust().to_string(), Type::F32 => "f32".to_string(), Type::F64 => "f64".to_string(), @@ -224,6 +307,7 @@ impl<'a> Abi<'a> { Type::Duration => "duration".to_string(), Type::Record(i) => strip(self.record(*i)), Type::Enum(i) => strip(self.enumeration(*i)), + Type::Object(i) => strip(self.object(*i)), Type::Range(int) => format!("range_{}", int.rust()), Type::Bound(int) => format!("bound_{}", int.rust()), Type::Bounds(int) => format!("bounds_{}", int.rust()), @@ -581,6 +665,43 @@ impl<'a> Abi<'a> { } } +/// The suffix naming each of a generic item's instances, given the names each of its +/// arguments may take, shortest first: each argument's shortest, lengthened by one at a +/// time only where two instances' suffixes are alike while their arguments differ there. +/// Each suffix depends on the whole group, not its order, so an instance added later can +/// lengthen another's name. Instances alike at every length keep their clash, which +/// claiming their C names reports. +fn shortest(group: &[Vec>]) -> Vec { + let mut lens: Vec> = group.iter().map(|args| vec![1; args.len()]).collect(); + loop { + let names: Vec = (group.iter().zip(&lens)) + .map(|(args, lens)| { + (args.iter().zip(lens)) + .map(|(forms, &len)| forms[len - 1].as_str()) + .collect::>() + .join("_") + }) + .collect(); + let mut grow = std::collections::BTreeSet::new(); + for (a, b) in (0..group.len()).flat_map(|a| (0..group.len()).map(move |b| (a, b))) { + if a == b || names[a] != names[b] { + continue; + } + for (j, forms) in group[a].iter().enumerate() { + if group[b].get(j) != Some(forms) && lens[a][j] < forms.len() { + grow.insert((a, j)); + } + } + } + if grow.is_empty() { + return names; + } + for (a, j) in grow { + lens[a][j] += 1; + } + } +} + /// A Rust identifier in snake case: `TrackProducer` is `track_producer`, and a name /// already in snake case stays as it is. pub fn snake(name: &str) -> String { @@ -727,3 +848,51 @@ pub fn dyn_wrap(form: Dyn, expr: &str) -> String { Dyn::Arc => format!("::std::sync::Arc::new({expr})"), } } + +#[cfg(test)] +mod tests { + use super::shortest; + + /// Each instance's arguments, each by its path's segments, whose forms are their + /// suffixes, shortest first. + fn group(instances: &[&[&[&str]]]) -> Vec>> { + (instances.iter()) + .map(|args| { + (args.iter()) + .map(|segments| { + (1..=segments.len()) + .map(|len| segments[segments.len() - len..].join("_")) + .collect() + }) + .collect() + }) + .collect() + } + + #[test] + fn lengthens_only_where_instances_clash() { + // Only the clashing arguments lengthen, a segment a round, until they differ. + let names = shortest(&group(&[ + &[&["a", "x", "foo"], &["u8"]], + &[&["b", "x", "foo"], &["u8"]], + &[&["foo"], &["u16"]], + &[&["c", "bar"], &["u8"]], + ])); + assert_eq!(names, ["a_x_foo_u8", "b_x_foo_u8", "foo_u16", "bar_u8"]); + // One with no more segments keeps its name while the other lengthens. + assert_eq!( + shortest(&group(&[&[&["foo"]], &[&["polar", "foo"]]])), + ["foo", "polar_foo"] + ); + } + + #[test] + fn names_apart_from_order() { + let instances: [&[&[&str]]; 3] = [&[&["x", "foo"]], &[&["y", "foo"]], &[&["bar"]]]; + let forward = shortest(&group(&instances)); + let mut reversed = shortest(&group(&[instances[2], instances[1], instances[0]])); + reversed.reverse(); + assert_eq!(forward, ["x_foo", "y_foo", "bar"]); + assert_eq!(forward, reversed); + } +} diff --git a/ffi/src/census.rs b/ffi/src/census.rs index 6887a91ec..b80ad9baf 100644 --- a/ffi/src/census.rs +++ b/ffi/src/census.rs @@ -139,21 +139,13 @@ 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 = ["); - // An instance is left out by not naming it. - let (instances, items): (Vec<&Refusal>, Vec<&Refusal>) = collected.refusals.iter().partition(|r| r.named); - let mut paths: Vec<&str> = items.iter().map(|r| r.path.as_str()).collect(); + let mut paths: Vec<&str> = collected.refusals.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 4728df24a..72e5f65ca 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -5,9 +5,11 @@ //! 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. A generic type -//! exports at each instance the config's `instances` names, and only there. +//! exports at the instances it infers: its defaults, each instance an inherent impl is +//! of, its exports' implementations of the traits bounding it, and each instance an export +//! names; and only there. -use std::collections::{BTreeMap, VecDeque}; +use std::collections::VecDeque; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId}; @@ -32,6 +34,9 @@ pub struct Why { pub note: Option<(Span, String)>, } +/// The construct of an instance no export names, which one that does infers. +const UNNAMED: &str = "instance no export names"; + fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -48,8 +53,6 @@ pub struct Refusal { pub kind: &'static str, pub span: Span, pub why: Vec, - /// Whether it is an instance the config's `instances` names, left out by not naming it. - pub named: bool, } /// What collection found. @@ -57,8 +60,6 @@ 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. @@ -69,8 +70,6 @@ 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, of types and functions, with their C names. - pub instances: &'a BTreeMap, } /// What collection found in one exported crate, by paths from its root. @@ -91,9 +90,6 @@ 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. @@ -120,35 +116,24 @@ struct Site<'tcx> { key: Key<'tcx>, /// Its generic arguments as exported, each lifetime `'static`. args: ty::GenericArgsRef<'tcx>, + /// How many of its type arguments it is named by: each up to the last that is not its + /// default, as Rust spells it. + explicit: usize, /// 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, -} - -/// An instance of a generic function or method the config names. -#[derive(Clone)] -struct FnInstance<'tcx> { - def_id: DefId, - /// The argument of each of its own type parameters, by its index in the generics. - args: Vec<(usize, Ty<'tcx>)>, - /// Its arguments as reports name it by: `(from: api_fixture::Point)`. - shown: String, - /// Its C name, without the prefix. - name: String, - /// The config's key, and its crate's root. - key: String, - root: String, - /// Whether an exported type or the crate's root reached it. - reached: bool, +/// The arguments a function exports at: an instance, if a type parameter exports at +/// several types. +struct Instantiation<'tcx> { + args: ty::GenericArgsRef<'tcx>, + /// The type parameters that take a foreign implementation or a lent closure, with the + /// type each takes. + impls: Vec<(Ty<'tcx>, Type)>, + /// The arguments of the type parameters that export at several types, which name it. + named: Vec>, } struct Collector<'tcx> { @@ -156,10 +141,14 @@ struct Collector<'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, Decl>, - /// The instances the config names, in its order. - instances: Vec>, - /// The instances of functions and methods the config names, in its order. - fn_instances: Vec>, + /// The instances generic types export at, each type's by how reports name them. + instances: Vec>, + /// Instances that do not export, and why. + rejected: rustc_data_structures::fx::FxHashMap, Why>, + /// Instances the signature being mapped names that are not yet inferred. + pending: std::cell::RefCell>>, + /// Instances signatures that export but for them name, which the next pass infers. + named: std::cell::RefCell>>, /// The exported crates, the configured one first, and what collection found in each. crates: Vec, reports: Vec, @@ -201,10 +190,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { _ => None, } }); - // Refusing an object no export returns refuses what takes it, which may leave another - // object no export returns, so collection repeats until it refuses no more. - let mut orphans = rustc_data_structures::fx::FxHashSet::default(); - loop { + let pass = |orphans: &rustc_data_structures::fx::FxHashSet>, named: &[Ty<'tcx>]| { let mut c = Collector { tcx, items: Vec::new(), @@ -222,11 +208,12 @@ 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(), - fn_instances: Vec::new(), + rejected: Default::default(), + pending: Default::default(), + named: Default::default(), left_out: Default::default(), impls: Default::default(), bytes, @@ -243,27 +230,36 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { }, }; c.walk(); - c.resolve(crates); + c.infer(named); c.declare(); c.define(); - c.unreached(); + c + }; + // Refusing an object no export returns refuses what takes it, which may leave another + // object no export returns, so collection repeats until it refuses no more. Within each, + // an instance an export names may name more, so it repeats until it infers no more. + let mut orphans = rustc_data_structures::fx::FxHashSet::default(); + loop { + let mut named: Vec> = Vec::new(); + let c = loop { + let c = pass(&orphans, &named); + let more: Vec> = (c.named.borrow().iter().copied()) + .filter(|ty| !named.contains(ty)) + .collect(); + if more.is_empty() { + break c; + } + for ty in more { + if !named.contains(&ty) { + named.push(ty); + } + } + }; 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); @@ -301,7 +297,7 @@ impl<'tcx> Collector<'tcx> { } /// Whether a type or trait takes type or const parameters: a type that does exports - /// only at the instances the config names. + /// only at the instances it infers. 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)) @@ -323,16 +319,17 @@ impl<'tcx> Collector<'tcx> { self.decls.get(&Key { def_id, args: None }) } - /// The types an item declares: itself, or each instance the config names of it. + /// The types an item declares: itself, or each instance it exports at. 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()) + .filter(|site| site.key.def_id == def_id) + .cloned() .collect(); match instances.is_empty() { true => vec![Site { key: Key { def_id, args: None }, args: statics(self.tcx, def_id), + explicit: 0, path: path.clone(), shown: path.clone(), }], @@ -348,7 +345,31 @@ impl<'tcx> Collector<'tcx> { .skip_norm_wip() } - /// A type as an instance's key spells it, each export's by its path in the IR. + /// How many of `def_id`'s type arguments `args` names it by, as Rust spells it: each up + /// to the last that is not its default. + fn explicit(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> usize { + let tcx = self.tcx; + let params: Vec<&ty::GenericParamDef> = (tcx.generics_of(def_id).own_params.iter()) + .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Type { .. })) + .collect(); + let mut explicit = params.len(); + while let Some(param) = explicit.checked_sub(1).map(|i| params[i]) { + let arg = args[param.index as usize]; + match param.default_value(tcx) { + Some(default) + if tcx.erase_and_anonymize_regions(default.instantiate(tcx, args).skip_norm_wip()) + == tcx.erase_and_anonymize_regions(arg) => + { + explicit -= 1 + } + _ => break, + } + } + explicit + } + + /// A type as reports spell it, each export's by its path in the IR, and an instance by + /// the arguments that name it. fn spell(&self, ty: Ty<'tcx>) -> String { let tcx = self.tcx; match ty.kind() { @@ -359,7 +380,8 @@ impl<'tcx> Collector<'tcx> { Some((_, path)) => path.join("::"), None => tcx.def_path_str(adt.did()), }; - let args: Vec = args.types().map(|ty| self.spell(ty)).collect(); + let explicit = self.explicit(adt.did(), args); + let args: Vec = args.types().take(explicit).map(|ty| self.spell(ty)).collect(); match args.is_empty() { true => path, false => format!("{path}<{}>", args.join(", ")), @@ -369,290 +391,181 @@ impl<'tcx> Collector<'tcx> { } } - /// Resolve the instances each export's config names, noting each that names nothing. - fn resolve(&mut self, crates: &[Crate<'_>]) { + /// Infer the instances each generic type exports at: its defaults, the instance each of + /// its inherent impls is of, each choice among its default and the implementations of + /// the traits bounding each parameter, and each instance the last pass's exports + /// `named`, with the instances inside it. + fn infer(&mut self, named: &[Ty<'tcx>]) { let tcx = self.tcx; - for krate in crates { - for (key, name) in krate.instances { - let parsed = crate::config::Key::parse(key).expect("the config checked each key"); - let mut parsed = match parsed { - crate::config::Key::Type(parsed) => parsed, - crate::config::Key::Function { mut path, args } => { - path.insert(0, krate.root.clone()); - match self.fn_instance(&path, &args, key, name) { - Ok(instance) => self.fn_instances.push(instance), - Err((why, span)) => { - let (report, _) = self.report(std::slice::from_ref(&krate.root)); - report.unresolved.push((key.clone(), why, span)); - } - } - continue; + let mut candidates: Vec> = Vec::new(); + for (def_id, _) in self.items.clone() { + if !matches!(tcx.def_kind(def_id), DefKind::Struct | DefKind::Enum) || !self.typed(def_id) { + continue; + } + for &imp in tcx.inherent_impls(def_id) { + let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + if !ty.has_non_region_param() { + candidates.push(ty); + } + } + let mut choices: Vec>> = vec![Vec::new()]; + for param in &tcx.generics_of(def_id).own_params { + let implementors = match param.kind { + ty::GenericParamDefKind::Type { .. } => { + self.implementors(def_id, tcx.mk_param_from_def(param).expect_ty()) } + _ => Vec::new(), }; - parsed.path.insert(0, krate.root.clone()); - let instance = self.instance_ty(&parsed).and_then(|ty| { - 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(), + choices = (choices.into_iter()) + .flat_map(|choice| { + let options: Vec> = match param.kind { + ty::GenericParamDefKind::Lifetime => vec![tcx.lifetimes.re_static.into()], + ty::GenericParamDefKind::Const { .. } => Vec::new(), + ty::GenericParamDefKind::Type { .. } => (param.default_value(tcx)) + .map(|default| default.instantiate(tcx, &choice[..]).skip_norm_wip()) + .into_iter() + .chain(implementors.iter().map(|&ty| ty.into())) + .collect(), + }; + options.into_iter().map(move |option| [&choice[..], &[option]].concat()) }) - }); - 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)); - } - } + .collect(); } + let adt = tcx.adt_def(def_id); + candidates.extend( + choices + .into_iter() + .map(|args| Ty::new_adt(tcx, adt, tcx.mk_args(&args))), + ); } - } - - /// The instance a function key names, at the C name `name`: the function or method its - /// path names, at the argument it gives each type parameter. - fn fn_instance( - &self, - path: &[String], - given: &[(String, crate::config::TypeName)], - key: &str, - name: &str, - ) -> Result, (String, Option)> { - let def_id = self.function_def(path)?; - let span = Some(self.tcx.def_span(def_id)); - let params = self.type_params(def_id).map_err(|why| (why, span))?; - if params.is_empty() { - return Err(("it takes no type parameters".to_string(), span)); - } - let names = || { - params - .iter() - .map(|(name, _)| format!("`{name}`")) - .collect::>() - .join(", ") - }; - if let Some((name, _)) = given.iter().find(|(name, _)| params.iter().all(|(p, _)| p != name)) { - return Err((format!("`{name}` is none of its type parameters {}", names()), span)); - } - let mut args = Vec::new(); - let mut shown = Vec::new(); - for (name, index) in ¶ms { - let Some((_, arg)) = given.iter().find(|(given, _)| given == name) else { - return Err((format!("it needs an argument for `{name}`"), span)); + candidates.extend(named); + // Each with the instances inside it, which its export needs. + let candidates: Vec> = (candidates.iter()) + .flat_map(|ty| ty.walk()) + .filter_map(|arg| arg.as_type()) + .collect(); + for ty in candidates { + let Some((key, site)) = self.admit(ty) else { + continue; }; - let ty = self.instance_ty(arg)?; - args.push((*index, ty)); - shown.push(format!("{name}: {}", self.spell(ty))); - } - let shown = format!("({})", shown.join(", ")); - if let Some(other) = (self.fn_instances.iter()).find(|other| other.def_id == def_id && other.args == args) { - return Err((format!("it is the instance `{}` names", other.key), span)); + match site { + Ok(site) if !self.instances.iter().any(|other| other.key == key) => self.instances.push(site), + Ok(_) => {} + Err(why) => { + self.rejected.insert(key, why); + } + } } - Ok(FnInstance { - def_id, - args, - shown, - name: name.to_string(), - key: key.to_string(), - root: path[0].clone(), - reached: false, - }) + self.instances.sort_by(|a, b| a.shown.cmp(&b.shown)); } - /// The function a path from an export's root names: a `fn` item, or the one inherent - /// method of that name of an exported struct or enum. - fn function_def(&self, path: &[String]) -> Result)> { + /// The types the exports implement a trait bounding `param` of `def_id` for, one of + /// the exports': each impl's in an export, whose type takes no type parameters and is + /// `()`, a primitive, `String`, or an exported type. + fn implementors(&self, def_id: DefId, param: Ty<'tcx>) -> Vec> { let tcx = self.tcx; - let at = |path: &[String]| (self.items.iter()).find(|(_, p)| p == path).map(|(def_id, _)| *def_id); - let none = || { - Err(( - format!("`{}` names no exported function or method", path[1..].join("::")), - None, - )) - }; - if let Some(def_id) = at(path) { - return match tcx.def_kind(def_id) { - DefKind::Fn => Ok(def_id), - _ => none(), + let mut found = Vec::new(); + for clause in tcx.clauses_of(def_id).instantiate_identity(tcx).clauses { + let Some(bound) = clause.skip_norm_wip().as_trait_clause() else { + continue; }; - } - let (name, owner) = path.split_last().expect("a path has a segment"); - let Some(owner) = at(owner).filter(|&owner| matches!(tcx.def_kind(owner), DefKind::Struct | DefKind::Enum)) - else { - return none(); - }; - let methods: Vec = (tcx.inherent_impls(owner).iter()) - .flat_map(|&imp| tcx.associated_items(imp).in_definition_order()) - .filter(|item| matches!(item.kind, ty::AssocKind::Fn { .. }) && item.name().as_str() == name) - .map(|item| item.def_id) - .collect(); - match methods[..] { - [one] => Ok(one), - [] => none(), - _ => Err(( - format!("`{}` names a method of several impls", path[1..].join("::")), - Some(tcx.def_span(owner)), - )), - } - } - - /// A function's own type parameters, in order, each by its index and the name a key - /// gives it: a declared one's own, and an `impl Trait` one's argument's. - fn type_params(&self, def_id: DefId) -> Result, String> { - let tcx = self.tcx; - let inputs = tcx.fn_sig(def_id).skip_binder().skip_binder().inputs(); - let idents = tcx.fn_arg_idents(def_id); - let mut params: Vec<(String, usize)> = Vec::new(); - for param in &tcx.generics_of(def_id).own_params { - let name = match param.kind { - ty::GenericParamDefKind::Lifetime => continue, - ty::GenericParamDefKind::Const { .. } => return Err("it takes a const parameter".to_string()), - ty::GenericParamDefKind::Type { synthetic: false, .. } => param.name.to_string(), - ty::GenericParamDefKind::Type { synthetic: true, .. } => { - let named = |ty: &Ty<'tcx>| { - ty.walk().any( - |arg| matches!(arg.as_type().map(Ty::kind), Some(ty::Param(p)) if p.index == param.index), - ) + if bound.self_ty().skip_binder() != param || !self.exported(bound.def_id().krate) { + continue; + } + for imp in tcx.all_impls(bound.def_id()) { + let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + let inner = ty.peel_refs(); + let named = inner.is_primitive() + || inner.is_unit() + || match inner.kind() { + ty::Adt(adt, _) => { + tcx.lang_items().string() == Some(adt.did()) + || self.items.iter().any(|(item, _)| *item == adt.did()) + } + _ => false, }; - let argument = inputs - .iter() - .position(named) - .and_then(|i| idents.get(i).copied().flatten()); - match argument { - Some(ident) => ident.to_string(), - None => return Err("an `impl Trait` argument no key can name".to_string()), - } + if !self.exported(imp.krate) || ty.has_non_region_param() || !named { + continue; + } + let ty = ty::fold_regions(tcx, ty, |_, _| tcx.lifetimes.re_static); + if !found.contains(&ty) { + found.push(ty); } - }; - if params.iter().any(|(other, _)| *other == name) { - return Err(format!("`{name}` names several of its type parameters")); - } - params.push((name, param.index as usize)); - } - Ok(params) - } - - /// The instances the config names of the function `def_id`, by index. - fn fn_instances_of(&self, def_id: DefId) -> Vec { - (self.fn_instances.iter().enumerate()) - .filter(|(_, instance)| instance.def_id == def_id) - .map(|(i, _)| i) - .collect() - } - - /// Note each function instance the config names that no export reached. - fn unreached(&mut self) { - for instance in self.fn_instances.clone() { - if !instance.reached { - let span = Some(self.tcx.def_span(instance.def_id)); - let (report, _) = self.report(std::slice::from_ref(&instance.root)); - let why = "nothing exported reaches it".to_string(); - report.unresolved.push((instance.key, why, span)); } } + found } - /// 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)> { + /// The instance `ty` is, if it is an exported generic type at arguments without type + /// parameters, or why it does not export: an argument holds an instance of a type + /// inside it, which could otherwise name ever deeper instances, a bound is unmet, or + /// the config excludes it. + fn admit(&mut self, ty: Ty<'tcx>) -> Option<(Key<'tcx>, Result, Why>)> { 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, + let ty::Adt(adt, args) = *ty.kind() else { + return 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 = adt.did(); + let (_, path) = self.items.iter().find(|(item, _)| *item == def_id)?.clone(); + if !matches!(tcx.def_kind(def_id), DefKind::Struct | DefKind::Enum) + || !self.typed(def_id) + || args.has_non_region_param() + { + return 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); + let args = ty::fold_regions(tcx, args, |_, _| tcx.lifetimes.re_static); + let key = self.key(def_id, args); + let spelled = self.spell(ty); + let nests = ty + .walk() + .filter_map(|arg| arg.as_type()) + .any(|outer| match outer.kind() { + ty::Adt(outer, inner) => (inner.iter().flat_map(|arg| arg.walk())).any( + |arg| matches!(arg.as_type().map(Ty::kind), Some(ty::Adt(inner, _)) if inner.did() == outer.did()), + ), + _ => false, + }); + if nests { + return Some(( + key, + Err(why("instance holding an instance of a type inside it", spelled)), + )); } - 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)); + // The IR keeps only an instance's type arguments, which would lose a const one. + if args.consts().next().is_some() { + return Some((key, Err(why("const generic", spelled)))); } - 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)); + return Some((key, Err(why("unmet bound of the instance", clause.to_string())))); } } - Ok(Ty::new_adt(tcx, tcx.adt_def(def_id), args)) + let explicit = self.explicit(def_id, args); + let mut shown = path.clone(); + if explicit > 0 { + let spelled: Vec = args.types().take(explicit).map(|ty| self.spell(ty)).collect(); + let last = shown.last_mut().expect("a path has a segment"); + *last = format!("{last}<{}>", spelled.join(", ")); + } + if self.exclude(&shown) { + return Some((key, Err(why("excluded type", spelled)))); + } + let site = Site { + key, + args, + explicit, + path, + shown, + }; + Some((key, Ok(site))) } - fn refuse(&mut self, path: &[String], kind: &'static str, span: Span, why: Vec, named: bool) { + 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, - named, - }); + report.refusals.push(Refusal { path, kind, span, why }); } /// Every `pub` item reachable from each exported crate's root, breadth first so each @@ -712,7 +625,6 @@ impl<'tcx> Collector<'tcx> { "use", span, vec![why("re-export of another crate's item", other.to_string())], - false, ); continue; } @@ -722,15 +634,15 @@ impl<'tcx> Collector<'tcx> { let (report, rest) = self.report(&path); report.aliases.push(rest); } - DefKind::Macro(_) => self.refuse(&path, "macro", span, vec![why("macro", "")], false), - DefKind::Static { .. } => self.refuse(&path, "static", span, vec![why("static", "")], false), + DefKind::Macro(_) => self.refuse(&path, "macro", span, vec![why("macro", "")]), + DefKind::Static { .. } => self.refuse(&path, "static", span, vec![why("static", "")]), DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait | DefKind::Fn | DefKind::Const => self.items.push((def_id, path)), - _ => self.refuse(&path, "item", span, vec![why("item kind", format!("{kind:?}"))], false), + _ => self.refuse(&path, "item", span, vec![why("item kind", format!("{kind:?}"))]), } } } @@ -756,10 +668,9 @@ impl<'tcx> Collector<'tcx> { loop { self.settle(); let mut changed = false; - for instance in self.instances.clone() { - let site = &instance.site; + for site in self.instances.clone() { if !matches!(self.decls.get(&site.key), Some(Decl::Refused(_)) | None) - && let Err(why) = self.args(site) + && let Err(why) = self.args(&site) { self.decls.insert(site.key, Decl::Refused(why)); changed = true; @@ -887,13 +798,13 @@ impl<'tcx> Collector<'tcx> { } } - /// An instance's type arguments, each of which must export as one the config can - /// spell: a default may name any type. + /// The type arguments an instance is named by, each of which must export as a value or + /// a handle: Rust fills in the defaults after them, which may be any type. fn args(&self, site: &Site<'tcx>) -> Result, Why> { - site.args.types().map(|ty| self.arg(ty)).collect() + site.args.types().take(site.explicit).map(|ty| self.arg(ty)).collect() } - /// A type argument of an instance, which must export as one the config can spell. + /// A type argument that names an instance: a value or a handle. fn arg(&self, ty: Ty<'tcx>) -> Result { let arg = match ty.kind() { ty::Tuple(list) if list.is_empty() => Type::Unit, @@ -910,7 +821,7 @@ impl<'tcx> Collector<'tcx> { | Type::Record(_) | Type::Enum(_) | Type::Object(_) => Ok(arg), - _ => Err(why("type argument the config cannot spell", self.spell(ty))), + _ => Err(why("type argument", self.spell(ty))), } } @@ -1054,6 +965,25 @@ impl<'tcx> Collector<'tcx> { /// A struct's or enum's variants, with their fields mapped. fn fields(&self, site: &Site<'tcx>) -> Result, Vec> { + self.naming(|| self.variants(site)) + } + + /// What `map` makes of a signature or a type's fields, noting each instance it names + /// that is not yet inferred, where those are all it refuses: one an export names is + /// inferred. + fn naming(&self, map: impl FnOnce() -> Result>) -> Result> { + self.pending.borrow_mut().clear(); + let mapped = map(); + let pending = self.pending.take(); + if let Err(why) = &mapped + && why.iter().all(|why| why.construct == UNNAMED) + { + self.named.borrow_mut().extend(pending); + } + mapped + } + + fn variants(&self, site: &Site<'tcx>) -> Result, Vec> { let tcx = self.tcx; let adt = tcx.adt_def(site.key.def_id); let identity = site.args; @@ -1102,10 +1032,10 @@ impl<'tcx> Collector<'tcx> { if !matches!(kind, DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait) { match kind { DefKind::Fn => { - for (function, shown, named) in self.functions(def_id, &path, &path, None, None) { + for (function, shown, _) in self.functions(def_id, &path, &path, None, None) { match function { Ok(function) => self.api.functions.push(function), - Err(why) => self.refuse(&shown, "fn", span, why, named), + Err(why) => self.refuse(&shown, "fn", span, why), } } } @@ -1128,7 +1058,7 @@ impl<'tcx> Collector<'tcx> { DefKind::Union => "union", _ => "struct", }; - self.refuse(&site.shown, kind, span, vec![why], site.key.args.is_some()); + self.refuse(&site.shown, kind, span, vec![why]); continue; } if let Some(Decl::Callback(index)) = decl { @@ -1205,8 +1135,13 @@ impl<'tcx> Collector<'tcx> { } let span = tcx.def_span(field.did); let ty = field.ty(tcx, site.args).skip_norm_wip(); + // An instance's field of `()`, such as a default extension, holds nothing to read. + if ty.is_unit() { + continue; + } // 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) { + let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); + match self.naming(|| self.ty(read, Pos::Return).map_err(|why| vec![why])) { Ok(ty) => getters.push(Function { path: [&site.path[..], &[name]].concat(), span, @@ -1220,7 +1155,7 @@ impl<'tcx> Collector<'tcx> { access: Access::Field { shared }, instance: None, }), - Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, vec![why], false), + Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, why), } } getters @@ -1270,20 +1205,20 @@ impl<'tcx> Collector<'tcx> { })); continue; } - for (function, shown, named) in + for (function, shown, instance) in self.functions(item.def_id, &method, &shown, Some(self_ty), Some(parent)) { match function { Ok(function) => methods.push(function), - Err(why) => refused.push((shown, span, why, named)), + Err(why) => refused.push((shown, span, why, instance)), } } } } // `poll_x` is left out when `x` exports as a future: the future is its poll. - for (method, span, why, named) in refused { + for (method, span, why, instance) in refused { let name = method.last().expect("a method has a name"); - let twin = !named + let twin = !instance && name .strip_prefix("poll_") .is_some_and(|x| methods.iter().any(|m| m.future && m.name() == x)); @@ -1292,7 +1227,7 @@ impl<'tcx> Collector<'tcx> { let (report, rest) = self.report(&method); report.twins.push(rest); } - false => self.refuse(&method, "method", span, why, named), + false => self.refuse(&method, "method", span, why), } } let env = TypingEnv::post_analysis(tcx, def_id); @@ -1388,7 +1323,13 @@ 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), None, None) { + let function = self + .instantiate(item.def_id, None) + .and_then(|instances| match &instances[..] { + [one] if one.named.is_empty() => self.function(item.def_id, method, Some(self_ty), one), + _ => Err(vec![why("generic parameter", name.to_string())]), + }); + match function { 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)) @@ -1418,9 +1359,8 @@ impl<'tcx> Collector<'tcx> { } } - /// A function or method as exported: by the rules, or at each instance the config - /// names of it instead, each with the path reports show it by and whether the config - /// names it. + /// A function or method as exported, at each instance it exports at, each with the path + /// reports show it by and whether it is an instance. fn functions( &mut self, def_id: DefId, @@ -1429,58 +1369,70 @@ impl<'tcx> Collector<'tcx> { self_ty: Option>, parent: Option>, ) -> Vec<(Result>, Path, bool)> { - let named = self.fn_instances_of(def_id); - if named.is_empty() { - let function = self.function(def_id, path.clone(), self_ty, parent, None); - return vec![(function, shown.clone(), false)]; - } + let instances = match self.instantiate(def_id, parent) { + Ok(instances) => instances, + Err(why) => return vec![(Err(why), shown.clone(), false)], + }; let mut functions = Vec::new(); - for i in named { - self.fn_instances[i].reached = true; - let instance = &self.fn_instances[i]; + for instance in &instances { let mut shown = shown.clone(); - *shown.last_mut().expect("a path has a segment") += &instance.shown; - let function = self.function(def_id, path.clone(), self_ty, parent, Some(instance)); - functions.push((function, shown, true)); + if !instance.named.is_empty() { + let spelled: Vec = instance.named.iter().map(|&ty| self.spell(ty.peel_refs())).collect(); + *shown.last_mut().expect("a path has a segment") += &format!("<{}>", spelled.join(", ")); + if self.exclude(&shown) { + continue; + } + } + let function = self.function(def_id, path.clone(), self_ty, instance); + functions.push((function, shown, !instance.named.is_empty())); } functions } - /// A function or method's signature, with its type parameters chosen by the rules, or - /// as the config's `instance` of it names them: a method's receiver is `self_ty`, at - /// its impl's `parent` arguments. + /// A function or method's signature at one of its instances: a method's receiver is + /// `self_ty`. fn function( &self, def_id: DefId, path: Path, self_ty: Option>, - parent: Option>, - instance: Option<&FnInstance<'tcx>>, + instance: &Instantiation<'tcx>, + ) -> Result> { + self.naming(|| self.signature(def_id, path, self_ty, instance)) + } + + fn signature( + &self, + def_id: DefId, + path: Path, + self_ty: Option>, + instance: &Instantiation<'tcx>, ) -> Result> { let tcx = self.tcx; let mut errs = Vec::new(); - self.impls.borrow_mut().clear(); - let args = match instance { - Some(instance) => self.instance_args(def_id, parent, instance)?, - None => self.instantiate(def_id, parent)?, - }; + *self.impls.borrow_mut() = instance.impls.clone(); + let args = instance.args; // What the glue names a declared type parameter as, which a call cannot always // infer; an `impl Trait` one cannot be named, and is inferred from its argument. - let instance = instance.map(|instance| { - let declared = (tcx.generics_of(def_id).own_params.iter()) - .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Type { synthetic: false, .. })); - let args = declared - .filter_map(|p| { - self.arg(args.type_at(p.index as usize)) - .map_err(|why| errs.push(why)) - .ok() - }) - .collect(); - crate::ir::Instance { - name: instance.name.clone(), - args, + let mut arg = |ty: Ty<'tcx>| { + let mapped = match *ty.kind() { + ty::Ref(_, inner, ty::Mutability::Not) => { + self.arg(inner).map(|inner| Type::Ref(Mutability::Not, Box::new(inner))) + } + _ => self.arg(ty), + }; + mapped.map_err(|why| errs.push(why)).ok() + }; + let instance = match instance.named.is_empty() { + true => None, + false => { + let declared = (tcx.generics_of(def_id).own_params.iter()) + .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Type { synthetic: false, .. })); + let args = declared.filter_map(|p| arg(args.type_at(p.index as usize))).collect(); + let named = instance.named.iter().filter_map(|&ty| arg(ty.peel_refs())).collect(); + Some(crate::ir::Instance { args, named }) } - }); + }; 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()); @@ -1585,49 +1537,16 @@ impl<'tcx> Collector<'tcx> { } } - /// The generic arguments of a function instance the config names: its parent's, its - /// lifetimes as they are, and its own type parameters' as the instance names them, - /// where its bounds hold. - fn instance_args( - &self, - def_id: DefId, - parent: Option>, - instance: &FnInstance<'tcx>, - ) -> Result, Vec> { - let tcx = self.tcx; - let mut args = ty::GenericArgs::identity_for_item(tcx, def_id).to_vec(); - if let Some(parent) = parent { - args[..parent.len()].copy_from_slice(parent); - } - for &(index, ty) in &instance.args { - args[index] = ty.into(); - } - let args = tcx.mk_args(&args); - let env = TypingEnv::post_analysis(tcx, def_id); - let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); - let unmet: Vec = (tcx.clauses_of(def_id).instantiate(tcx, args).clauses.iter()) - .map(|clause| clause.skip_norm_wip()) - .filter(|&clause| { - let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause); - !infcx.predicate_must_hold_modulo_regions(&obligation) - }) - .map(|clause| why("unmet bound of the instance", clause.to_string())) - .collect(); - match unmet.is_empty() { - true => Ok(args), - false => Err(unmet), - } - } - /// 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`]. + /// parameter by the rules in [`Self::choose`], or else at each type [`Self::each`] + /// finds, an instance for each choice where its bounds hold. fn instantiate( &self, def_id: DefId, parent: Option>, - ) -> Result, Vec> { + ) -> Result>, Vec> { let tcx = self.tcx; let generics = tcx.generics_of(def_id); let identity = ty::GenericArgs::identity_for_item(tcx, def_id); @@ -1638,6 +1557,8 @@ impl<'tcx> Collector<'tcx> { args[..count].copy_from_slice(parent); } let base = args.clone(); + let mut impls = Vec::new(); + let mut several = Vec::new(); for (i, arg) in identity.iter().enumerate() { match arg.kind() { _ if i < count => {} @@ -1646,7 +1567,7 @@ impl<'tcx> Collector<'tcx> { // The parameter stays, and `ty` maps it to the closure. GenericArgKind::Type(param) if let Some(closure) = self.closure(def_id, param, &base) => { match closure { - Ok(closure) => self.impls.borrow_mut().push((param, closure)), + Ok(closure) => impls.push((param, closure)), Err(why) => errs.push(why), } } @@ -1657,18 +1578,58 @@ impl<'tcx> Collector<'tcx> { construct: "callback bound", .. }) if let Some(callback) = self.foreign(def_id, param) => { - self.impls - .borrow_mut() - .push((param, Type::Callback(callback, Dyn::Impl))); + impls.push((param, Type::Callback(callback, Dyn::Impl))); } - Err(why) => errs.push(why), + Err(why) => match self.each(def_id, param, &base)[..] { + [] => errs.push(why), + ref each => several.push((i, each.to_vec())), + }, }, } } - match errs.is_empty() { - true => Ok(tcx.mk_args(&args)), - false => Err(errs), + if !errs.is_empty() { + return Err(errs); + } + let mut choices = vec![(args, Vec::new())]; + for (i, each) in several { + choices = (choices.into_iter()) + .flat_map(|(args, named): (Vec>, Vec>)| { + each.iter().map(move |&ty| { + let mut args = args.clone(); + args[i] = ty.into(); + (args, [&named[..], &[ty]].concat()) + }) + }) + .collect(); } + let env = TypingEnv::post_analysis(tcx, def_id); + let instances: Vec> = (choices.into_iter()) + .map(|(args, named)| (tcx.mk_args(&args), named)) + .filter(|(args, named)| named.is_empty() || self.holds(def_id, args, env)) + .map(|(args, named)| Instantiation { + args, + impls: impls.clone(), + named, + }) + .collect(); + match instances.is_empty() { + true => Err(vec![why("generic parameters no choice meets the bounds of", "")]), + false => Ok(instances), + } + } + + /// Whether `def_id`'s bounds hold at `args`. + fn holds(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>, env: TypingEnv<'tcx>) -> bool { + let tcx = self.tcx; + let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); + tcx.clauses_of(def_id) + .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) + }) } /// The type a type parameter is exported as: `X` for `impl Into` or @@ -1723,25 +1684,9 @@ impl<'tcx> Collector<'tcx> { candidates.push(Ty::new_adt(tcx, tcx.adt_def(vec), args)); } } - let env = TypingEnv::post_analysis(tcx, def_id); - 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 = base.to_vec(); - args[p.index as usize] = candidate.into(); - 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 at(candidate).is_some() && self.ty(candidate, Pos::Param).is_ok() { + if self.at(def_id, param, base, candidate).is_some() && self.ty(candidate, Pos::Param).is_ok() { return Ok(candidate); } } @@ -1757,12 +1702,67 @@ impl<'tcx> Collector<'tcx> { .filter(|b| !sized.contains(&Some(b.def_id()))) .map(|b| tcx.def_path_str(b.def_id())) .collect(); - if let [_] = local.as_slice() { - return Err(why("callback bound", names.join(" + "))); + match local[..] { + [_] => Err(why("callback bound", names.join(" + "))), + _ => Err(why("generic parameter", names.join(" + "))), + } + } + + /// The arguments with `param` of `def_id` as `candidate`, if its bounds hold there. + fn at( + &self, + def_id: DefId, + param: Ty<'tcx>, + base: &[ty::GenericArg<'tcx>], + candidate: Ty<'tcx>, + ) -> Option> { + let tcx = self.tcx; + 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 args = tcx.mk_args(&args); + self.holds(def_id, args, TypingEnv::post_analysis(tcx, def_id)) + .then_some(args) + } + + /// The types a type parameter exports at each of, where no one type is the rules': + /// each type the exports implement a trait bounding it for, or a reference to it where + /// that meets the bounds too, which leaves C its handle; and, as an argument of a + /// generic type the signature names, each argument of an instance that meets its + /// bounds where each generic type the signature names is an instance. + fn each(&self, def_id: DefId, param: Ty<'tcx>, base: &[ty::GenericArg<'tcx>]) -> Vec> { + let tcx = self.tcx; + let env = TypingEnv::post_analysis(tcx, def_id); + let at = |candidate: Ty<'tcx>| self.at(def_id, param, base, candidate); + // A lifetime bound, such as `'static`, which a reference to a value C passes for the + // call cannot meet, though `at` holds modulo regions. + let outlives = (tcx + .clauses_of(def_id) + .instantiate(tcx, tcx.mk_args(base)) + .clauses + .iter()) + .filter_map(|clause| clause.skip_norm_wip().as_type_outlives_clause()) + .any(|pred| pred.skip_binder().0 == param); + let mut found: Vec> = Vec::new(); + for ty in self.implementors(def_id, param) { + if outlives && ty.is_ref() { + continue; + } + // An implementation for `&X` is taken as it is: C passes no reference to one. + let borrowed = (!ty.is_ref() && !outlives).then(|| Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty)); + let ty = match borrowed.filter(|&borrowed| at(borrowed).is_some()) { + Some(borrowed) => borrowed, + None if at(ty).is_some() => ty, + None => continue, + }; + // `X` and an implementation for `&X` both choose `&X`. + let ty = tcx.erase_and_anonymize_regions(ty); + if !found.contains(&ty) && self.ty(ty, Pos::Param).is_ok() { + found.push(ty); + } } - // 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, @@ -1778,15 +1778,17 @@ impl<'tcx> Collector<'tcx> { .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() { + for site in self.instances.iter().filter(|_| argument) { + for candidate in site.args.types() { let erased = tcx.erase_and_anonymize_regions(candidate); - if found.iter().any(|&f| tcx.erase_and_anonymize_regions(f) == erased) { + if found + .iter() + .any(|&f| tcx.erase_and_anonymize_regions(f.peel_refs()) == erased) + { continue; } let Some(args) = at(candidate) else { @@ -1803,14 +1805,7 @@ impl<'tcx> Collector<'tcx> { } } } - 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(", "))) - } - } + found } /// The closure a type parameter takes, if an `Fn` trait bounds it: one the callee calls @@ -2171,13 +2166,14 @@ impl<'tcx> Collector<'tcx> { Err(why) => why, }; if why.construct != "constant type" { - self.refuse(&path, "const", span, vec![why], false); + self.refuse(&path, "const", span, vec![why]); return None; } tcx.type_of(def_id).instantiate_identity().skip_norm_wip() } }; - match self.ty(ty, Pos::Return) { + // Through `naming`, so an instance only a constant names is inferred. + match self.naming(|| self.ty(ty, Pos::Return).map_err(|why| vec![why])) { Ok(ok) => Some(Function { path, span, @@ -2192,7 +2188,7 @@ impl<'tcx> Collector<'tcx> { instance: None, }), Err(why) => { - self.refuse(&path, "const", span, vec![why], false); + self.refuse(&path, "const", span, why); None } } @@ -2345,11 +2341,13 @@ impl<'tcx> Collector<'tcx> { 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) - ); + if let Some(why) = self.rejected.get(&key) { + return Err(why.clone()); + } + // Inferred if this is all its export refuses. + self.pending.borrow_mut().push(ty); + let mut why = why(UNNAMED, name); + let note = format!("`{}` exports only at the instances it infers", strip_args(tcx, did)); why.note = Some((tcx.def_span(did), note)); return Err(why); } diff --git a/ffi/src/config.rs b/ffi/src/config.rs index e6be19d57..289b62a51 100644 --- a/ffi/src/config.rs +++ b/ffi/src/config.rs @@ -25,24 +25,14 @@ pub struct Config { /// named through its new name. A field is named by its path as `exclude` names it. #[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. A key may name a generic - /// function or method instead, with an argument for each of its type parameters by - /// name, an `impl Trait` one by its argument's: - /// `"Counter::seeded(from: api_fixture::Point)" = "counter_seeded_point"`. - #[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, renames them, and names its instances, as -/// `exclude`, `rename`, and `instances` do the package's. +/// What leaves another export's items out and renames them, as `exclude` and `rename` do +/// the package's. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct Items { @@ -50,8 +40,6 @@ pub struct Items { pub exclude: Vec, #[serde(default)] pub rename: BTreeMap, - #[serde(default)] - pub instances: BTreeMap, } impl Config { @@ -65,10 +53,6 @@ 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) { - Key::parse(key).map_err(|err| format!("{}: instance `{key}`: {err}", path.display()))?; - } Ok(config) } @@ -78,120 +62,6 @@ impl Config { } } -/// A key of `instances`: a generic type, or a generic function or method with the argument -/// of each of its type parameters by name. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Key { - Type(TypeName), - Function { - path: Vec, - args: Vec<(String, TypeName)>, - }, -} - -impl Key { - /// The instance `text` names, or why it names none. - pub fn parse(text: &str) -> Result { - let mut rest = text; - let name = TypeName::parse_from(&mut rest)?; - let key = match eat(&mut rest, "(") { - false => Self::Type(name), - true if !name.args.is_empty() => { - return Err("a function's type arguments are named in its parentheses, as `f(T: u8)`".to_string()); - } - true => { - let mut args: Vec<(String, TypeName)> = Vec::new(); - while !eat(&mut rest, ")") { - let param = ident(&mut rest, "a parameter's name")?; - if !eat(&mut rest, ":") { - return Err(format!("expected `:` at `{rest}`")); - } - if args.iter().any(|(other, _)| *other == param) { - return Err(format!("`{param}` is named twice")); - } - args.push((param, TypeName::parse_from(&mut rest)?)); - if !eat(&mut rest, ",") && !rest.starts_with(')') { - return Err(format!("expected `,` or `)` at `{rest}`")); - } - } - Self::Function { path: name.path, args } - } - }; - match rest.trim_start() { - "" => Ok(key), - extra => Err(format!("unexpected `{extra}`")), - } - } -} - -/// 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 `rest` starts with, which it advances past. - fn parse_from(rest: &mut &str) -> Result { - 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 { - path.push(ident(rest, "a path")?); - 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 }) - } -} - -/// Whether `rest` starts with `token` past whitespace, advancing past it if so. -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 -} - -/// The identifier `rest` starts with past whitespace, `what` the key expects there, -/// which it advances past. -fn ident(rest: &mut &str, what: &str) -> Result { - *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 {what} at `{rest}`")); - } - *rest = &rest[len..]; - Ok(ident.to_string()) -} - /// 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 9a010bd0d..cb6e3e74a 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -105,7 +105,7 @@ impl Callbacks for Export { renames.insert(format!("{field}{}::{path}", report.krate), name.clone()); } } - let abi = Abi::new(&collected.api, &self.config.prefix(), &renames, &collected.instances); + let abi = Abi::new(&collected.api, &self.config.prefix(), &renames); for key in abi.unused_renames() { let (field, key) = field(key); let (krate, path) = key.split_once("::").expect("a rename starts with its crate"); @@ -114,22 +114,6 @@ 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)); @@ -147,15 +131,10 @@ impl Callbacks for Export { false => format!("{} `{}`", why.construct, why.detail), }) .collect(); - // An instance is left out by not naming it. - let fix = match refusal.named { - true => format!("drop it from {table}'s `instances`"), - false => format!("exclude it in {table} to leave it out"), - }; let mut err = tcx.dcx().struct_span_err( refusal.span, format!( - "rust2-ffi: cannot export {} `{}`: {}; {fix}", + "rust2-ffi: cannot export {} `{}`: {}; exclude it in {table} to leave it out", refusal.kind, refusal.path, reasons.join("; ") @@ -252,17 +231,16 @@ impl Export { Output::Census(_) => &[], Output::Dir(_) => self.items(package).0, }, - instances: self.items(package).2, }); } Some(crates) } - /// The config's `exclude`, `rename`, and `instances` for `package`. - fn items(&self, package: &str) -> (&[String], &BTreeMap, &BTreeMap) { + /// The config's `exclude` and `rename` for `package`. + fn items(&self, package: &str) -> (&[String], &BTreeMap) { match self.config.crates.get(package) { - Some(items) => (&items.exclude, &items.rename, &items.instances), - None => (&self.config.exclude, &self.config.rename, &self.config.instances), + Some(items) => (&items.exclude, &items.rename), + None => (&self.config.exclude, &self.config.rename), } } diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index bddc63c72..1917da348 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -159,17 +159,18 @@ pub struct Function { pub eager: bool, /// What it reads: Rust's function, or a field or constant named as it is. pub access: Access, - /// The instance the config names, if it is generic. + /// The instance it is, if a type parameter exports at several. pub instance: Option, } -/// An instance of a generic function or method the config names. +/// An instance of a generic function or method, at one of the types a type parameter +/// exports at. pub struct Instance { - /// Its C name, without the prefix. - pub name: String, /// The arguments of its declared type parameters, which the call names, as Rust /// cannot infer one no argument names; its argument infers an `impl Trait` one. pub args: Vec, + /// The arguments that tell it from its other instances, which name it. + pub named: Vec, } /// What an exported function reads. diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 173679fd0..ddaf4f863 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -360,46 +360,66 @@ 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); + /* Generic types, each at the instances it infers, named by their arguments. */ + api_pair_u32 pair = {.left = 2, .right = 5}; + api_pair_u32 swapped = api_pair_u32_swap(&pair); + printf("pair %u %u sum %u ", swapped.left, swapped.right, api_pair_u32_sum(&pair)); + print("", api_pair_u32_debug(&pair), " "); + printf("%s\n", api_pair_u32_eq(&pair, &swapped) ? "true" : "false"); + api_pair_u32 twins = {.left = 7, .right = 7}; + printf("even %s %s\n", api_pair_u32_even(&pair) ? "true" : "false", + api_pair_u32_even(&twins) ? "true" : "false"); + api_pair_size_u8 sizes = api_tag((api_size){.width = 1, .height = 2}, 3); + api_pair_u8_size flipped = api_pair_size_u8_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); + print("", api_pair_u8_size_debug(&flipped), "\n"); + api_pair_u32 byte = {.left = 258, .right = 9}; + api_pair_u8_size beside = api_pair_u32_beside_size(&byte, sizes.left); printf("beside %u ", beside.left); - print("", api_pair_size_debug(&beside), "\n"); - api_counters *stack = api_counters_new(); + print("", api_pair_u8_size_debug(&beside), "\n"); + /* At its default, named as the type itself. */ + api_stack *stack = api_stack_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_stack_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 *top = api_stack_pop(stack); + printf("stack %zu Some(%llu)", api_stack_depth(stack), (unsigned long long)api_counter_get(top)); api_counter_free(top); - api_counter *next = api_counters_pop(stack); + api_counter *next = api_stack_pop(stack); printf(" %s", next != NULL ? "true" : "false"); api_counter_free(next); - printf(" %s\n", api_counters_pop(stack) == NULL ? "true" : "false"); - /* Generic functions and methods, at each instance the config names, by its own name. */ + printf(" %s\n", api_stack_pop(stack) == NULL ? "true" : "false"); + /* Generic functions and methods, at each implementation of the trait bounding them, by + reference, which leaves C its handle. */ api_counter *from_point = api_counter_seeded_point(str("p"), (api_point){.x = -3, .y = 4}); api_counter *from_size = api_counter_seeded_size(str("s"), (api_size){.width = 5, .height = 6}); - printf("seeded %llu %llu past %llu seeds %llu\n", (unsigned long long)api_counter_get(from_point), - (unsigned long long)api_counter_get(from_size), - (unsigned long long)api_counters_depth_past_point(stack, (api_point){.x = 1, .y = 2}), - (unsigned long long)api_seeds((api_size){.width = 2, .height = 3})); + api_counter *from_counter = api_counter_seeded_counter(str("c"), from_point); + /* Two instances whose arguments share a last segment: one takes its module too. */ + api_counter *from_polar = api_counter_seeded_polar_point(str("q"), (api_polar_point){.turns = 1, .distance = 2}); + printf("seeded %llu %llu %llu %llu past %llu seeds %llu\n", (unsigned long long)api_counter_get(from_point), + (unsigned long long)api_counter_get(from_size), (unsigned long long)api_counter_get(from_counter), + (unsigned long long)api_counter_get(from_polar), + (unsigned long long)api_stack_depth_past_point(stack, (api_point){.x = 1, .y = 2}), + (unsigned long long)api_seeds_point_size((api_size){.width = 2, .height = 3})); api_counter_free(from_point); api_counter_free(from_size); - api_counters_free(stack); + api_counter_free(from_counter); + api_counter_free(from_polar); + api_stack_free(stack); + + /* A trait implemented for `Point` and `&Point` apart: one instance. */ + printf("weigh %u\n", api_weigh_point((api_point){.x = -1, .y = 2})); + /* Instances that name each other, and one made only by an impl of it. */ + api_outer_inner_u8 *outer = api_outer_inner_u8_new(4); + printf("cross %u outer %u\n", + api_cross((api_left_right_u8){.value = {.value = 1}}, (api_right_left_u8){.value = {.value = 2}}), + api_outer_inner_u8_get(outer)); + api_outer_inner_u8_free(outer); + /* A bound that outlives the call takes a value, and an instance only a constant names. */ + printf("kept %llu boxed %u\n", (unsigned long long)api_kept_point((api_point){.x = 1, .y = -2}), api_boxed().value); /* Its Drop runs when C frees the handle, not before. */ api_token *token = api_token_new(7); @@ -412,9 +432,9 @@ static int script(void) { api_option_u32 limit = api_retry_limit_setting(retry); printf("retry %d %u %u %u\n", limit.some, limit.value, api_retry_limit(retry), api_retry_delay(retry)); api_retry_free(retry); - api_byte_slot *slot = api_byte_slot_new(200); - printf("slot %u\n", api_byte_slot_value(slot)); - api_byte_slot_free(slot); + api_slot_u8 *slot = api_slot_u8_new(200); + printf("slot %u\n", api_slot_u8_value(slot)); + api_slot_u8_free(slot); /* Each future dropped its waker once it finished, and Rust the one it was given. */ return drops == 5 ? 0 : 1; } diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index f61a3485e..60cd1072a 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -308,22 +308,23 @@ int script() { std::printf("area %u %u %llu\n", size.width, size.height, ull(area.pixels())); } - // Generic types, each at the instances the config names under their own names. - api::pair pair{2, 5}; - api::pair swapped = pair.swap(); + // Generic types, each at the instances it infers, named by their arguments. + api::pair_u32 pair{2, 5}; + api::pair_u32 swapped = pair.swap(); std::printf("pair %u %u sum %u ", swapped.left, swapped.right, pair.sum()); print("", pair.debug(), " "); std::printf("%s\n", yes(pair == swapped)); - std::printf("even %s %s\n", yes(pair.even()), yes(api::pair{7, 7}.even())); - api::size_pair sizes{{1, 2}, 3}; - api::pair_size flipped = sizes.swap(); + std::printf("even %s %s\n", yes(pair.even()), yes(api::pair_u32{7, 7}.even())); + api::pair_size_u8 sizes = api::tag({1, 2}, 3); + api::pair_u8_size flipped = sizes.swap(); std::printf("sized %u %u ", flipped.left, flipped.right.width); print("", flipped.debug(), "\n"); - api::pair_size beside = api::pair{258, 9}.beside(sizes.left); + api::pair_u8_size beside = api::pair_u32{258, 9}.beside_size(sizes.left); std::printf("beside %u ", beside.left); print("", beside.debug(), "\n"); { - api::counters stack = api::counters::new_(); + // At its default, named as the type itself. + api::stack stack = api::stack::new_(); const char *names[] = {"a", "b"}; for (int i = 0; i < 2; i++) { stack.push(api::counter::new_(names[i], static_cast(i) + 1)); @@ -332,13 +333,26 @@ int script() { std::printf("stack %zu Some(%llu)", stack.depth(), ull(top->get())); std::printf(" %s", yes(stack.pop().has_value())); std::printf(" %s\n", yes(!stack.pop().has_value())); - // Generic functions and methods, at each instance the config names, by its own name. + // Generic functions and methods, at each implementation of the trait bounding them, + // by reference, which leaves C++ its handle. Two arguments sharing a last segment + // name their instances apart by the module of one. api::counter from_point = api::counter::seeded_point("p", {-3, 4}); api::counter from_size = api::counter::seeded_size("s", {5, 6}); - std::printf("seeded %llu %llu past %llu seeds %llu\n", ull(from_point.get()), ull(from_size.get()), - ull(stack.depth_past_point({1, 2})), ull(api::seeds({2, 3}))); + api::counter from_counter = api::counter::seeded_counter("c", from_point); + api::counter from_polar = api::counter::seeded_polar_point("q", {1, 2}); + std::printf("seeded %llu %llu %llu %llu past %llu seeds %llu\n", ull(from_point.get()), ull(from_size.get()), + ull(from_counter.get()), ull(from_polar.get()), ull(stack.depth_past_point({1, 2})), + ull(api::seeds_point_size({2, 3}))); } + // A trait implemented for `Point` and `&Point` apart: one instance. + std::printf("weigh %u\n", api::weigh_point({-1, 2})); + // Instances that name each other, and one made only by an impl of it. + std::printf("cross %u outer %u\n", api::cross(api::left_right_u8{api::right_u8{1}}, api::right_left_u8{api::left_u8{2}}), + api::outer_inner_u8::new_(4).get()); + // A bound that outlives the call takes a value, and an instance only a constant names. + std::printf("kept %llu boxed %u\n", ull(api::kept_point({1, -2})), api::boxed().value); + // Its Drop runs when C++ destroys the handle, not before. { api::token token = api::token::new_(7); @@ -350,7 +364,7 @@ int script() { api::retry retry = api::retry::new_(5u); std::optional limit = retry.limit_setting(); std::printf("retry %d %u %u %u\n", limit.has_value(), limit.value_or(0), retry.limit(), retry.delay()); - std::printf("slot %u\n", api::byte_slot::new_(200).value()); + std::printf("slot %u\n", api::slot_u8::new_(200).value()); return 0; } diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 7c591df36..b56623757 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -47,7 +47,7 @@ Every generator on the C ABI: ## Required -- [Instances the config can't name yet](/quest/m1/ffi-export/instance-keys.md) - `&T` keys, `IntoIterator` as a `Vec`, `serde_json::Value`, and `Catalog<()>` +- [Iterator and JSON arguments the exporter can't map yet](/quest/m1/ffi-export/instance-keys.md) - `IntoIterator` as a `Vec`, and `serde_json::Value` - [moq-clock's C names once it moves into kio](/quest/m1/ffi-export/crates.md) - `moq_now` and `moq_origin` become the clock's, after moq moves it into `kio::clock` - [Setters for an object's pub fields](/quest/m1/ffi-export/field-setters.md) - C fills in a session's config, as Rust assigns it - [Session config's foreign types](/quest/m1/ffi-export/foreign-types.md) - `Url`, `SocketAddr`, `PathBuf`, and `Vec` cross the C ABI diff --git a/quest/m1/ffi-export/instance-keys.md b/quest/m1/ffi-export/instance-keys.md index 10bd32b80..7fd539cb9 100644 --- a/quest/m1/ffi-export/instance-keys.md +++ b/quest/m1/ffi-export/instance-keys.md @@ -1,22 +1,27 @@ -# [M] Instances the config can't name yet +# [M] Iterator and JSON arguments the exporter can't map yet ## Goal -The exporter's `instances` key names the instances moq-ffi still wraps by hand: a `&T` -argument (`with_publisher` at `&origin::Producer`, as moq-ffi passes it), -`impl IntoIterator` exported as a `Vec` of `X`, `serde_json::Value` as the `T` of -`catalog::Producer`'s `json_snapshot` and `json_stream`, and `DEFAULT_NAME` on -`hang::Catalog<()>`. +moq-net's `track::Subscription::with_ranges(impl IntoIterator)` exports, +taking a `Vec` of `Range`, and moq-mux's `catalog::Producer::json_snapshot` and +`json_stream` export at `serde_json::Value` as their `T`, crossing as something every +generator can read. Both come from fixed rules, with no config: moq's crates export as +they are. ## Plan -Left out of [#126](https://github.com/kixelated/rust2/pull/126), which exports generic -functions at config-named instances; decided with the maintainer on 2026-10-27 to plan -them all. +Decided with the maintainer on 2026-10-27, superseding this quest's plan to extend the +config's `instances` key: translators take stock crates as they are, so the exporter +infers the instances it exports at, and the `instances` key is gone +([#152](https://github.com/kixelated/rust2/pull/152)). That PR also exports this quest's +other two items: moq-net's `with_publisher` at `&origin::Producer`, and `DEFAULT_NAME` on +hang's `Catalog<()>`. What remains is two type mappings. -- `IntoIterator` as a `Vec` needs `Vec` of records to map first. +- `IntoIterator` as a `Vec` needs a `Vec` of records to map first. - `serde_json::Value` crosses the C ABI as something every generator can read; decide - its shape (JSON text is the obvious one) when the quest starts. + its shape (JSON text is the obvious one) when the quest starts. Today the `T: Serialize` + parameter is refused as a generic parameter, though `String` meets its bound: find out + why first. - Report moq-ffi's coverage and the census before and after. -Public API: the exporter's config and the C names it emits. +Public API: the C names and types these methods export with.