diff --git a/ffi/README.md b/ffi/README.md index eedc1e8f2..a83347de7 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -68,6 +68,7 @@ export's, and adds nothing; another crate's type is refused. | `fn` and inherent `pub` methods | functions named through their type | | `Result` | `bool f(..., T *out, E *err)` | | a returned tuple `(A, B)` | one out pointer each: `void f(..., A *out0, B *out1)` | +| a tuple inside another type, or as a field or parameter | `_tuple__`: a struct of fields `_0`, `_1`, and so on; of references only returned | | `async fn`, or a return that implements `Future` | a future: `f` makes it, `f_poll` polls it, `f_future_free` drops it; a function that is not `async` runs at the call, as in Rust | | `poll_x`, when `x` exports as a future | left out: the future is its poll | | `bool`, integers but 128-bit, floats, `char` | `bool`, `` types, `float`, `double`, a `uint32_t` code point | @@ -241,7 +242,7 @@ in as a `ByteArray`, bytes returned as their owner, and anything else encoded in as a read-only direct `ByteBuffer` until `close()` frees it, or, never closed, until the GC collects that buffer; `Bytes(ByteArray)` holds Kotlin's for a record passed in. Strings are `String`, `Option` `T?`, a tuple `Pair`, - `Triple`, or past them a generated `Tuple`, `Duration` `kotlin.time.Duration`, and an `Err` a thrown `Exception` + `Triple`, or else a generated `Tuple`, though a tuple of one returned whole is its element, `Duration` `kotlin.time.Duration`, and an `Err` a thrown `Exception` holding it, whose message is its `Display`. - 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 diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index a5b592694..cea6cc249 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -99,6 +99,52 @@ fn main() { Err(e) => println!("divide err {e}"), } } + for n in [98305, 0] { + match api_lib::spread(n) { + Some((a, b, c, d)) => println!("spread {a} {b} {c} {d}"), + None => println!("spread none"), + } + } + for needle in [&b"lo"[..], b"x"] { + match api_lib::find(b"hello", needle) { + Some((at, len)) => println!("find {at} {len}"), + None => println!("find none"), + } + } + let rows = api_lib::rows(&[Point { x: 1, y: 2 }, Point { x: 3, y: 3 }]); + let rows: Vec = (rows.iter()) + .map(|(name, shape, p)| format!("{name} {shape:?} {} {}", p.x, p.y)) + .collect(); + println!("rows {}", rows.join(", ")); + let board = api_lib::Board::new(vec![ + ("low".to_string(), Counter::new("l", 1)), + ("high".to_string(), Counter::new("h", 9)), + ]); + let ranked: Vec = (board.ranked()) + .map(|(name, counter)| format!("{name} {} {}", counter.name(), counter.get())) + .collect(); + println!("ranked {}", ranked.join(", ")); + let span = api_lib::Span { + bounds: (2, 10), + named: Some(("s".to_string(), Shape::Square)), + }; + let ((a, b), (c, d)) = api_lib::halves(&span); + println!("halves {a} {b} {c} {d} {span:?}"); + let (n, text) = api_lib::swapped(("t".to_string(), 4)); + println!("swapped {n} {text}"); + for value in [None, Some((None,)), Some((Some(3),))] { + println!("doubled {:?}", api_lib::doubled(value)); + } + let lent = (vec![1, 2],); + let (lent,) = api_lib::lent_back(&lent); + let (boxed,) = *api_lib::boxed_tuple(vec![3]); + println!("lent back {lent:?} boxed {boxed:?}"); + println!( + "title {:?} {:?} named {:?}", + api_lib::title(true), + api_lib::title(false), + api_lib::named("x") + ); // Each lent counter is a new handle to a clone. let mut registry = Registry::new(Counter::new("first", 1)); @@ -144,6 +190,14 @@ fn main() { api_lib::count((Bound::Excluded(2), Bound::Included(4))) ); println!("end {:?} {:?}", api_lib::end(3), api_lib::end(0)); + let (start, end) = api_lib::ends(3); + println!("ends {start:?} {end:?}"); + for n in [2, 5] { + match api_lib::below(n, 3) { + Ok(n) => println!("below {n}"), + Err((start, end)) => println!("below err {start:?} {end:?}"), + } + } let window = Window { range: 2..8, end: api_lib::end(5), diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index b42f8592f..e5fccbb98 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -179,6 +179,101 @@ pub fn divide(a: u64, b: u64) -> Result<(u64, u64), Error> { } } +/// `n` narrowed as [`widths`] does, unless 0: a tuple inside an `Option` is a struct. +pub fn spread(n: u64) -> Option<(u8, i16, u32, u64)> { + (n != 0).then(|| widths(n)) +} + +/// Where `needle` first starts in `haystack`, and its length, as moq-mux's +/// `find_start_code` returns it. +pub fn find(haystack: &[u8], needle: &[u8]) -> Option<(usize, usize)> { + (haystack.windows(needle.len())) + .position(|window| window == needle) + .map(|at| (at, needle.len())) +} + +/// Each point named by its index, with its shape: rows of tuples, as moq-net's stats +/// snapshots return them. +pub fn rows(points: &[Point]) -> Vec<(String, Shape, Point)> { + (points.iter().enumerate()) + .map(|(i, p)| { + let shape = match p.x == p.y { + true => Shape::Square, + false => Shape::Circle, + }; + (format!("p{i}"), shape, *p) + }) + .collect() +} + +/// Counters by name, which takes each counter's handle in a tuple. +pub struct Board { + counters: std::collections::BTreeMap, +} + +impl Board { + pub fn new(counters: Vec<(String, Counter)>) -> Self { + Self { + counters: counters.into_iter().collect(), + } + } + + /// Each name and its counter, highest first, as hang's `ranked`: each pair borrowed, + /// so each crosses as a clone. + pub fn ranked(&self) -> impl Iterator { + let mut ranked: Vec<_> = self.counters.iter().collect(); + ranked.sort_by_key(|(_, counter)| std::cmp::Reverse(counter.get())); + ranked.into_iter() + } +} + +/// A span: a record whose fields are tuples, one holding text. +#[derive(Clone, Debug, PartialEq)] +pub struct Span { + pub bounds: (u32, u32), + pub named: Option<(String, Shape)>, +} + +/// The span's two halves, each a tuple inside the tuple returned. +pub fn halves(span: &Span) -> ((u32, u32), (u32, u32)) { + let (start, end) = span.bounds; + let mid = start + (end - start) / 2; + ((start, mid), (mid, end)) +} + +/// `value` doubled: a tuple of one inside an `Option` keeps `None` apart from +/// `Some((None,))`. +pub fn doubled(value: Option<(Option,)>) -> Option<(Option,)> { + value.map(|(n,)| (n.map(|n| n * 2),)) +} + +/// A title, for formal speech: a tuple of one borrowed string, whose C struct one of an +/// owned string shares. +pub fn title(formal: bool) -> Option<(&'static str,)> { + formal.then_some(("Dr",)) +} + +/// `name`, unless empty: a tuple of one owned string. +pub fn named(name: &str) -> Option<(String,)> { + (!name.is_empty()).then(|| (name.to_string(),)) +} + +/// `value` lent back: a borrowed tuple of one, returned as a clone, is a tuple, not its +/// element, as only a tuple returned whole is. +pub fn lent_back(value: &(Vec,)) -> &(Vec,) { + value +} + +/// `bytes` in a boxed tuple of one, which is a tuple too. +pub fn boxed_tuple(bytes: Vec) -> Box<(Vec,)> { + Box::new((bytes,)) +} + +/// `pair` with its sides swapped: a tuple taken by value. +pub fn swapped(pair: (String, u32)) -> (u32, String) { + (pair.1, pair.0) +} + /// Holds counters and lends them: each borrowed return is a new handle to a clone. #[derive(Default)] pub struct Registry { @@ -275,6 +370,21 @@ pub fn end(limit: u64) -> Bound { } } +/// A range's two bounds, up to the end `limit` puts on it: returned whole, a tuple, not +/// the pair a `RangeBounds` parameter takes. +pub fn ends(limit: u64) -> (Bound, Bound) { + (Bound::Included(0), end(limit)) +} + +/// `n` if below `limit`, or else the bounds it falls outside: an error is the pair a +/// `RangeBounds` parameter takes, not a tuple. +pub fn below(n: u64, limit: u64) -> Result, Bound)> { + match n < limit { + true => Ok(n), + false => Err(ends(limit)), + } +} + /// A record of a range and a bound, which C holds after the structs they are. #[derive(Clone, Debug, PartialEq)] pub struct Window { diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index bfae6c52a..6a79b9967 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -8,6 +8,8 @@ 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:139:1: rust2-ffi: tuple `((u8, u16), u32)` and tuple `((u8, u16, u32),)` are both `reject_tuple_tuple_u8_u16_u32` in C + fixtures/reject/src/lib.rs:139:1: note: tuple `((u8, u16, u32),)` is here fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out fixtures/reject/src/lib.rs: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: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 @@ -82,5 +84,5 @@ fixtures/reject/src/lib.rs:86:2: rust2-ffi: cannot export method `Text::view`: r fixtures/reject/src/lib.rs:92:1: rust2-ffi: cannot export fn `retext`: 'static borrow `&'a str`; exclude it in the config to leave it out 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: cannot export fn `pair`: tuple of references `(&str, u8)`; exclude it in the config to leave it out no span: rust2-ffi: rename `field@Limit::min` in the config names nothing exported diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 5f7f0ba08..6eecc5cb7 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -5,9 +5,9 @@ use std::collections::HashMap; /// A generic type. pub struct Wrap(pub T); -/// A tuple inside an `Option`: only a returned tuple crosses, as out pointers. -pub fn pair() -> Option<(u8, u8)> { - Some((1, 2)) +/// A tuple of references taken: C lends nothing inside a value. +pub fn pair(pair: (&str, u8)) -> u8 { + pair.1 } /// Another crate's type, which has no mapping. @@ -574,3 +574,9 @@ impl std::str::pattern::Pattern for Slash { pub fn halves() -> impl Iterator { "a/b".split(Slash) } + +/// Two tuples whose C names run their elements together alike: both are +/// `reject_tuple_tuple_u8_u16_u32`. +pub fn mixed(a: Option<((u8, u16), u32)>, b: Option<((u8, u16, u32),)>) -> bool { + a.is_some() && b.is_some() +} diff --git a/ffi/moq/ffi.toml b/ffi/moq/ffi.toml index e76d9e2c2..61c3b5b36 100644 --- a/ffi/moq/ffi.toml +++ b/ffi/moq/ffi.toml @@ -34,9 +34,6 @@ exclude = [ "group::Producer::write_frames", "origin::Requesting", "server::Handshake", - "stats::Snapshot::control", - "stats::Snapshot::sessions", - "stats::Snapshot::traffic", "time::Driver", "track::Fetching", "track::Resolving", @@ -250,7 +247,6 @@ exclude = [ "Catalog::from_reader", "Catalog::subscribe", "catalog::Audio::enabled", - "catalog::Audio::ranked", "catalog::Audio::renditions", "catalog::Binary::tracks", "catalog::BinaryConfig::extra", @@ -262,7 +258,6 @@ exclude = [ "catalog::UnknownContainer", "catalog::UnknownProjection", "catalog::Video::enabled", - "catalog::Video::ranked", "catalog::Video::renditions", "container::Frame::encode", "echo::Snapshot", @@ -323,7 +318,6 @@ exclude = [ "codec::aac::Config::parse", "codec::annexb::NalIterator", "codec::annexb::build_prefix", - "codec::annexb::find_start_code", "codec::annexb::from_length_prefixed", "codec::annexb::length_prefixed_to_annexb", "codec::av1::Error", diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 28af70bf8..233275063 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -80,6 +80,7 @@ fn owned(ty: &Type) -> Type { Type::Option(inner) => Type::Option(Box::new(owned(inner))), Type::Box(inner) => Type::Box(Box::new(owned(inner))), Type::List(inner) => Type::List(Box::new(owned(inner))), + Type::Tuple(elements) => Type::Tuple(elements.iter().map(owned).collect()), ty => ty.clone(), } } @@ -104,6 +105,8 @@ pub struct Abi<'a> { pub ranges: BTreeMap, /// Each `Vec` struct by C name, with `T`. pub lists: BTreeMap, + /// Each tuple struct by C name, with its elements. + pub tuples: BTreeMap>, /// Every C name claimed, with what claimed it. names: HashMap, /// Each name claimed twice. @@ -121,6 +124,7 @@ impl<'a> Abi<'a> { options: BTreeMap::new(), ranges: BTreeMap::new(), lists: BTreeMap::new(), + tuples: BTreeMap::new(), names: HashMap::new(), clashes: Vec::new(), }; @@ -325,6 +329,11 @@ impl<'a> Abi<'a> { format!("{}_vec_{}", self.prefix, self.key(elem)) } + /// The C name of a tuple's struct: `_tuple_string_u64`. + pub fn tuple(&self, elements: &[Type]) -> String { + format!("{}_{}", self.prefix, self.key(&Type::Tuple(elements.to_vec()))) + } + /// The C name of a range, bound, or pair of bounds struct: `_range_u64`. pub fn range(&self, ty: &Type) -> String { format!("{}_{}", self.prefix, self.key(ty)) @@ -347,6 +356,10 @@ impl<'a> Abi<'a> { Type::SocketAddr(_) => "socket_addr".to_string(), Type::Option(inner) => format!("option_{}", self.key(inner)), Type::List(inner) => format!("vec_{}", self.key(inner)), + Type::Tuple(elements) => { + let keys: Vec = elements.iter().map(|e| self.key(e)).collect(); + format!("tuple_{}", keys.join("_")) + } Type::Record(i) => strip(self.record(*i)), Type::Enum(i) => strip(self.enumeration(*i)), Type::Object(i) => strip(self.object(*i)), @@ -358,6 +371,21 @@ impl<'a> Abi<'a> { } } + /// A type by its key, with each tuple spelled as Rust spells it, which tells apart + /// tuples that share a C name. + fn spell(&self, ty: &Type) -> String { + match ty { + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.spell(e)).collect(); + match elements.len() { + 1 => format!("({},)", elements[0]), + _ => format!("({})", elements.join(", ")), + } + } + ty => self.key(ty), + } + } + /// Whether `ty` crosses as a `_buf`. pub fn is_buf(ty: &Type) -> bool { matches!( @@ -410,7 +438,7 @@ impl<'a> Abi<'a> { Type::Callback(i, _) => Ty::Struct(self.callback(*i)), Type::Closure(params, ret) => Ty::Fn(params.iter().map(|p| self.ty(p)).collect(), Box::new(self.ty(ret))), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => Ty::Struct(self.range(ty)), - Type::Tuple(_) => unreachable!("a tuple is only returned, through out parameters"), + Type::Tuple(elements) => Ty::Struct(self.tuple(elements)), } } @@ -640,7 +668,11 @@ impl<'a> Abi<'a> { self.claim(free.name.clone(), what.clone(), function.span); } types.extend(function.params.iter().map(|p| &p.ty)); - types.push(&function.ok); + // A tuple returned whole is written element by element, with no struct of its own. + match &function.ok { + Type::Tuple(elements) => types.extend(elements), + ok => types.push(ok), + } types.extend(&function.err); } for constant in &api.constants { @@ -653,6 +685,8 @@ impl<'a> Abi<'a> { let mut options = BTreeMap::new(); let mut ranges = BTreeMap::new(); let mut lists = BTreeMap::new(); + let mut tuples: BTreeMap> = BTreeMap::new(); + let mut mixed = Vec::new(); let mut stack = types; while let Some(ty) = stack.pop() { match ty { @@ -668,7 +702,21 @@ impl<'a> Abi<'a> { stack.push(inner); } Type::Ref(_, inner) | Type::Box(inner) => stack.push(inner), - Type::Tuple(elements) => stack.extend(elements), + Type::Tuple(elements) => { + // A returned tuple of borrows holds clones, as a `Vec` does. + let owned: Vec = elements.iter().map(owned).collect(); + let name = self.tuple(elements); + let layout = |elements: &[Type]| elements.iter().map(|e| self.ty(e)).collect::>(); + match tuples.get(&name) { + // Its name runs its elements' together, which two nestings can share. + Some(other) if layout(other) != layout(&owned) => mixed.push((name, owned)), + Some(_) => {} + None => { + tuples.insert(name, owned); + } + } + stack.extend(elements); + } Type::Closure(params, ret) => { stack.extend(params); stack.push(ret); @@ -689,6 +737,14 @@ impl<'a> Abi<'a> { for name in ranges.keys() { self.claim(name.clone(), "a range".to_string(), crate_span); } + for (name, elements) in &tuples { + let what = format!("tuple `{}`", self.spell(&Type::Tuple(elements.clone()))); + self.claim(name.clone(), what, crate_span); + } + for (name, elements) in mixed { + let what = format!("tuple `{}`", self.spell(&Type::Tuple(elements))); + self.claim(name, what, crate_span); + } for name in lists.keys() { self.claim(name.clone(), "a Vec".to_string(), crate_span); self.claim(format!("{name}_free"), "a Vec".to_string(), crate_span); @@ -706,6 +762,7 @@ impl<'a> Abi<'a> { self.options = options; self.ranges = ranges; self.lists = lists; + self.tuples = tuples; } /// Claim the functions a type's std traits export. diff --git a/ffi/src/c.rs b/ffi/src/c.rs index bf333850e..0f16e0fd5 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -129,6 +129,9 @@ impl Header<'_> { for name in abi.options.keys() { self.value(&Ty::Struct(name.clone())); } + for name in abi.tuples.keys() { + self.value(&Ty::Struct(name.clone())); + } for i in 0..api.records.len() { self.value(&Ty::Struct(abi.record(i))); } @@ -283,6 +286,16 @@ impl Header<'_> { )); return; } + if let Some(elements) = abi.tuples.get(name) { + let elements: Vec = elements.iter().map(|e| abi.ty(e)).collect(); + let mut decls = Vec::new(); + for (n, element) in elements.iter().enumerate() { + self.value(element); + decls.push(format!("\t{};", self.decl(element, &format!("_{n}")))); + } + self.line(format!("typedef struct {name} {{\n{}\n}} {name};\n", decls.join("\n"))); + return; + } if let Some(i) = (0..abi.api.records.len()).find(|&i| &abi.record(i) == name) { let record = &abi.api.records[i]; let fields: Vec = record.fields.iter().map(|f| abi.ty(&f.ty)).collect(); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 1c1bc18a2..4438c48ab 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2721,20 +2721,24 @@ impl<'tcx> Collector<'tcx> { (held, lent) } - /// What a function returns: a tuple's elements each, or else one value. + /// What a function returns: a tuple returned whole, even a pair of bounds, is written + /// through an out pointer per element. fn ret(&self, ty: Ty<'tcx>) -> Result { - let ty::Tuple(list) = ty.kind() else { - return self.ty(ty, Pos::Return); - }; - if list.is_empty() { - return Ok(Type::Unit); + match ty.kind() { + ty::Tuple(list) if !list.is_empty() => self.tuple(ty, Pos::Return), + _ => self.ty(ty, Pos::Return), } - let mut elements = Vec::new(); - for element in list.iter() { - match self.ty(element, Pos::Return)? { - Type::Unit => return Err(why("unit in a tuple", ty.to_string())), - element => elements.push(element), - } + } + + /// The tuple `ty`, each element mapped as inside a value at `pos`. + fn tuple(&self, ty: Ty<'tcx>, pos: Pos) -> Result { + let elements = (ty.tuple_fields().iter()) + .map(|element| self.ty(element, pos.inner())) + .collect::, _>>()?; + // C lends nothing inside a value, and an element lowered back into one is a clone + // of what Rust lent. + if elements.iter().any(borrows) && !matches!(pos, Pos::Return | Pos::Returned) { + return Err(why("tuple of references", ty.to_string())); } Ok(Type::Tuple(elements)) } @@ -3063,7 +3067,7 @@ impl<'tcx> Collector<'tcx> { { Type::Bounds(int) } - _ => return Err(why("tuple", "")), + _ => self.tuple(ty, pos)?, }, ty::Array(..) => return Err(why("array", ty.to_string())), ty::Slice(_) | ty::Str => return Err(why("unsized type", ty.to_string())), @@ -3130,6 +3134,7 @@ fn buildable(api: &Api, ty: &Type, held: &[bool]) -> bool { Type::Object(i) => held[*i], Type::Ref(_, inner) | Type::Box(inner) => buildable(api, inner, held), Type::Record(i) => api.records[*i].fields.iter().all(|f| buildable(api, &f.ty, held)), + Type::Tuple(elements) => elements.iter().all(|ty| buildable(api, ty, held)), Type::Enum(i) => api.enums[*i] .variants .iter() @@ -3193,6 +3198,7 @@ fn borrows(ty: &Type) -> bool { match ty { Type::Ref(..) => true, Type::Option(inner) | Type::Box(inner) | Type::List(inner) => borrows(inner), + Type::Tuple(elements) => elements.iter().any(borrows), _ => false, } } diff --git a/ffi/src/cpp.rs b/ffi/src/cpp.rs index ec6ed343f..945395707 100644 --- a/ffi/src/cpp.rs +++ b/ffi/src/cpp.rs @@ -144,8 +144,8 @@ impl<'a> Header<'a> { } Type::Object(i) if abi.api.objects[*i].copy => format!("const {} *", self.owned(inner)), // Moved out of, as a handle taken by value is. - _ if matches!(inner.base(), Type::Object(_)) => format!("::std::optional<{}>", self.owned(inner)), - _ => format!("const ::std::optional<{}> &", self.owned(inner)), + _ if moves(abi, inner) => format!("::std::optional<{}>", self.held(inner)), + _ => format!("const ::std::optional<{}> &", self.held(inner)), }, Type::Waker => format!("const ::{}::waker &", self.ns), Type::Ref(m, inner) if matches!(**inner, Type::Object(_)) => match m { @@ -158,6 +158,9 @@ impl<'a> Header<'a> { format!("const {} &", self.owned(ty)) } Type::Enum(i) if !abi.api.enums[*i].plain() => format!("const {} &", self.owned(ty)), + // Moved out of, each handle as a handle taken by value is. + Type::Tuple(_) if moves(abi, ty) => self.held(ty), + Type::Tuple(_) => format!("const {} &", self.held(ty)), ty => self.owned(ty), } } @@ -167,9 +170,18 @@ impl<'a> Header<'a> { let Type::List(inner) = ty else { unreachable!("{ty:?} is no Vec") }; - match Abi::is_buf(inner) { - true => format!("::std::vector<::{}::view>", self.ns), - false => format!("::std::vector<{}>", self.owned(inner)), + format!("::std::vector<{}>", self.held(inner)) + } + + /// The C++ type a parameter's `Vec`, `Option`, or tuple holds a `ty` as: bytes as a view. + fn held(&self, ty: &Type) -> String { + match ty { + ty if Abi::is_buf(ty) => format!("::{}::view", self.ns), + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.held(e)).collect(); + format!("::std::tuple<{}>", elements.join(", ")) + } + ty => self.owned(ty), } } @@ -180,6 +192,7 @@ impl<'a> Header<'a> { match ty { Type::List(_) => true, Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) => self.arena(inner), + Type::Tuple(elements) => elements.iter().any(|e| self.arena(e)), Type::Record(i) => api.records[*i].fields.iter().any(|f| self.arena(&f.ty)), Type::Enum(i) => (api.enums[*i].variants.iter()).any(|v| v.fields.iter().any(|f| self.arena(&f.ty))), _ => false, @@ -253,7 +266,12 @@ impl<'a> Header<'a> { Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => { unreachable!("a buffer is above") } - Type::Tuple(_) => unreachable!("a tuple is only returned"), + Type::Tuple(elements) => { + let fields: Vec = (0..elements.len()) + .map(|n| self.lower(&elements[n], &format!("::std::get<{n}>({e})"))) + .collect(); + format!("::{}{{{}}}", abi.tuple(elements), fields.join(", ")) + } } } @@ -299,6 +317,12 @@ impl<'a> Header<'a> { false => format!("{d}::lift({e})"), }, Type::Object(_) => format!("{d}::access::wrap<{}>({e})", self.owned(ty)), + Type::Tuple(elements) => { + let lifted: Vec = (elements.iter().enumerate()) + .map(|(n, ty)| self.lift(ty, &format!("{e}._{n}"))) + .collect(); + format!("{}({})", self.owned(ty), lifted.join(", ")) + } other => unreachable!("{other:?} is never returned"), } } @@ -1238,11 +1262,13 @@ fn record(abi: &Abi<'_>, c: &str) -> Type { Type::Record(i.expect("a member method's value is a record")) } -/// Whether passing a `Vec` of `elem` moves each handle out, as a handle taken by value is. -fn moves(abi: &Abi<'_>, elem: &Type) -> bool { - match elem { +/// Whether passing `ty` moves a handle out of a `Vec`, `Option`, or tuple, as a handle +/// taken by value is. +fn moves(abi: &Abi<'_>, ty: &Type) -> bool { + match ty { Type::Object(i) => !abi.api.objects[*i].copy, Type::Option(inner) | Type::Box(inner) | Type::List(inner) => moves(abi, inner), + Type::Tuple(elements) => elements.iter().any(|e| moves(abi, e)), _ => false, } } @@ -1276,6 +1302,7 @@ fn init(ty: &Type) -> &'static str { match ty { Type::Object(_) | Type::Enum(_) | Type::Record(_) => "", Type::Box(inner) => init(inner), + Type::Tuple(elements) if elements.iter().any(|e| init(e).is_empty()) => "", _ => "{}", } } diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index c2a1a6ea2..66f8ec0c2 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -273,7 +273,13 @@ impl Gen<'_> { Type::Closure(params, ret) => self.closure(params, ret, e), Type::Range(_) => format!("{e}.lift()"), Type::Bound(_) | Type::Bounds(_) => format!("{e}.lift(w)"), - Type::Tuple(_) => unreachable!("a tuple is never taken"), + Type::Tuple(elements) => { + // The trailing comma makes `(x,)` a tuple, not parentheses. + let lifted: Vec = (elements.iter().enumerate()) + .map(|(n, ty)| format!("{},", self.lift(ty, &format!("{e}._{n}")))) + .collect(); + format!("({})", lifted.concat()) + } } } @@ -369,7 +375,18 @@ impl Gen<'_> { Type::Range(_) => format!("rt::Range::lower({e})"), Type::Bound(_) => format!("rt::Bound::lower({e})"), Type::Bounds(_) => format!("rt::Bounds::lower({e})"), - Type::Tuple(_) => unreachable!("a tuple is lowered element by element"), + Type::Tuple(elements) => { + let names: Vec = (0..elements.len()).map(|n| format!("t{n},")).collect(); + let fields: Vec = (elements.iter().enumerate()) + .map(|(n, ty)| format!("_{n}: {}", self.lower(ty, &format!("t{n}")))) + .collect(); + format!( + "match {e} {{ ({}) => {} {{ {} }} }}", + names.concat(), + self.abi.tuple(elements), + fields.join(", ") + ) + } } } @@ -393,6 +410,12 @@ impl Gen<'_> { .map(|free| format!("if {e}.some {{ {free} }}")), }, Type::Box(inner) => self.free(inner, e), + Type::Tuple(elements) => { + let frees: Vec = (elements.iter().enumerate()) + .filter_map(|(n, ty)| self.free(ty, &format!("{e}._{n}"))) + .collect(); + (!frees.is_empty()).then(|| frees.join(" ")) + } Type::Object(i) => Some(format!( "unsafe {{ rt::Object::<{}>::free({e}) }};", self.object_path(*i) @@ -409,6 +432,7 @@ impl Gen<'_> { _ if Abi::is_buf(ty) => true, Type::Object(_) | Type::List(_) => true, Type::Option(inner) | Type::Box(inner) => self.owns(inner), + Type::Tuple(elements) => elements.iter().any(|ty| self.owns(ty)), Type::Record(i) => self.abi.api.records[*i].fields.iter().any(|f| self.owns(&f.ty)), Type::Enum(i) => self.abi.api.enums[*i] .variants @@ -467,6 +491,14 @@ impl Gen<'_> { "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}_free(this: {name}) {{\n\t{free}\n}}\n" )); } + for (name, elements) in &self.abi.tuples.clone() { + let fields: String = (elements.iter().enumerate()) + .map(|(n, ty)| format!("\tpub _{n}: {},\n", self.rs(&self.abi.ty(ty)))) + .collect(); + self.line(format!( + "#[repr(C)]\n#[derive(Clone, Copy)]\npub struct {name} {{\n{fields}}}\n" + )); + } for (name, inner) in &self.abi.options.clone() { let value = self.rs(&self.abi.ty(inner)); self.line(format!( diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 76bceb48e..6a93fa33d 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -279,7 +279,7 @@ pub enum Type { Bound(Int), /// `(Bound, Bound)` of an integer, the form a `RangeBounds` parameter takes. Bounds(Int), - /// A tuple, only as what a function returns. + /// A tuple of one element or more. Tuple(Vec), } diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 17c30c725..c25c97b80 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -235,7 +235,7 @@ struct Gen<'a> { errors: Vec, /// A counter for fresh Kotlin names. fresh: usize, - /// The arities past `Triple` a tuple class is written for. + /// The arities a tuple class is written for: one, and past `Triple`. tuples: BTreeSet, } @@ -270,23 +270,14 @@ impl<'a> Gen<'a> { } } - /// The class of a tuple of `n` past `Triple`, written once, its fields named as - /// `Triple`'s go on. + /// The class of a tuple of `n`, of one or past `Triple`, written once, its fields named + /// as `Triple`'s. fn tuple(&mut self, n: usize) -> String { let name = format!("Tuple{n}"); if self.tuples.insert(n) { self.claim(&name, format!("a tuple of {n}")); - let ordinals = [ - "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", - "eleventh", "twelfth", - ]; - let field = |k: usize| { - ordinals - .get(k) - .map_or_else(|| format!("item{}", k + 1), |o| o.to_string()) - }; let params: Vec = (1..=n).map(|k| format!("T{k}")).collect(); - let fields: Vec = (0..n).map(|k| format!("\tval {}: T{},\n", field(k), k + 1)).collect(); + let fields: Vec = (0..n).map(|k| format!("\tval {}: T{},\n", ordinal(k), k + 1)).collect(); let _ = write!( self.types, "/** A tuple of {n}, as `Pair` and `Triple` are of two and three. */\ndata class {name}<{}>(\n{})\n\n", @@ -297,6 +288,15 @@ impl<'a> Gen<'a> { name } + /// The Kotlin type of a tuple of `elements`. + fn tuple_of(&mut self, elements: Vec) -> String { + match elements.len() { + 2 => format!("kotlin.Pair<{}>", elements.join(", ")), + 3 => format!("kotlin.Triple<{}>", elements.join(", ")), + n => format!("{}<{}>", self.tuple(n), elements.join(", ")), + } + } + /// The Kotlin type of `ty` as a value, owning what it holds. fn kt(&mut self, ty: &Type) -> String { let abi = self.abi; @@ -327,12 +327,7 @@ impl<'a> Gen<'a> { Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => self.class(&abi.range(ty)), Type::Tuple(elements) => { let elements: Vec = elements.iter().map(|e| self.kt(e)).collect(); - match elements.len() { - 1 => elements[0].clone(), - 2 => format!("kotlin.Pair<{}>", elements.join(", ")), - 3 => format!("kotlin.Triple<{}>", elements.join(", ")), - n => format!("{}<{}>", self.tuple(n), elements.join(", ")), - } + self.tuple_of(elements) } } } @@ -345,6 +340,10 @@ impl<'a> Gen<'a> { Type::List(inner) => format!("kotlin.collections.List<{}>", self.kt_param(inner)), Type::Option(inner) => format!("{}?", self.kt_param(inner)), Type::Box(inner) | Type::Ref(_, inner) => self.kt_param(inner), + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.kt_param(e)).collect(); + self.tuple_of(elements) + } _ => self.kt(ty), } } @@ -395,6 +394,13 @@ impl<'a> Gen<'a> { }, Type::Object(_) => format!("{w}.handle({e}.handle)"), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("w_{}({w}, {e})", abi.range(ty)), + Type::Tuple(elements) => { + let t = self.fresh("t"); + let writes: Vec = (elements.iter().enumerate()) + .map(|(k, ty)| self.write_value(ty, w, &format!("{t}.{}", ordinal(k)))) + .collect(); + format!("{e}.let {{ {t} -> {} }}", writes.join("; ")) + } other => unreachable!("{other:?} is never encoded"), } } @@ -455,9 +461,8 @@ impl<'a> Gen<'a> { Type::Object(i) => format!("{}({r}.i64())", self.class(&abi.object(*i))), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("r_{}({r})", abi.range(ty)), Type::Tuple(elements) => { - let read: Vec = elements.iter().map(|e| self.read_value(e, r)).collect(); + let read: Vec = elements.iter().map(|e| self.read(e, r, owned)).collect(); match read.len() { - 1 => read[0].clone(), 2 => format!("kotlin.Pair({})", read.join(", ")), 3 => format!("kotlin.Triple({})", read.join(", ")), n => format!("{}({})", self.tuple(n), read.join(", ")), @@ -628,6 +633,9 @@ impl<'a> Gen<'a> { for c in abi.options.clone().keys() { self.glue_option(c); } + for (c, elements) in &abi.tuples.clone() { + self.glue_tuple(c, elements); + } for constant in &api.constants { let name = self.bare(&abi.name(&constant.path)).to_uppercase(); let (ty, value) = match constant.value { @@ -735,6 +743,19 @@ impl<'a> Gen<'a> { ); } + /// The glue's codec for a tuple struct, field by field. + fn glue_tuple(&mut self, c: &str, elements: &[Type]) { + let fields: Vec = (0..elements.len()).map(|n| format!("_{n}: r.get()")).collect(); + let puts: String = (elements.iter().enumerate()) + .map(|(n, ty)| format!("\t\t{};\n", put(ty, &format!("self._{n}")))) + .collect(); + let _ = write!( + self.glue, + "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\tSelf {{ {} }}\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n{puts}\t}}\n}}\n\n", + fields.join(", ") + ); + } + /// The members a type's std traits export beyond Kotlin's own: `toString` from /// `Display`, `debug` from `Debug`, and a companion's `default` from `Default`, with /// `clone` and `equals` for an object. `this_c` is the C name, and `object` whether @@ -1450,7 +1471,12 @@ impl<'a> Gen<'a> { let rust_args: Vec = args.iter().flat_map(|a| a.rust_args.clone()).collect(); let after: Vec = args.iter().flat_map(|a| a.after.clone()).collect(); - let ok = strip_refs(&function.ok); + // A tuple of one returned whole is its element, written through its one out pointer; + // one behind a reference or `Box` is returned as a struct, so stays a tuple. + let ok = match &function.ok { + Type::Tuple(elements) if elements.len() == 1 => strip_refs(&elements[0]), + ok => strip_refs(ok), + }; let ret_kt = self.kt(&ok); let err = function.err.as_ref().map(strip_refs); let exception = err.as_ref().map(|e| { @@ -1678,6 +1704,14 @@ impl<'a> Gen<'a> { format!("{e}?.let {{ {v} -> {close} }}") } Type::Box(inner) => self.close(inner, e), + Type::Tuple(elements) => { + let t = self.fresh("t"); + let closes: Vec = (elements.iter().enumerate()) + .filter(|(_, ty)| moved(self.abi, ty)) + .map(|(k, ty)| self.close(ty, &format!("{t}.{}", ordinal(k)))) + .collect(); + format!("{e}.let {{ {t} -> {} }}", closes.join("; ")) + } Type::List(inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); @@ -1760,6 +1794,7 @@ fn moved(abi: &Abi<'_>, ty: &Type) -> bool { match ty { Type::Object(i) => !abi.api.objects[*i].copy, Type::Option(inner) | Type::Box(inner) | Type::List(inner) => moved(abi, inner), + Type::Tuple(elements) => elements.iter().any(|ty| moved(abi, ty)), _ => false, } } @@ -1959,6 +1994,17 @@ fn strip_refs(ty: &Type) -> Type { } } +/// The name of a tuple's field `k`, as `Pair`'s and `Triple`'s go on. +fn ordinal(k: usize) -> String { + const ORDINALS: [&str; 12] = [ + "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", + "twelfth", + ]; + ORDINALS + .get(k) + .map_or_else(|| format!("item{}", k + 1), |o| o.to_string()) +} + /// A snake-case name in Pascal case: `size_pair` is `SizePair`. fn pascal(name: &str) -> String { name.split('_') diff --git a/ffi/tests/api.c b/ffi/tests/api.c index a59d19063..12c5cf135 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -217,6 +217,105 @@ static int script(void) { api_error_free(&err); } } + /* A tuple inside another type is a struct, its fields _0, _1, and so on. */ + uint64_t spreads[] = {98305, 0}; + for (int i = 0; i < 2; i++) { + api_option_tuple_u8_i16_u32_u64 spread = api_spread(spreads[i]); + if (spread.some) { + printf("spread %u %d %u %llu\n", spread.value._0, spread.value._1, spread.value._2, + (unsigned long long)spread.value._3); + } else { + printf("spread none\n"); + } + } + const char *needles[] = {"lo", "x"}; + for (int i = 0; i < 2; i++) { + api_option_tuple_usize_usize found = api_find(str("hello"), str(needles[i])); + if (found.some) { + printf("find %zu %zu\n", found.value._0, found.value._1); + } else { + printf("find none\n"); + } + } + api_point row_points[] = {{.x = 1, .y = 2}, {.x = 3, .y = 3}}; + api_vec_tuple_string_shape_point stat_rows = api_rows((api_vec_point){.ptr = row_points, .len = 2}); + printf("rows"); + for (size_t i = 0; i < stat_rows.len; i++) { + /* The array's free frees each element's buffer. */ + printf("%s%.*s ", i == 0 ? " " : ", ", (int)stat_rows.ptr[i]._0.len, (const char *)stat_rows.ptr[i]._0.ptr); + print("", api_shape_debug(&stat_rows.ptr[i]._1), " "); + printf("%d %d", stat_rows.ptr[i]._2.x, stat_rows.ptr[i]._2.y); + } + printf("\n"); + api_vec_tuple_string_shape_point_free(stat_rows); + /* Each handle in a tuple moves in, as one taken by value does. */ + api_tuple_string_counter tallies[] = { + {._0 = str("low"), ._1 = api_counter_new(str("l"), 1)}, + {._0 = str("high"), ._1 = api_counter_new(str("h"), 9)}, + }; + api_board *board = api_board_new((api_vec_tuple_string_counter){.ptr = tallies, .len = 2}); + api_counter_free(tallies[0]._1); + api_counter_free(tallies[1]._1); + api_vec_tuple_string_counter ranked = api_board_ranked(board); + printf("ranked"); + for (size_t i = 0; i < ranked.len; i++) { + printf("%s%.*s ", i == 0 ? " " : ", ", (int)ranked.ptr[i]._0.len, (const char *)ranked.ptr[i]._0.ptr); + print("", api_counter_name(ranked.ptr[i]._1), " "); + printf("%llu", (unsigned long long)api_counter_get(ranked.ptr[i]._1)); + } + printf("\n"); + api_vec_tuple_string_counter_free(ranked); + api_board_free(board); + api_span span = { + .bounds = {._0 = 2, ._1 = 10}, + .named = {.some = true, .value = {._0 = str("s"), ._1 = API_SHAPE_SQUARE}}, + }; + api_tuple_u32_u32 lower_half, upper_half; + api_halves(span, &lower_half, &upper_half); + printf("halves %u %u %u %u ", lower_half._0, lower_half._1, upper_half._0, upper_half._1); + print("", api_span_debug(&span), "\n"); + uint32_t swapped_n; + api_buf swapped_text; + api_swapped((api_tuple_string_u32){._0 = str("t"), ._1 = 4}, &swapped_n, &swapped_text); + printf("swapped %u ", swapped_n); + print("", swapped_text, "\n"); + api_option_tuple_option_u32 doubles[] = { + {.some = false}, + {.some = true, .value = {._0 = {.some = false}}}, + {.some = true, .value = {._0 = {.some = true, .value = 3}}}, + }; + for (int i = 0; i < 3; i++) { + api_option_tuple_option_u32 doubled = api_doubled(doubles[i]); + if (!doubled.some) { + printf("doubled None\n"); + } else if (!doubled.value._0.some) { + printf("doubled Some((None,))\n"); + } else { + printf("doubled Some((Some(%u),))\n", doubled.value._0.value); + } + } + /* A borrowed or boxed tuple of one is a tuple struct, not its element. */ + uint8_t lent_bytes[] = {1, 2}; + uint8_t boxed_bytes[] = {3}; + api_tuple_bytes lent_one = api_lent_back((api_tuple_bytes){._0 = {.ptr = lent_bytes, .len = 2}}); + api_tuple_bytes boxed_one = api_boxed_tuple((api_buf){.ptr = boxed_bytes, .len = 1}); + api_buf both[] = {lent_one._0, boxed_one._0}; + for (int i = 0; i < 2; i++) { + printf("%s[", i == 0 ? "lent back " : " boxed "); + for (size_t j = 0; j < both[i].len; j++) { + printf("%s%u", j == 0 ? "" : ", ", both[i].ptr[j]); + } + printf("]"); + api_buf_free(both[i]); + } + printf("\n"); + /* A borrowed string and an owned one share a tuple struct. */ + api_option_tuple_string formal = api_title(true); + api_option_tuple_string informal = api_title(false); + api_option_tuple_string named = api_named(str("x")); + print("title Some((\"", formal.value._0, "\",)) "); + printf("%s ", informal.some ? "Some" : "None"); + print("named Some((\"", named.value._0, "\",))\n"); /* Each lent counter is a new handle to a clone. */ api_registry *registry = api_registry_new(api_counter_new(str("first"), 1)); @@ -298,6 +397,27 @@ static int script(void) { printf(" "); print_bound(api_end(0)); printf("\n"); + api_bound_u64 ends_start, ends_end; + api_ends(3, &ends_start, &ends_end); + printf("ends "); + print_bound(ends_start); + printf(" "); + print_bound(ends_end); + printf("\n"); + uint64_t belows[] = {2, 5}; + for (int i = 0; i < 2; i++) { + uint64_t n; + api_bounds_u64 outside; + if (api_below(belows[i], 3, &n, &outside)) { + printf("below %llu\n", (unsigned long long)n); + } else { + printf("below err "); + print_bound(outside.start); + printf(" "); + print_bound(outside.end); + printf("\n"); + } + } api_window window = {.range = {.start = 2, .end = 8}, .end = api_end(5)}; printf("window %s %s ", api_window_contains(&window, 4) ? "true" : "false", api_window_contains(&window, 6) ? "true" : "false"); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 58474db4b..619365bef 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -169,6 +169,86 @@ int script() { print("divide err ", api::error_to_string(r.error()), "\n"); } } + // A tuple inside another type is a std::tuple. + for (std::uint64_t n : {98305, 0}) { + if (auto spread = api::spread(n)) { + auto [s8, s16, s32, s64] = *spread; + std::printf("spread %u %d %u %llu\n", s8, s16, s32, ull(s64)); + } else { + std::printf("spread none\n"); + } + } + for (const char *needle : {"lo", "x"}) { + if (auto found = api::find("hello", needle)) { + std::printf("find %zu %zu\n", std::get<0>(*found), std::get<1>(*found)); + } else { + std::printf("find none\n"); + } + } + std::printf("rows"); + auto stat_rows = api::rows({api::point{1, 2}, api::point{3, 3}}); + for (std::size_t i = 0; i < stat_rows.size(); i++) { + auto &[name, shape, at] = stat_rows[i]; + print(i == 0 ? " " : ", ", name, " "); + print("", api::shape_debug(shape), " "); + std::printf("%d %d", at.x, at.y); + } + std::printf("\n"); + { + // Each handle in a tuple moves in, as one taken by value does. + std::vector> tallies; + tallies.emplace_back("low", api::counter::new_("l", 1)); + tallies.emplace_back("high", api::counter::new_("h", 9)); + auto board = api::board::new_(std::move(tallies)); + std::printf("ranked"); + auto ranked = board.ranked(); + for (std::size_t i = 0; i < ranked.size(); i++) { + auto &[name, counter] = ranked[i]; + print(i == 0 ? " " : ", ", name, " "); + print("", counter.name(), " "); + std::printf("%llu", ull(counter.get())); + } + std::printf("\n"); + } + api::span span{{2, 10}, std::make_tuple(api::buf("s"), api::shape::square)}; + auto [lower_half, upper_half] = api::halves(span); + std::printf("halves %u %u %u %u ", std::get<0>(lower_half), std::get<1>(lower_half), std::get<0>(upper_half), + std::get<1>(upper_half)); + print("", span.debug(), "\n"); + auto [swapped_n, swapped_text] = api::swapped({"t", 4}); + std::printf("swapped %u ", swapped_n); + print("", swapped_text, "\n"); + using single = std::tuple>; + for (const auto &value : {std::optional(), std::optional(single()), std::optional(single(3))}) { + auto doubled = api::doubled(value); + if (!doubled) { + std::printf("doubled None\n"); + } else if (auto n = std::get<0>(*doubled)) { + std::printf("doubled Some((Some(%u),))\n", *n); + } else { + std::printf("doubled Some((None,))\n"); + } + } + // A borrowed or boxed tuple of one is a tuple, not its element. + { + std::uint8_t lent_bytes[] = {1, 2}; + std::uint8_t boxed_bytes[] = {3}; + auto [lent] = api::lent_back(std::make_tuple(api::view(lent_bytes, 2))); + auto [boxed] = api::boxed_tuple(api::view(boxed_bytes, 1)); + const api::buf *both[] = {&lent, &boxed}; + for (int i = 0; i < 2; i++) { + std::printf("%s[", i == 0 ? "lent back " : " boxed "); + for (std::size_t j = 0; j < both[i]->size(); j++) { + std::printf("%s%u", j == 0 ? "" : ", ", both[i]->data()[j]); + } + std::printf("]"); + } + std::printf("\n"); + } + // A borrowed string and an owned one share a tuple struct. + print("title Some((\"", std::get<0>(*api::title(true)), "\",)) "); + std::printf("%s ", api::title(false) ? "Some" : "None"); + print("named Some((\"", std::get<0>(*api::named("x")), "\",))\n"); // Each lent counter is a new handle to a clone. api::registry registry = api::registry::new_(api::counter::new_("first", 1)); @@ -232,6 +312,23 @@ int script() { std::printf(" "); print_bound(api::end(0)); std::printf("\n"); + auto [ends_start, ends_end] = api::ends(3); + std::printf("ends "); + print_bound(ends_start); + std::printf(" "); + print_bound(ends_end); + std::printf("\n"); + for (std::uint64_t n : {2, 5}) { + if (auto r = api::below(n, 3)) { + std::printf("below %llu\n", ull(*r)); + } else { + std::printf("below err "); + print_bound(r.error().start); + std::printf(" "); + print_bound(r.error().end); + std::printf("\n"); + } + } api::window window{{2, 8}, api::end(5)}; std::printf("window %s %s ", yes(window.contains(4)), yes(window.contains(6))); print("", window.debug(), "\n"); diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index a96f7dcd8..970995243 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -83,6 +83,38 @@ fun script() { println("divide err ${e.message}") } } + // A tuple inside another type is a Pair, a Triple, or a longer tuple class. + for (n in listOf(98305uL, 0uL)) { + val spread = spread(n) + println(if (spread == null) "spread none" else "spread ${spread.first} ${spread.second} ${spread.third} ${spread.fourth}") + } + for (needle in listOf("lo", "x")) { + val found = find("hello".encodeToByteArray(), needle.encodeToByteArray()) + println(if (found == null) "find none" else "find ${found.first} ${found.second}") + } + val statRows = rows(listOf(Point(1, 2), Point(3, 3))) + println("rows ${statRows.joinToString(", ") { (name, shape, p) -> "$name ${shape.debug()} ${p.x} ${p.y}" }}") + // Each handle in a tuple moves in, as one taken by value does. + Board.new(listOf(Pair("low", Counter.new("l", 1u)), Pair("high", Counter.new("h", 9u)))).use { board -> + val ranked = board.ranked() + println("ranked ${ranked.joinToString(", ") { (name, counter) -> "$name ${counter.name()} ${counter.get()}" }}") + ranked.forEach { it.second.close() } + } + val span = Span(Pair(2u, 10u), Pair("s", Shape.SQUARE)) + val (lowerHalf, upperHalf) = halves(span) + println("halves ${lowerHalf.first} ${lowerHalf.second} ${upperHalf.first} ${upperHalf.second} ${span.debug()}") + val (swappedN, swappedText) = swapped(Pair("t", 4u)) + println("swapped $swappedN $swappedText") + for (value in listOf(null, Tuple1(null), Tuple1(3u))) { + val doubled = doubled(value) + println(if (doubled == null) "doubled None" else "doubled Some((${doubled.first?.let { "Some($it)" } ?: "None"},))") + } + // A borrowed or boxed tuple of one is a tuple, not its element. + val lentOne = lentBack(Tuple1(byteArrayOf(1, 2))).first.use { it.toByteArray().toList() } + val boxedOne = boxedTuple(byteArrayOf(3)).first.use { it.toByteArray().toList() } + println("lent back $lentOne boxed $boxedOne") + // A borrowed string and an owned one share a tuple struct. + println("title Some((\"${title(true)!!.first}\",)) ${if (title(false) == null) "None" else "Some"} named Some((\"${named("x")!!.first}\",))") // Each lent counter is a new handle to a clone. val registry = Registry.new(Counter.new("first", 1u)) @@ -129,6 +161,15 @@ fun script() { ).map { count(it) } println("count ${counts.joinToString(" ")}") println("end ${bound(end(3u))} ${bound(end(0u))}") + val (endsStart, endsEnd) = ends(3u) + println("ends ${bound(endsStart)} ${bound(endsEnd)}") + for (n in listOf(2uL, 5uL)) { + try { + println("below ${below(n, 3u)}") + } catch (e: BoundsU64Exception) { + println("below err ${bound(e.error.start)} ${bound(e.error.end)}") + } + } val window = Window(RangeU64(2u, 8u), end(5u)) println("window ${window.contains(4u)} ${window.contains(6u)} ${window.debug()}") diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index c48a608d0..78e0bc649 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -49,7 +49,6 @@ Every generator on the C ABI: - [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` - [Sessions on sans-IO QUIC](/quest/m1/ffi-export/session-quic.md) - bindings move UDP datagrams and drive the session's poll themselves, over moq's runtime-free QUIC driver once it lands -- [Tuples inside other types](/quest/m1/ffi-export/tuples.md) - a tuple crosses as an iterator's or `Vec`'s item, in an `Option`, or as a field, so hang's `ranked` exports - [C++ bindings on MSVC and Clang](/quest/m1/ffi-export/cpp.md) - the C++ header built and tested beyond GCC on Linux - [Kotlin bindings on Android](/quest/m1/ffi-export/kotlin-android.md) - an R8 keep rule for JNI's lookups, and an emulator run in CI - [Kotlin payload reads at JNI's cost](/quest/m1/ffi-export/kotlin-reads.md) - a Kotlin payload read stops paying `NewDirectByteBuffer`'s ~100 ns, if the maintainer lets `Bytes` copy diff --git a/quest/m1/ffi-export/tuples.md b/quest/m1/ffi-export/tuples.md deleted file mode 100644 index e9258de15..000000000 --- a/quest/m1/ffi-export/tuples.md +++ /dev/null @@ -1,35 +0,0 @@ -# [M] Tuples inside other types - -## Goal - -A tuple crosses wherever its elements map, not only as a function's whole return: as an -iterator's or `Vec`'s item, inside an `Option` or `Result`, and as a record's field or a -parameter. - -hang's `catalog::Audio::ranked` and `catalog::Video::ranked` are the consumer. They return -`impl Iterator` (and `&VideoConfig`), which -[#213](https://github.com/moq-dev/rust2/pull/213) collects into an array but refuses for -the tuple. They export as an array of pairs, each a string and a clone of the config object. -The same refusal holds back moq-net's `stats::Snapshot::{control, traffic, sessions}` (`Vec`s -of 2- and 3-tuples) and moq-mux's `codec::annexb::find_start_code` (`Option<(usize, usize)>`), -which come with it. Their excludes leave [the config](/ffi/moq/ffi.toml). - -C, C++ and Kotlin match native Rust's transcript, and the PR reports the census before and -after. - -## Plan - -`ir::Type::Tuple` is only a return today, lowered to one out pointer per element. As a value -it needs a layout in each language: - -- C: a generated struct per distinct element list, with fields `_0`, `_1`, and so on, named - by the rule from its elements. -- C++: `std::tuple`, as a return is already. -- Kotlin: `Pair`, `Triple`, and the generated data class beyond three, as a return is already. - -Open: whether a whole return keeps its out pointers or becomes the struct. Keeping them avoids -a breaking change to every tuple-returning C function. One rule is simpler, but a change needs -a `MIGRATE.md` entry. Decide by which reads better at moq's call sites. - -The `(start, end)` pair that maps to a bound keeps its own mapping. `Audio::enabled` and -`Video::enabled` stay refused, since they `filter` through a closure, which #213 refuses.