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
3 changes: 3 additions & 0 deletions ffi/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

- `&[T]` of any type and `SocketAddrV4` and `SocketAddrV6` map, so a struct or enum whose
fields were refused only for the socket addresses is a value now, not an object, and
an item that newly exports can clash with another's C name, which takes a `rename`.
- `Vec<T>`, `PathBuf`, `SocketAddr`, and `url::Url` map, so a struct or enum whose
fields were refused only for them is a value now, not an object: moq-tokio's
`listen::Bind` is the C enum `moq_listen_bind`, freed with `moq_listen_bind_free(&b)`,
Expand Down
13 changes: 7 additions & 6 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ export's, and adds nothing; another crate's type is refused.
| `&str`, `String`, `&[u8]`, `Vec<u8>`, `bytes::Bytes` | `<prefix>_buf`: a view passed in, an owned buffer returned |
| `&Path`, `PathBuf` | `<prefix>_buf` of the path's bytes as the OS holds them on Unix, which need not be UTF-8, else UTF-8 |
| `Duration` | `<prefix>_duration` |
| `SocketAddr` | `<prefix>_socket_addr`: its IP's bytes, port, and whether it is IPv6 |
| `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` | `<prefix>_socket_addr`: its IP's bytes, port, and whether it is IPv6; one of the other family passed to `V4` or `V6` aborts |
| `url::Url` | an object `<prefix>_url`, made by `<prefix>_url_parse`, which fails with the parse error's message, and printed by `_to_string` |
| `Vec<T>` of any other `T` | `<prefix>_vec_<T>`: an array of `T`'s C values, viewed passed in and owned returned; `Vec<&T>` only returned |
| `Vec<T>` and `&[T]` of any other `T` | `<prefix>_vec_<T>`: an array of `T`'s C values, viewed passed in and owned returned, a slice as a clone; of references only returned |
| `Waker`, taken by value | `<prefix>_waker`, as a future's poll takes it |
| `Range<T>`, `Bound<T>` of an integer | `<prefix>_range_<T>`, `<prefix>_bound_<T>`: a `<prefix>_bound` kind and a value |
| `impl RangeBounds<T>` of an integer | `<prefix>_bounds_<T>`: its start and end bounds |
Expand Down Expand Up @@ -232,10 +232,11 @@ kotlinx-coroutines. Each value crosses JNI as a scalar, a handle as a `Long`, by
- **Bytes** are `ByteArray`, strings `String`, `Option<T>` `T?`, a tuple `Pair`,
`Triple`, or past them a generated `Tuple<n>`, `Duration` `kotlin.time.Duration`, and an `Err` a thrown `<E>Exception`
holding it, whose message is its `Display`.
- A **path** is a `String`: one Rust returns that is not UTF-8 throws. A `SocketAddr` is a
`java.net.InetSocketAddress`, which must be resolved; one Rust returns with an IPv6 flow
label, which Java does not keep, throws. A `Vec<T>` is a `List`, and passing it by
value closes each object in it once the call returns.
- A **path** is a `String`: one Rust returns that is not UTF-8 throws. A `SocketAddr`,
`SocketAddrV4`, or `SocketAddrV6` is a `java.net.InetSocketAddress`, which must be
resolved and, for `V4` or `V6`, of that family; one Rust returns with an IPv6 flow
label, which Java does not keep, throws. A `Vec<T>` or `&[T]` is a `List`, and passing
a `Vec` by value closes each object in it once the call returns.
- **Traits** are interfaces; once Rust drops an implementation, it is closed if
`AutoCloseable`.
- **Closures** lent for a call are function types, which Rust calls only during the call,
Expand Down
10 changes: 10 additions & 0 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,4 +370,14 @@ fn main() {
println!("sums {:?}", api_lib::sums(vec![vec![1, 2], Vec::new(), vec![3]]));
let site = api_lib::Site::new(base);
println!("site {} {}", site.home, site.home);

// Slices, passed in and returned as clones, and the socket address of each family.
println!("shapes {:?} greetings {:?}", api_lib::Shape::ALL, api_lib::GREETINGS);
let trail = api_lib::Trail::new(
&[api_lib::Point { x: 1, y: 2 }, api_lib::Point { x: 3, y: 4 }],
&["a".to_string(), "b".to_string()],
);
println!("trail {:?} {:?}", trail.points(), trail.labels());
let (v4, v6) = api_lib::nexts("127.0.0.1:8080".parse().unwrap(), "[::1%3]:443".parse().unwrap());
println!("nexts {} {} {} {}", v4.ip(), v4.port(), v6.port(), v6.scope_id());
}
50 changes: 50 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -981,3 +981,53 @@ impl Site {
Self { home }
}
}

impl Shape {
/// Every shape, as a constant slice.
pub const ALL: &'static [Shape] = &[Shape::Circle, Shape::Square];
}

/// Greetings, as a constant slice of references, each returned as a clone.
pub const GREETINGS: &[&str] = &["hi", "hello"];

/// A trail through points, each labeled: slices passed in and lent back out.
pub struct Trail {
points: Vec<Point>,
labels: Vec<Label>,
}

impl Trail {
/// A trail through `points`, named by `names`, which it copies.
pub fn new(points: &[Point], names: &[String]) -> Self {
let labels = (points.iter().zip(names))
.map(|(point, name)| Label {
name: name.clone(),
at: Some(*point),
ttl: None,
})
.collect();
Self {
points: points.to_vec(),
labels,
}
}

/// Its points.
pub fn points(&self) -> &[Point] {
&self.points
}

/// A label per point, each owning its name.
pub fn labels(&self) -> &[Label] {
&self.labels
}
}

/// Each address at the next port, one IPv4 and one IPv6.
pub fn nexts(
v4: std::net::SocketAddrV4,
mut v6: std::net::SocketAddrV6,
) -> (std::net::SocketAddrV4, std::net::SocketAddrV6) {
v6.set_port(v6.port() + 1);
(std::net::SocketAddrV4::new(*v4.ip(), v4.port() + 1), v6)
}
3 changes: 3 additions & 0 deletions ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ fixtures/reject/src/lib.rs:310:1: rust2-ffi: cannot export fn `read`: lent objec
fixtures/reject/src/lib.rs:315:1: rust2-ffi: cannot export fn `count_words`: Vec of references `&str`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option<std::boxed::Box<std::option::Option<u32>>>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:320:1: rust2-ffi: cannot export fn `count_some`: Vec of references `std::option::Option<&str>`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:325:1: rust2-ffi: cannot export fn `count_slice`: slice of references `&str`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:330:1: rust2-ffi: cannot export fn `peek_all`: reference to a handle inside a value `[Opaque]`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:335:1: rust2-ffi: cannot export fn `none_opaque`: borrowed return that is not Clone `[Opaque]`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box<Opaque>`; 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
Expand Down
15 changes: 15 additions & 0 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,3 +320,18 @@ pub fn count_words(words: Vec<&str>) -> usize {
pub fn count_some(words: Vec<Option<&str>>) -> usize {
words.iter().flatten().count()
}

/// A slice of references C cannot lend, as a `Vec` of them.
pub fn count_slice(words: &[&str]) -> usize {
words.len()
}

/// A slice of handles: lifting each would move it out of its caller's handle.
pub fn peek_all(values: &[Opaque]) -> usize {
values.len()
}

/// A borrowed slice whose elements have no clone to return.
pub fn none_opaque() -> &'static [Opaque] {
&[]
}
12 changes: 2 additions & 10 deletions ffi/moq/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ prefix = "moq"
# What the export refuses at the pinned revision, as `just ffi census` lists it: the API
# a hand-written wrapper still has to cover.
exclude = [
"ALPNS",
"BoundsExceeded",
"Client::connect",
"Consume",
"DecodeError",
"Driver",
"Hops::as_slice",
"Hops::iter",
"IntoBytes",
"InvalidEpoch",
Expand All @@ -40,8 +38,6 @@ exclude = [
"origin::Requesting",
"origin::Routing",
"server::Handshake",
"stats::Failure::ALL",
"stats::RefusalKind::ALL",
"stats::Snapshot::control",
"stats::Snapshot::sessions",
"stats::Snapshot::traffic",
Expand Down Expand Up @@ -89,7 +85,7 @@ exclude = [

# Exported with moq-net, whose signatures name their types, such as `Patterns` and `Instant`.
[crates.moq-pattern]
exclude = ["Pattern::captures", "Pattern::new", "Pattern::segments", "Patterns::iter"]
exclude = ["Pattern::captures", "Pattern::new", "Patterns::iter"]

[crates.moq-clock]
exclude = [
Expand Down Expand Up @@ -120,7 +116,6 @@ exclude = [
"Log::level",
"Log::new",
"RedactedUrl",
"accept::Failure::ALL",
"accept::Failure::classify",
"accept::Health::failed",
"accept::Health::new",
Expand All @@ -135,14 +130,12 @@ exclude = [
"cli::answer",
"cli::check_env",
"cli::usage_rs",
"connect::Addr",
"connect::Addr::pinned",
"connection::Monitor::poll_presence",
"crypto::install_default",
"crypto::provider",
"failover::Attempt",
"field@Log::level",
"listen::Config::preferred_v4",
"listen::Config::preferred_v6",
"notify",
"panic::isolate",
"panic::message",
Expand Down Expand Up @@ -365,7 +358,6 @@ exclude = [
"container::Producer",
"container::flv::Export",
"container::fmp4::Export",
"container::fmp4::Muxer::fragment",
"container::fmp4::Wire::new",
"container::fmp4::Wire::trak",
"container::fmp4::mp4_atom",
Expand Down
10 changes: 10 additions & 0 deletions ffi/moq/moq.c
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,17 @@ int main(void) {
moq_option_listen_bind bound = moq_listen_config_bind(listen);
CHECK(bound.some && moq_listen_bind_eq(&bound.value, &bind));
moq_listen_bind_free(&bound.value);
/* The preferred address of each family, which takes only that family. */
moq_socket_addr preferred = {.ip = {10, 0, 0, 1}, .port = 4443};
moq_listen_config_set_preferred_v4(listen, (moq_option_socket_addr){.some = true, .value = preferred});
moq_option_socket_addr preferred_v4 = moq_listen_config_preferred_v4(listen);
CHECK(preferred_v4.some && !preferred_v4.value.v6 && preferred_v4.value.ip[0] == 10 && preferred_v4.value.port == 4443);
CHECK(!moq_listen_config_preferred_v6(listen).some);
moq_listen_config_free(listen);
/* A constant slice, as an array of clones. */
moq_vec_string alpns_all = moq_alpns();
CHECK(alpns_all.len > 0);
moq_vec_string_free(alpns_all);

if (failures == 0) {
printf("ok\n");
Expand Down
6 changes: 6 additions & 0 deletions ffi/moq/moq.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,12 @@ int main() {
listen.set_bind(moq::listen_bind(moq::listen_bind_addr{addr}));
auto bind = listen.bind();
CHECK(bind && is(moq::listen_bind_to_string(*bind), "[::1]:4443"));
// The preferred address of each family, which takes only that family.
listen.set_preferred_v6(addr);
auto preferred = listen.preferred_v6();
CHECK(preferred && preferred->v6 && preferred->port == 4443 && !listen.preferred_v4());
// A constant slice, as a vector of clones.
CHECK(!moq::alpns().empty());
}

// moq-tokio's terminal connect errors, which moq-net's `Error` shares no names with.
Expand Down
4 changes: 4 additions & 0 deletions ffi/moq/moq.kt
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ fun main() {
}
url.close()
// A `Vec<String>`, as a List.
expect(ALPNS.isNotEmpty(), "a constant slice crosses as a List")
val alpns = versions.alpns()
expect(alpns.isNotEmpty() && alpns.all { it.isNotEmpty() }, "each version has an ALPN")
versions.close()
Expand All @@ -234,6 +235,9 @@ fun main() {
expect(v4.toString() == "127.0.0.1:0", "an IPv4 bind prints as Rust's")
ListenConfig.default().use { listen ->
listen.setBind(bind)
// The preferred address of each family, which takes only that family.
listen.setPreferredV4(v4._0)
expect(listen.preferredV4 == v4._0 && listen.preferredV6 == null, "a listener keeps its preferred IPv4 address")
expect(listen.bind == bind, "a listener's config keeps its bind")
}
// TLS files, as OS paths, and fingerprints, as strings: none by default.
Expand Down
12 changes: 12 additions & 0 deletions ffi/runtime/rt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ class Writer {
i32((ip as? java.net.Inet6Address)?.scopeId ?: 0)
}

/** An IPv4 address, for Rust's `SocketAddrV4`. */
fun socketAddrV4(v: java.net.InetSocketAddress) {
kotlin.require(v.address !is java.net.Inet6Address) { "an IPv6 address has no Rust SocketAddrV4" }
socketAddr(v)
}

/** An IPv6 address, for Rust's `SocketAddrV6`. */
fun socketAddrV6(v: java.net.InetSocketAddress) {
kotlin.require(v.address !is java.net.Inet4Address) { "an IPv4 address has no Rust SocketAddrV6" }
socketAddr(v)
}

fun duration(v: kotlin.time.Duration) {
kotlin.require(!v.isNegative()) { "a negative duration has no Rust Duration" }
v.toComponents { secs, nanos ->
Expand Down
16 changes: 16 additions & 0 deletions ffi/runtime/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,22 @@ impl SocketAddr {
std::net::SocketAddrV4::new(std::net::Ipv4Addr::new(a, b, c, d), self.port).into()
}

/// An IPv4 address, for `SocketAddrV4`: an IPv6 one aborts.
pub fn lift_v4(self, what: &str) -> std::net::SocketAddrV4 {
match self.lift(what) {
std::net::SocketAddr::V4(addr) => addr,
std::net::SocketAddr::V6(_) => fail(what, "an IPv6 socket address where IPv4 is taken"),
}
}

/// An IPv6 address, for `SocketAddrV6`: an IPv4 one aborts.
pub fn lift_v6(self, what: &str) -> std::net::SocketAddrV6 {
match self.lift(what) {
std::net::SocketAddr::V6(addr) => addr,
std::net::SocketAddr::V4(_) => fail(what, "an IPv4 socket address where IPv6 is taken"),
}
}

pub fn lower(addr: std::net::SocketAddr) -> Self {
match addr {
std::net::SocketAddr::V4(v4) => {
Expand Down
4 changes: 2 additions & 2 deletions ffi/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ impl<'a> Abi<'a> {
Type::F64 => "f64".to_string(),
Type::Char => "char".to_string(),
Type::Duration => "duration".to_string(),
Type::SocketAddr => "socket_addr".to_string(),
Type::SocketAddr(_) => "socket_addr".to_string(),
Type::Option(inner) => format!("option_{}", self.key(inner)),
Type::List(inner) => format!("vec_{}", self.key(inner)),
Type::Record(i) => strip(self.record(*i)),
Expand Down Expand Up @@ -377,7 +377,7 @@ impl<'a> Abi<'a> {
Type::Char => Ty::Char,
Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => Ty::Buf,
Type::Duration => Ty::Duration,
Type::SocketAddr => Ty::SocketAddr,
Type::SocketAddr(_) => Ty::SocketAddr,
Type::Waker => Ty::Waker,
Type::List(inner) => Ty::Struct(self.list(inner)),
Type::Option(inner) => match Self::nullable(inner) {
Expand Down
39 changes: 33 additions & 6 deletions ffi/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;

use crate::ir::{
Access, Api, Callback, Constant, Dyn, Enum, Field, Function, Int, Literal, Mutability, Object, Param, Path,
Access, Api, Callback, Constant, Dyn, Enum, Family, Field, Function, Int, Literal, Mutability, Object, Param, Path,
Receiver, Record, Traits, Type, Variant,
};

Expand Down Expand Up @@ -2478,7 +2478,20 @@ impl<'tcx> Collector<'tcx> {
Type::Path
}
ty::Slice(elem) if *elem == tcx.types.u8 => Type::Slice,
ty::Slice(elem) => return Err(why("slice", elem.to_string())),
// An array, as a `Vec`'s, which C passes and Rust returns as a clone.
ty::Slice(elem) => {
let item = self.ty(
*elem,
match pos {
Pos::Return | Pos::Returned => Pos::Returned,
_ => Pos::Behind,
},
)?;
if borrows(&item) && !matches!(pos, Pos::Return | Pos::Returned) {
return Err(why("slice of references", elem.to_string()));
}
Type::List(Box::new(item))
}
ty::Dynamic(..) => return Err(why("trait object", inner.to_string())),
_ => self.ty(
*inner,
Expand All @@ -2495,7 +2508,13 @@ impl<'tcx> Collector<'tcx> {
match (&inner_ty, pos, mutability) {
// Returned as a clone: a handle in it is a new handle to its clone.
(Type::Str | Type::Slice | Type::Path, Pos::Return | Pos::Returned, _) => {}
(_, Pos::Return | Pos::Returned, _) if !self.is_clone(*inner) => {
// A slice's clone is a `Vec` of its elements' clones.
(_, Pos::Return | Pos::Returned, _)
if !self.is_clone(match inner.kind() {
ty::Slice(elem) => *elem,
_ => *inner,
}) =>
{
return Err(why("borrowed return that is not Clone", inner.to_string()));
}
(_, Pos::Field, _) => return Err(why("reference field", inner.to_string())),
Expand Down Expand Up @@ -2533,8 +2552,16 @@ impl<'tcx> Collector<'tcx> {
Type::Duration
} else if tcx.is_diagnostic_item(rustc_span::Symbol::intern("PathBuf"), did) {
Type::PathBuf
} else if tcx.crate_name(did.krate) == sym::core && tcx.item_name(did).as_str() == "SocketAddr" {
Type::SocketAddr
} else if let Some(family) = (tcx.crate_name(did.krate) == sym::core)
.then(|| match tcx.item_name(did).as_str() {
"SocketAddr" => Some(Family::Any),
"SocketAddrV4" => Some(Family::V4),
"SocketAddrV6" => Some(Family::V6),
_ => None,
})
.flatten()
{
Type::SocketAddr(family)
} else if let Some((url, i)) = self.url
&& did == url
{
Expand Down Expand Up @@ -2680,7 +2707,7 @@ enum Pos {
/// copied by it if kept.
fn foreign_arg(ty: &Type) -> bool {
match ty {
Type::Bool | Type::Int(_) | Type::F32 | Type::F64 | Type::Char | Type::Duration | Type::SocketAddr => true,
Type::Bool | Type::Int(_) | Type::F32 | Type::F64 | Type::Char | Type::Duration | Type::SocketAddr(_) => true,
Type::String | Type::Vec | Type::Bytes | Type::PathBuf => true,
Type::Ref(Mutability::Not, inner) => matches!(**inner, Type::Str | Type::Slice | Type::Path),
Type::Option(inner) => foreign_arg(inner),
Expand Down
Loading