Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ffi/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,14 @@
`detail`) and every variant's payload name (`<enum>_<variant>`, 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<u8, dep_fixture::Size>"`, 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<catalog::hang::Extra>` 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.
49 changes: 29 additions & 20 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<moq_mux::catalog::hang::Extra>" = "catalog_producer"
"catalog::Producer::binary_stream(config: moq_mux::binary::Config)" = "catalog_producer_binary_stream"
```

## Rules
Expand All @@ -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 |
Expand All @@ -87,7 +77,16 @@ export's, and adds nothing; another crate's type is refused.
| `Option<T>` | a null handle or buffer, or `<prefix>_option_<T>` |
| a `pub const` | a `#define` if a `bool` or integer, else a function returning it |
| `impl Into<X>`, `impl AsRef<X>` | `X` |
| another type parameter | the first of `String`, `Bytes`, and `Vec<u8>` 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<u8>` 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<u32>`; 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<Cell<u8>>`, 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
Expand Down Expand Up @@ -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<moq_mux::catalog::hang::Extra>::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<catalog::hang::Extra>` 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<moq_mux::catalog::hang::Extra>::stats"`) out of that one; a
`rename` by the generic item's path renames each of its instances.

## C++

Expand Down Expand Up @@ -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 `<package>.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

Expand Down
33 changes: 26 additions & 7 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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::<Point>(Size { width: 2, height: 3 })
from_counter.get(),
from_polar.get(),
stack.depth_past(&Point { x: 1, y: 2 }),
api_lib::seeds::<Point>(&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);
Expand Down
29 changes: 11 additions & 18 deletions ffi/fixtures/api/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>`'s do. `Slot<u32>` has no such method, so its path alone names its field.
exclude = ["Node::next", "Pair<u8, dep_fixture::Size>::swap", "Seed", "Slot<u32>::value", "field@Retry::delay", "field@Slot<u8>::value"]
# `Slot<u8>`'s do. `Slot<u32>` 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<u8, dep_fixture::Size>::swap",
"Seed",
"Slot<u32>::value",
"field@Retry::delay",
"field@Slot<u8>::value",
"Stack::depth_past<api_fixture::polar::Point>",
]

# 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<u32>` is
# `Pair<u32, u32>`, and `swap` returns each `Pair` of a `Size` as the other.
[instances]
"Pair<u32>" = "pair"
"Pair<dep_fixture::Size, u8>" = "size_pair"
"Pair<u8, dep_fixture::Size>" = "pair_size"
"Stack<api_fixture::Counter>" = "counters"
"Slot<u8>" = "byte_slot"
"Slot<u32>" = "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"]
127 changes: 119 additions & 8 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<L, R = L> {
pub left: L,
Expand All @@ -618,14 +618,14 @@ impl<L: Copy, R: Copy> Pair<L, R> {
}
}

/// 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<u32> {
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<T: Copy>(&self, right: T) -> Pair<u8, T> {
Pair {
left: self.left as u8,
Expand All @@ -634,9 +634,15 @@ impl Pair<u32> {
}
}

/// 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<Size, u8> {
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<T> {
pub struct Stack<T = Counter> {
items: Vec<T>,
}

Expand Down Expand Up @@ -664,11 +670,93 @@ impl<T> Stack<T> {
}

/// 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<T> {
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<u32> for Point {
fn seed(&self) -> u32 {
self.x.unsigned_abs() + self.y.unsigned_abs()
}
}

impl Seed<u32> for &Point {
fn seed(&self) -> u32 {
Seed::<u32>::seed(*self)
}
}

/// Two generic records whose instances name each other, as `Left<Right<u8>>` and
/// `Right<Left<u8>>` do: each instance is named without the other's name.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Left<T> {
pub value: T,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Right<T> {
pub value: T,
}

/// The sum of what each holds inside.
pub fn cross(left: Left<Right<u8>>, right: Right<Left<u8>>) -> 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>(T);

impl Outer<Inner<u8>> {
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<T> {
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<u64> + 'static) -> u64 {
from.seed()
}

/// A generic record only a constant names, which infers its instance.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Boxed<T> {
pub value: T,
}

pub const BOXED: Boxed<u16> = Boxed { value: 42 };

/// `from`'s weight.
pub fn weigh(from: impl Seed<u32>) -> u32 {
from.seed()
}

impl<S: Seed<u64>> Seed<u64> for &S {
fn seed(&self) -> u64 {
(**self).seed()
}
}

impl Seed<u64> for Counter {
fn seed(&self) -> u64 {
self.value
}
}

impl Seed<u64> for Point {
fn seed(&self) -> u64 {
u64::from(self.x.unsigned_abs()) + u64::from(self.y.unsigned_abs())
Expand All @@ -681,8 +769,26 @@ impl Seed<u64> 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<u64> 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<u64>) -> Counter {
Counter::new(name, from.seed())
}
Expand Down Expand Up @@ -722,3 +828,8 @@ impl Slot<u8> {
u16::from(self.value) * 2
}
}

/// A wide slot: a signature that names `Slot<u32>`, which infers it.
pub fn wide(value: u32) -> Slot<u32> {
Slot::new(value)
}
Loading