From 53e1b93fa4dbc401834cb3136a956fad9ba984fc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:07:24 -0700 Subject: [PATCH 1/6] chore(quest): claim quest/m1/ffi-export/tuples.md Quest-Claim: 0222202dd6e6899d From b5cce918bf5fedf0bcbf6598e78d3b0241f8e88d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:23:17 -0700 Subject: [PATCH 2/6] feat(ffi): export tuples inside other types as C structs A tuple now crosses wherever its elements map: as a Vec's or iterator's item, inside an Option or Result, as a record's field, or as a parameter. C gets a struct per element list, _tuple__ with fields _0, _1, ...; C++ a std::tuple and Kotlin a Pair, Triple, or TupleN, as a returned tuple already was. A whole returned tuple keeps its out pointers. hang's catalog Audio/Video::ranked, moq-net's stats::Snapshot::{control, traffic, sessions} and moq-mux's codec::annexb::find_start_code now export. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 1 + ffi/fixtures/api/examples/transcript.rs | 33 +++++++++++ ffi/fixtures/api/src/lib.rs | 67 +++++++++++++++++++++ ffi/fixtures/reject/expected.txt | 2 +- ffi/fixtures/reject/src/lib.rs | 6 +- ffi/moq/ffi.toml | 6 -- ffi/src/abi.rs | 32 +++++++++- ffi/src/c.rs | 13 ++++ ffi/src/collect.rs | 43 ++++++-------- ffi/src/cpp.rs | 45 +++++++++++--- ffi/src/glue.rs | 36 ++++++++++- ffi/src/ir.rs | 2 +- ffi/src/kotlin.rs | 79 +++++++++++++++++++------ ffi/tests/api.c | 62 +++++++++++++++++++ ffi/tests/api.cpp | 49 +++++++++++++++ ffi/tests/api.kt | 22 +++++++ 16 files changed, 432 insertions(+), 66 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index cbbf26931..cc5982ca1 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 | diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 6e233edab..40db8713c 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -99,6 +99,39 @@ 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}"); // Each lent counter is a new handle to a clone. let mut registry = Registry::new(Counter::new("first", 1)); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 197d2c8af..9a0986e72 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -179,6 +179,73 @@ 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)) +} + +/// `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 { diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index bfae6c52a..0b81abc09 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -82,5 +82,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..0cc8357d6 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. 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..7a84cf8c2 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)), @@ -410,7 +423,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 +653,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 +670,7 @@ impl<'a> Abi<'a> { let mut options = BTreeMap::new(); let mut ranges = BTreeMap::new(); let mut lists = BTreeMap::new(); + let mut tuples = BTreeMap::new(); let mut stack = types; while let Some(ty) = stack.pop() { match ty { @@ -668,7 +686,11 @@ 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. + tuples.insert(self.tuple(elements), elements.iter().map(owned).collect()); + stack.extend(elements); + } Type::Closure(params, ret) => { stack.extend(params); stack.push(ret); @@ -689,6 +711,9 @@ impl<'a> Abi<'a> { for name in ranges.keys() { self.claim(name.clone(), "a range".to_string(), crate_span); } + for name in tuples.keys() { + self.claim(name.clone(), "a tuple".to_string(), 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 +731,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 b74cb85e8..25a450354 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1815,7 +1815,7 @@ impl<'tcx> Collector<'tcx> { // refused. let mut collect = false; if !future - && self.ret(output).is_err() + && self.ty(output, Pos::Return).is_err() && let Some(items) = self .collected(output, env) .and_then(|item| self.vec_of(normalize(item))) @@ -1824,10 +1824,11 @@ impl<'tcx> Collector<'tcx> { collect = true; } let (ok, err) = match output.kind() { - ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => { - (self.ret(args.type_at(0)), Some(self.ty(args.type_at(1), Pos::Return))) - } - _ => (self.ret(output), None), + ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => ( + self.ty(args.type_at(0), Pos::Return), + Some(self.ty(args.type_at(1), Pos::Return)), + ), + _ => (self.ty(output, Pos::Return), None), }; let ok = ok.map_err(|why| errs.push(why)).ok(); let err = match err { @@ -2727,24 +2728,6 @@ impl<'tcx> Collector<'tcx> { (held, lent) } - /// What a function returns: a tuple's elements each, or else one value. - 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); - } - 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), - } - } - Ok(Type::Tuple(elements)) - } - /// `(Bound, Bound)`, which a `RangeBounds` parameter takes. fn bounds(&self, int: Ty<'tcx>) -> Option> { let tcx = self.tcx; @@ -3069,7 +3052,17 @@ impl<'tcx> Collector<'tcx> { { Type::Bounds(int) } - _ => return Err(why("tuple", "")), + list => { + let elements = (list.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())); + } + Type::Tuple(elements) + } }, ty::Array(..) => return Err(why("array", ty.to_string())), ty::Slice(_) | ty::Str => return Err(why("unsized type", ty.to_string())), @@ -3136,6 +3129,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() @@ -3199,6 +3193,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 a2c199471..50da4ffa0 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -276,17 +276,8 @@ impl<'a> Gen<'a> { 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,16 @@ impl<'a> Gen<'a> { name } + /// The Kotlin type of a tuple of `elements`: one element alone is itself. + fn tuple_of(&mut self, elements: Vec) -> String { + 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(", ")), + } + } + /// 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 +328,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 +341,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 +395,14 @@ 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) if elements.len() == 1 => self.write_value(&elements[0], w, e), + 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,7 +463,7 @@ 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(", ")), @@ -628,6 +636,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 +746,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 @@ -1678,6 +1702,15 @@ impl<'a> Gen<'a> { format!("{e}?.let {{ {v} -> {close} }}") } Type::Box(inner) => self.close(inner, e), + Type::Tuple(elements) if elements.len() == 1 => self.close(&elements[0], 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 +1793,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 +1993,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 3ae0a5141..7ca8a2de1 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -217,6 +217,68 @@ 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"); /* Each lent counter is a new handle to a clone. */ api_registry *registry = api_registry_new(api_counter_new(str("first"), 1)); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 6f5b9b8c5..b99b3af77 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -169,6 +169,55 @@ 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"); // Each lent counter is a new handle to a clone. api::registry registry = api::registry::new_(api::counter::new_("first", 1)); diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 160adb87a..db0409c0a 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -83,6 +83,28 @@ 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") // Each lent counter is a new handle to a clone. val registry = Registry.new(Counter.new("first", 1u)) From 8d15d3710ed3d12440d5ad3c7f9ca6ac32ca3726 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:32:03 -0700 Subject: [PATCH 3/6] chore(quest): finish m1/ffi-export/tuples A whole returned tuple keeps its C out pointers, as the maintainer picked. Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-export/README.md | 1 - quest/m1/ffi-export/tuples.md | 35 ----------------------------------- 2 files changed, 36 deletions(-) delete mode 100644 quest/m1/ffi-export/tuples.md diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 2f5fabb58..49fd7bc2e 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 reads at JNI's cost](/quest/m1/ffi-export/kotlin-reads.md) - a ready Kotlin read loses the allocations that keep it ~230 ns over C diff --git a/quest/m1/ffi-export/tuples.md b/quest/m1/ffi-export/tuples.md deleted file mode 100644 index f0fb0f805..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/kixelated/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. From a1f8b3de72769f661e5ffdd58ce43b24e059e461 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:41:26 -0700 Subject: [PATCH 4/6] fix(ffi): fail on tuples sharing a C name, keep a bounds pair's return, and wrap a nested tuple of one in Kotlin Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 2 +- ffi/fixtures/api/examples/transcript.rs | 5 ++++ ffi/fixtures/api/src/lib.rs | 12 ++++++++ ffi/fixtures/reject/expected.txt | 2 ++ ffi/fixtures/reject/src/lib.rs | 6 ++++ ffi/src/abi.rs | 38 ++++++++++++++++++++++--- ffi/src/collect.rs | 4 ++- ffi/src/kotlin.rs | 18 ++++++------ ffi/tests/api.c | 22 ++++++++++++++ ffi/tests/api.cpp | 17 +++++++++++ ffi/tests/api.kt | 6 ++++ 11 files changed, 117 insertions(+), 15 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 3325b5270..a83347de7 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -242,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 cd64db54d..3fafd8c48 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -132,6 +132,9 @@ fn main() { 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)); + } // Each lent counter is a new handle to a clone. let mut registry = Registry::new(Counter::new("first", 1)); @@ -177,6 +180,8 @@ 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:?}"); 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 252233065..74a8c41c9 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -241,6 +241,12 @@ pub fn halves(span: &Span) -> ((u32, u32), (u32, u32)) { ((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),)) +} + /// `pair` with its sides swapped: a tuple taken by value. pub fn swapped(pair: (String, u32)) -> (u32, String) { (pair.1, pair.0) @@ -342,6 +348,12 @@ 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)) +} + /// 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 0b81abc09..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 diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 0cc8357d6..6eecc5cb7 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -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/src/abi.rs b/ffi/src/abi.rs index 7a84cf8c2..4d200cfae 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -371,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!( @@ -670,7 +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::new(); + let mut tuples: BTreeMap> = BTreeMap::new(); + let mut mixed = Vec::new(); let mut stack = types; while let Some(ty) = stack.pop() { match ty { @@ -688,7 +704,16 @@ impl<'a> Abi<'a> { Type::Ref(_, inner) | Type::Box(inner) => stack.push(inner), Type::Tuple(elements) => { // A returned tuple of borrows holds clones, as a `Vec` does. - tuples.insert(self.tuple(elements), elements.iter().map(owned).collect()); + let owned: Vec = elements.iter().map(owned).collect(); + let name = self.tuple(elements); + match tuples.get(&name) { + // Its name runs its elements' together, which two nestings can share. + Some(other) if *other != owned => mixed.push((name, owned)), + Some(_) => {} + None => { + tuples.insert(name, owned); + } + } stack.extend(elements); } Type::Closure(params, ret) => { @@ -711,8 +736,13 @@ impl<'a> Abi<'a> { for name in ranges.keys() { self.claim(name.clone(), "a range".to_string(), crate_span); } - for name in tuples.keys() { - self.claim(name.clone(), "a tuple".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); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 6a7eebf85..7b82dd868 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3040,8 +3040,10 @@ impl<'tcx> Collector<'tcx> { } } ty::Tuple(list) => match list.as_slice() { + // Returned whole, the pair is a tuple, written through an out pointer each. [start, end] - if start == end + if pos != Pos::Return + && start == end && let Some(int) = self.bound_of(*start) => { Type::Bounds(int) diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 50da4ffa0..0169b0d32 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,8 +270,8 @@ 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) { @@ -288,10 +288,9 @@ impl<'a> Gen<'a> { name } - /// The Kotlin type of a tuple of `elements`: one element alone is itself. + /// The Kotlin type of a tuple of `elements`. fn tuple_of(&mut self, elements: Vec) -> String { 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(", ")), @@ -395,7 +394,6 @@ 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) if elements.len() == 1 => self.write_value(&elements[0], w, e), Type::Tuple(elements) => { let t = self.fresh("t"); let writes: Vec = (elements.iter().enumerate()) @@ -465,7 +463,6 @@ impl<'a> Gen<'a> { Type::Tuple(elements) => { 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(", ")), @@ -1474,7 +1471,11 @@ 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. + let ok = match strip_refs(&function.ok) { + Type::Tuple(mut elements) if elements.len() == 1 => elements.remove(0), + ok => ok, + }; let ret_kt = self.kt(&ok); let err = function.err.as_ref().map(strip_refs); let exception = err.as_ref().map(|e| { @@ -1702,7 +1703,6 @@ impl<'a> Gen<'a> { format!("{e}?.let {{ {v} -> {close} }}") } Type::Box(inner) => self.close(inner, e), - Type::Tuple(elements) if elements.len() == 1 => self.close(&elements[0], e), Type::Tuple(elements) => { let t = self.fresh("t"); let closes: Vec = (elements.iter().enumerate()) diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 344f6b2e2..1193ec4fd 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -279,6 +279,21 @@ static int script(void) { 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); + } + } /* Each lent counter is a new handle to a clone. */ api_registry *registry = api_registry_new(api_counter_new(str("first"), 1)); @@ -360,6 +375,13 @@ 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"); 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 54c173cf4..843e36259 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -218,6 +218,17 @@ int script() { 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"); + } + } // Each lent counter is a new handle to a clone. api::registry registry = api::registry::new_(api::counter::new_("first", 1)); @@ -281,6 +292,12 @@ 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"); 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 3d50844b8..a4225318b 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -105,6 +105,10 @@ fun script() { 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"},))") + } // Each lent counter is a new handle to a clone. val registry = Registry.new(Counter.new("first", 1u)) @@ -151,6 +155,8 @@ 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)}") val window = Window(RangeU64(2u, 8u), end(5u)) println("window ${window.contains(4u)} ${window.contains(6u)} ${window.debug()}") From 65e9db4da6569a8b9a49df838389fd052a0d5230 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:45:09 -0700 Subject: [PATCH 5/6] fix(ffi): map only a whole success return's bound pair as a tuple, and clash tuples only on C layout Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 12 ++++++ ffi/fixtures/api/src/lib.rs | 20 ++++++++++ ffi/src/abi.rs | 3 +- ffi/src/collect.rs | 49 +++++++++++++++---------- ffi/tests/api.c | 21 +++++++++++ ffi/tests/api.cpp | 15 ++++++++ ffi/tests/api.kt | 9 +++++ 7 files changed, 108 insertions(+), 21 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 3fafd8c48..166855522 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -135,6 +135,12 @@ fn main() { for value in [None, Some((None,)), Some((Some(3),))] { println!("doubled {:?}", api_lib::doubled(value)); } + 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)); @@ -182,6 +188,12 @@ fn main() { 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 74a8c41c9..2e6012eb3 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -247,6 +247,17 @@ 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(),)) +} + /// `pair` with its sides swapped: a tuple taken by value. pub fn swapped(pair: (String, u32)) -> (u32, String) { (pair.1, pair.0) @@ -354,6 +365,15 @@ 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/src/abi.rs b/ffi/src/abi.rs index 4d200cfae..233275063 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -706,9 +706,10 @@ impl<'a> Abi<'a> { // 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 *other != owned => mixed.push((name, owned)), + Some(other) if layout(other) != layout(&owned) => mixed.push((name, owned)), Some(_) => {} None => { tuples.insert(name, owned); diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 7b82dd868..4438c48ab 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1815,7 +1815,7 @@ impl<'tcx> Collector<'tcx> { // refused. let mut collect = false; if !future - && self.ty(output, Pos::Return).is_err() + && self.ret(output).is_err() && let Some(items) = self .collected(output, env) .and_then(|item| self.vec_of(normalize(item))) @@ -1824,11 +1824,10 @@ impl<'tcx> Collector<'tcx> { collect = true; } let (ok, err) = match output.kind() { - ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => ( - self.ty(args.type_at(0), Pos::Return), - Some(self.ty(args.type_at(1), Pos::Return)), - ), - _ => (self.ty(output, Pos::Return), None), + ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Result, adt.did()) => { + (self.ret(args.type_at(0)), Some(self.ty(args.type_at(1), Pos::Return))) + } + _ => (self.ret(output), None), }; let ok = ok.map_err(|why| errs.push(why)).ok(); let err = match err { @@ -2722,6 +2721,28 @@ impl<'tcx> Collector<'tcx> { (held, lent) } + /// 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 { + match ty.kind() { + ty::Tuple(list) if !list.is_empty() => self.tuple(ty, Pos::Return), + _ => self.ty(ty, Pos::Return), + } + } + + /// 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)) + } + /// `(Bound, Bound)`, which a `RangeBounds` parameter takes. fn bounds(&self, int: Ty<'tcx>) -> Option> { let tcx = self.tcx; @@ -3040,25 +3061,13 @@ impl<'tcx> Collector<'tcx> { } } ty::Tuple(list) => match list.as_slice() { - // Returned whole, the pair is a tuple, written through an out pointer each. [start, end] - if pos != Pos::Return - && start == end + if start == end && let Some(int) = self.bound_of(*start) => { Type::Bounds(int) } - list => { - let elements = (list.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())); - } - Type::Tuple(elements) - } + _ => 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())), diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 1193ec4fd..08ef0c27b 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -294,6 +294,13 @@ static int script(void) { printf("doubled Some((Some(%u),))\n", doubled.value._0.value); } } + /* 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)); @@ -382,6 +389,20 @@ static int script(void) { 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 843e36259..3129fe2f7 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -229,6 +229,10 @@ int script() { std::printf("doubled Some((None,))\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)); @@ -298,6 +302,17 @@ int script() { 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 a4225318b..223da20bb 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -109,6 +109,8 @@ fun script() { val doubled = doubled(value) println(if (doubled == null) "doubled None" else "doubled Some((${doubled.first?.let { "Some($it)" } ?: "None"},))") } + // 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)) @@ -157,6 +159,13 @@ fun script() { 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()}") From c25212cf1a716a15e1c64c77419b158f09c91af2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:25:08 -0700 Subject: [PATCH 6/6] fix(ffi): flatten only a tuple of one returned whole in Kotlin, not one behind a reference or Box Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 4 ++++ ffi/fixtures/api/src/lib.rs | 11 +++++++++++ ffi/src/kotlin.rs | 9 +++++---- ffi/tests/api.c | 15 +++++++++++++++ ffi/tests/api.cpp | 16 ++++++++++++++++ ffi/tests/api.kt | 4 ++++ 6 files changed, 55 insertions(+), 4 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 166855522..cea6cc249 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -135,6 +135,10 @@ fn main() { 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), diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 2e6012eb3..e5fccbb98 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -258,6 +258,17 @@ 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) diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 5d63d065a..c25c97b80 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -1471,10 +1471,11 @@ 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(); - // A tuple of one returned whole is its element, written through its one out pointer. - let ok = match strip_refs(&function.ok) { - Type::Tuple(mut elements) if elements.len() == 1 => elements.remove(0), - ok => 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); diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 08ef0c27b..12c5cf135 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -294,6 +294,21 @@ static int script(void) { 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); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 3129fe2f7..619365bef 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -229,6 +229,22 @@ int script() { 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"); diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 223da20bb..970995243 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -109,6 +109,10 @@ fun script() { 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}\",))")