From 7bb5b8fd9f28049b57f600ad2762f08622461be6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:38:05 -0800 Subject: [PATCH 1/9] chore(quest): claim quest/m1/ffi-speed/kotlin-values.md Quest-Claim: a344ebf337874708 From 571d12b81e7a94f70f7d40c9e5a42800c9eee57e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:10:10 -0800 Subject: [PATCH 2/9] feat(ffi): Kotlin values hold a Long per word, with no LongArray Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 10 +- ffi/fixtures/api/src/lib.rs | 50 ++++++- ffi/runtime/jni.rs | 58 ++------- ffi/src/kotlin.rs | 252 +++++++++++++++++++++--------------- ffi/tests/api.kt | 8 ++ 5 files changed, 223 insertions(+), 155 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 78a3ceef1..866fff162 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -492,8 +492,10 @@ kotlinx-coroutines. Each value crosses JNI as a scalar, a handle as a `Long`, by in as a `ByteArray`, bytes returned as their owner, a block of numbers as its primitive array, and anything else encoded into a `ByteArray` as its C struct holds it. A record a call takes or returns directly, or in an `Option` returned, crosses as its scalars, a -nested record's included, as JNI parameters in and through a `LongArray` each thread keeps -out, with only its other fields encoded. +nested record's included, and an opaque value as its 64-bit words, as JNI parameters in +and through a `LongArray` each thread keeps out, with only a record's other fields encoded; +an opaque value of one word returns as that `Long`. Past the 255 slots a JVM method takes, +the rest cross encoded. - **Names** are in a package of the prefix: types in PascalCase without it, members in camelCase without their type's name (`moq.TrackProducer.appendGroup`). Pascal case @@ -518,8 +520,8 @@ out, with only its other fields encoded. value** is a class with an internal constructor, so only Rust makes one: of no more than 8 bytes on every target, with no padding, fields of integers, `bool`s, and `char`s alone, nested or not, and a derived or std `PartialEq`, a value class over a `Long`, compared by its bits, which - allocates nothing unless Kotlin boxes it, as in a `List` or a nullable; otherwise one over - a `LongArray`, whose `==` is Rust's, and whose `hashCode` is 0, since none Kotlin + allocates nothing unless Kotlin boxes it, as in a `List` or a nullable; otherwise a class of a `Long` for each 64-bit word of its bytes, which allocates + nothing where the JIT sees it does not escape, whose `==` is Rust's, and whose `hashCode` is 0, since none Kotlin computes agrees with it. Either is shared by reference, so it never changes: a `&mut self` method, a field's setter included, returns the value as the call left it, `x = x.add(o)`, and beside Rust's own return, a `Pair`, or each element of its tuple, diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index b3e7f593a..9711519c6 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1253,7 +1253,7 @@ impl Gap { } } -/// A value named as Kotlin's `LongArray`, which holds a value's words, with a method named +/// A value named as Kotlin's `LongArray`, which holds a returned value's words, with a method named /// as C++'s member holding its bytes: each generator keeps its own apart. #[derive(Clone, Copy, Debug, PartialEq)] pub struct LongArray { @@ -1270,6 +1270,54 @@ impl LongArray { } } +/// A value of 64 words: Kotlin passes one as its words, but two, as its `==` takes, past a +/// JVM method's 255 slots, so encoded. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Wide { + words: [u64; 64], +} + +impl Wide { + /// Words `seed`, `seed + 1`, and on, wrapping. + pub fn new(seed: u64) -> Self { + Self { + words: std::array::from_fn(|k| seed.wrapping_add(k as u64)), + } + } + + pub fn sum(&self) -> u64 { + self.words.iter().fold(0, |a, w| a.wrapping_add(*w)) + } +} + +/// A moment and a count: a record holding a value past a word, flattened as its words. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clocked { + pub at: Moment, + pub count: u32, +} + +/// `clocked`, its moment `ticks` later and its count one more. +pub fn clocked_after(clocked: Clocked, ticks: u64) -> Clocked { + Clocked { + at: clocked.at.after(ticks), + count: clocked.count + 1, + } +} + +/// Declares `crammed`, whose numbers take 248 of a JVM method's 255 slots, so its first +/// moment crosses as its words and its second, past the limit, encoded. +macro_rules! crammed { + ($($n:ident)*) => { + /// Both moments' millis and every number, summed. + pub fn crammed(a: Moment, b: Moment, $($n: u64),*) -> u64 { + a.millis().wrapping_add(b.millis())$(.wrapping_add($n))* + } + }; +} + +crammed!(n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 n16 n17 n18 n19 n20 n21 n22 n23 n24 n25 n26 n27 n28 n29 n30 n31 n32 n33 n34 n35 n36 n37 n38 n39 n40 n41 n42 n43 n44 n45 n46 n47 n48 n49 n50 n51 n52 n53 n54 n55 n56 n57 n58 n59 n60 n61 n62 n63 n64 n65 n66 n67 n68 n69 n70 n71 n72 n73 n74 n75 n76 n77 n78 n79 n80 n81 n82 n83 n84 n85 n86 n87 n88 n89 n90 n91 n92 n93 n94 n95 n96 n97 n98 n99 n100 n101 n102 n103 n104 n105 n106 n107 n108 n109 n110 n111 n112 n113 n114 n115 n116 n117 n118 n119 n120 n121 n122 n123); + /// A `Copy` type whose `None` leaves its payload's bytes uninitialized, so no padding table /// covers it: a handle, rather than a value. #[derive(Clone, Copy, Debug)] diff --git a/ffi/runtime/jni.rs b/ffi/runtime/jni.rs index 9702cc561..272f65641 100644 --- a/ffi/runtime/jni.rs +++ b/ffi/runtime/jni.rs @@ -984,62 +984,26 @@ impl Writer { } } -/// An opaque value's C struct from the `long` Kotlin holds it in: its bytes, at the word's -/// lowest addresses, as [`to_word`] put them. -pub fn from_word(word: jlong) -> T { - const { assert!(size_of::() <= size_of::()) }; +/// An opaque value's C struct from the `W` `long`s Kotlin holds it in: its bytes, in the +/// words' order, as [`to_words`] put them. +pub fn from_words(words: [jlong; W]) -> T { + const { assert!(size_of::() <= W * size_of::()) }; let mut value = std::mem::MaybeUninit::::zeroed(); // SAFETY: `T` is a struct of `MaybeUninit` units, any bytes of which are one. unsafe { - std::ptr::copy_nonoverlapping((&raw const word).cast::(), value.as_mut_ptr().cast::(), size_of::()); - value.assume_init() - } -} - -/// The `long` Kotlin holds an opaque value's C struct in, which has no padding: Kotlin -/// compares two by it. -pub fn to_word(value: T) -> jlong { - const { assert!(size_of::() <= size_of::()) }; - let mut word: jlong = 0; - // SAFETY: every byte of a value with no padding is initialized, and the rest are zero. - unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::(), (&raw mut word).cast::(), size_of::()) }; - word -} - -/// An opaque value's C struct from the `W` words of the `long[]` Kotlin holds it in. -/// -/// # Safety -/// `array` is a live `long[]`. -pub unsafe fn from_words(env: *mut JNIEnv, array: jlongArray) -> T { - const { assert!(size_of::() <= W * size_of::()) }; - let mut words = [std::mem::MaybeUninit::::zeroed(); W]; - // SAFETY: `array` is live, and `T` is a struct of `MaybeUninit` units. - unsafe { - if array.is_null() || ((**env).v1_2.GetArrayLength)(env, array) != W as jsize { - fail(env, "jni", "an opaque value's words are not its own"); - } - ((**env).v1_2.GetLongArrayRegion)(env, array, 0, W as jsize, words.as_mut_ptr().cast()); - let mut value = std::mem::MaybeUninit::::zeroed(); std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), value.as_mut_ptr().cast::(), size_of::()); value.assume_init() } } -/// A new `long[]` of the `W` words an opaque value's C struct is held in: its bytes, then -/// zeros. Its padding crosses as the bytes it holds, which Kotlin never reads. -pub fn to_words(env: *mut JNIEnv, value: T) -> jlongArray { +/// The `W` `long`s Kotlin holds an opaque value's C struct in: its bytes, then zeros. +/// Kotlin compares a value class of one by it. +pub fn to_words(value: T) -> [jlong; W] { const { assert!(size_of::() <= W * size_of::()) }; - let mut words = [std::mem::MaybeUninit::::zeroed(); W]; - // SAFETY: `env` is this thread's; JNI copies the words as bytes. - unsafe { - std::ptr::copy_nonoverlapping((&raw const value).cast::(), words.as_mut_ptr().cast::(), size_of::()); - let array = ((**env).v1_2.NewLongArray)(env, W as jsize); - if array.is_null() { - fail(env, "jni", "a long[] is out of memory"); - } - ((**env).v1_2.SetLongArrayRegion)(env, array, 0, W as jsize, words.as_ptr().cast()); - array - } + let mut words = [0; W]; + // SAFETY: an opaque value's C struct initializes every byte, as the glue makes it. + unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::(), words.as_mut_ptr().cast::(), size_of::()) }; + words } /// An opaque value's C struct as it crosses encoded: the `W` words Kotlin holds it in, diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 79d220b00..5154374c6 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -17,8 +17,9 @@ //! bytes returned as their owner, which a `Bytes` reads through a call each, or encoded //! into native scratch memory consumed synchronously by a kept Kotlin factory. Composite //! results cross JNI as their constructed Kotlin value, without a transport `byte[]`. -//! A record passed or returned directly crosses as its scalars instead, parameters in and -//! a thread's `long[]` slots out, with only its other fields encoded. +//! A record passed or returned directly crosses as its scalars instead, and an opaque +//! value as its words, parameters in and a thread's `long[]` slots out, with only a +//! record's other fields encoded; an opaque value of one word returns as that `long`. //! An object never closed, and Rust's bytes, are freed once the GC collects them. use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -863,7 +864,7 @@ impl<'a> Gen<'a> { _ => wrap(e), } } - Ty::Struct(name) if opaque_of(self.abi, c).is_some() => format!("{}({e})", self.qualified(name)), + Ty::Struct(name) if opaque_of(self.abi, c).is_some_and(|o| one_word(&o)) => format!("{}({e})", self.qualified(name)), Ty::Buf => match (decode(ty), matches!(ty.base(), Type::Option(_)), lent) { (Some(decode), true, _) => format!("{e}?.{decode}"), (Some(decode), false, _) => format!("{e}!!.{decode}"), @@ -887,7 +888,11 @@ impl<'a> Gen<'a> { match c { Ty::Int(int) => to_signed(*int, e), Ty::Buf => format!("{e}.encodeToByteArray()"), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) => format!("{e}.{}", holder(&opaque)), + Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + format!("{e}.{}", holders(&opaque)[0]) + } Ty::Struct(_) => { let w = self.fresh("w"); let write = self.write_value(ty, &w, e); @@ -1000,20 +1005,12 @@ impl<'a> Gen<'a> { "crate::{name} {{ vtable: &VTABLE_{name}, data: rt::global(env, {p}) }}" )); } - // An opaque value crosses as the word or words Kotlin holds it in. - Ty::Struct(_) | Ty::In(_) if let Some(opaque) = opaque_of(abi, c) => { - arg.exprs.push(format!("{e}.{}", holder(&opaque))); - arg.rust_pre.push(format!("let a{p} = {};", from_kotlin(&opaque, &p))); - arg.rust_args.push(match c { - Ty::In(_) => format!("&a{p}"), - _ => format!("a{p}"), - }); - } - // A record crosses as its scalars, and its other fields encoded into one `byte[]`. - // Only while the call's JVM parameters stay within the 255 slots a method takes. + // A record crosses as its scalars, and its other fields encoded into one `byte[]`; + // an opaque value as the words Kotlin holds it in. Only while the call's JVM + // parameters stay within the 255 slots a method takes, which a word always does. Ty::Struct(_) | Ty::In(_) if let Type::Record(i) = ty.base() - && let Some(left) = self.room.checked_sub(weight(abi, *i).saturating_sub(c_slots(abi, c))) => + && let Some(left) = self.room.checked_sub(weight(abi, *i).saturating_sub(c_slots(c))) => { self.room = left; arg.jni.clear(); @@ -1285,8 +1282,11 @@ impl<'a> Gen<'a> { Type::Record(i) => self.abi.api.records[*i].opaque, _ => None, }; + // Whether `n` opaque values cross as their words within the 255 JVM slots a method + // takes, or else encoded. + let fits = |n: u64| opaque.is_some_and(|o| 2 * n * o.words() <= 255); // The receiver as the glue takes it: a handle, held for the call, an opaque value's - // word or words, or encoded. + // words, or encoded. let (params, open, arg, rust_self): (Vec<(&str, &str)>, _, _, _) = match (object, opaque) { (true, _) => ( vec![("jlong", "Long")], @@ -1294,16 +1294,16 @@ impl<'a> Gen<'a> { "h".to_string(), "p0 as usize as _".to_string(), ), - (false, Some(opaque)) => { - let (jni, native) = jni_type(self.abi, &Ty::Struct(c.to_string()), ty); + (false, Some(opaque)) if fits(1) => { + let words: Vec = (0..opaque.words()).map(|k| format!("p{k}")).collect(); ( - vec![(jni, native)], + vec![("jlong", "Long"); words.len()], "run {".to_string(), - holder(&opaque).to_string(), - format!("&{}", from_kotlin(&opaque, "p0")), + holders(&opaque).join(", "), + format!("&{}", from_kotlin(&opaque, &words)), ) } - (false, None) => { + (false, _) => { let write = self.write_value(ty, "w", "this"); ( vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], @@ -1345,20 +1345,33 @@ impl<'a> Gen<'a> { "\t/** A new handle to a clone. */\n\tfun clone(): {class} = handle.hold {{ h -> {class}(_Native.{bare}_clone(h)) }}\n" )); } - // An opaque value Kotlin holds in a word compares by it, as a value class does. + // An opaque value Kotlin holds in a word compares by it, as a value class does; any + // other through Rust, passing both values' words, or both encoded. if let Some(opaque) = opaque.filter(|opaque| t.eq && !word(opaque)) { - self.native( - &format!("{bare}_eq"), - &[("jlongArray", "LongArray"), ("jlongArray", "LongArray")], - ("jboolean", "Boolean"), - &format!( - "crate::{c}_eq(&{}, &{})", - from_kotlin(&opaque, "p0"), - from_kotlin(&opaque, "p1") - ), - ); + let holders = holders(&opaque); + let (params, rust, kt) = match fits(2) { + true => { + let words: Vec = (0..2 * holders.len()).map(|k| format!("p{k}")).collect(); + let (a, b) = words.split_at(holders.len()); + let others: Vec = holders.iter().map(|h| format!("other.{h}")).collect(); + ( + vec![("jlong", "Long"); words.len()], + format!("crate::{c}_eq(&{}, &{})", from_kotlin(&opaque, a), from_kotlin(&opaque, b)), + format!("_Native.{bare}_eq({}, {})", holders.join(", "), others.join(", ")), + ) + } + false => { + let (this, other) = (self.write_value(ty, "w", "this"), self.write_value(ty, "w", "other")); + ( + vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], + "{ let b = rt::bytes(env, p0).unwrap_or_default(); let mut r = rt::Reader::new(env, &b, p1); crate::{c}_eq(&r.get(), &r.get()) }".replace("{c}", c), + format!("_Native.__Writer().use {{ w -> {this}; {other}; _Native.{bare}_eq(w.finish(), w.refs()) }}"), + ) + } + }; + self.native(&format!("{bare}_eq"), ¶ms, ("jboolean", "Boolean"), &rust); body.push(format!( - "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {class} && _Native.{bare}_eq(words, other.words)\n\n\t/** One for every value: Rust's `PartialEq` comes with no `Hash`. */\n\toverride fun hashCode(): kotlin.Int = 0\n" + "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {class} && {kt}\n\n\t/** One for every value: Rust's `PartialEq` comes with no `Hash`. */\n\toverride fun hashCode(): kotlin.Int = 0\n" )); } if object && t.eq { @@ -1418,7 +1431,7 @@ impl<'a> Gen<'a> { self.traits(&ty, &c, record.traits, &mut body, &mut statics); let mut members: Vec = fields.iter().map(|(f, _)| format!("val {f}")).collect(); if let Some(opaque) = record.opaque { - members.push(format!("val {}", holder(&opaque))); + members.extend(holders(&opaque).iter().map(|h| format!("val {h}"))); } let owner = Ty::Struct(c.clone()); for method in &record.methods { @@ -1522,22 +1535,19 @@ impl<'a> Gen<'a> { } /// An opaque value's class, `name` in Kotlin and `c` in C, and its codec: a value class - /// over the `Long` it fits in with no padding, or else a class over its words, which - /// compares through Rust's `PartialEq`. Only Rust makes one. + /// over the `Long` it fits in with no padding, or else a class of a `Long` for each of + /// its words, which compares through Rust's `PartialEq`, so one that does not escape + /// allocates nothing. Only Rust makes one. fn opaque(&mut self, c: &str, name: &str, opaque: &Opaque, docs: &str, body: &str) { let words = opaque.words(); - let (head, write, read) = match word(opaque) { - true => ( - format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), - "\tw.i64(v.bits)\n".to_string(), - format!("{name}(r.i64())"), - ), - false => ( - format!("class {name} internal constructor(internal val words: LongArray)"), - "\tfor (word in v.words) w.i64(word)\n".to_string(), - format!("{name}(LongArray({words}) {{ r.i64() }})"), - ), + let holders = holders(opaque); + let fields: Vec = holders.iter().map(|h| format!("@JvmField internal val {h}: Long")).collect(); + let head = match word(opaque) { + true => format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), + false => format!("class {name} internal constructor({})", fields.join(", ")), }; + let write: String = holders.iter().map(|h| format!("\tw.i64(v.{h})\n")).collect(); + let read = format!("{name}({})", vec!["r.i64()"; holders.len()].join(", ")); let _ = write!(self.types, "{docs}{head}{body}\n\n"); let _ = write!( self.top, @@ -1872,10 +1882,11 @@ impl<'a> Gen<'a> { Ty::Enum(_) => ("i", format!("p{k}")), Ty::Handle { .. } => ("j", format!("p{k} as usize as jlong")), Ty::Buf => ("l", format!("unsafe {{ rt::lent(env, p{k}) }}")), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) => match word(&opaque) { - true => ("j", to_kotlin(&opaque, &format!("p{k}"))), - false => ("l", to_kotlin(&opaque, &format!("p{k}"))), - }, + Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + ("j", to_kotlin(&opaque, &format!("p{k}"), 0)) + } _ => ( "l", format!("{{ let mut w = rt::Writer::default(); w.put(p{k}); w.array(env) }}"), @@ -1917,8 +1928,13 @@ impl<'a> Gen<'a> { Ty::Char => "ret as u32".to_string(), // A buffer Rust frees, as `buf_copy` makes one. Ty::Buf => "crate::rt::Buf::vec(rt::bytes(env, ret).unwrap_or_default())".to_string(), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, &c_ok) => from_kotlin(&opaque, "ret"), - // Encoded, as an option of an opaque value, which names no array or text to refer to. + Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, &c_ok) + && one_word(&opaque) => + { + from_kotlin(&opaque, &["ret".to_string()]) + } + // Encoded, as an option of an opaque value or one past a word, which names no + // array or text to refer to. Ty::Struct(_) => { "rt::Reader::new(env, &rt::bytes(env, ret).unwrap_or_default(), ::std::ptr::null_mut()).get()" .to_string() @@ -2119,7 +2135,7 @@ impl<'a> Gen<'a> { .iter() .any(|p| matches!(&p.ty, Type::Ref(..)) && p.ty.written()); self.room = room( - export.call.params.iter().map(|(_, c)| c_slots(abi, c)).sum(), + export.call.params.iter().map(|(_, c)| c_slots(c)).sum(), export.future.is_some(), written, ); @@ -2262,9 +2278,11 @@ impl<'a> Gen<'a> { let err = function.err.as_ref().map(strip_refs); let exception = err.as_ref().map(|e| self.exception(e)); // A record returned directly crosses as its scalars, set into slots the call takes, - // and its other fields encoded into the `byte[]` it returns. + // and its other fields encoded into the `byte[]` it returns; an opaque value as its + // words, unless it returns its one word itself. let flat = match (&export.future, outs.is_empty()) { - (None, true) if self.room > 0 => returned_record(&ok).filter(|(i, _)| abi.api.records[*i].opaque.is_none()), + (None, true) if self.room > 0 => returned_record(&ok) + .filter(|(i, option)| *option || !abi.api.records[*i].opaque.is_some_and(|o| one_word(&o))), _ => None, }; let flat = flat.map(|(i, option)| { @@ -2867,8 +2885,9 @@ impl<'a> Gen<'a> { } /// The glue's C value of the record `i` Kotlin passes as `e`: each scalar, nested - /// records' too, a JNI parameter `arg` gains, numbered from `n`, and each other field - /// read from `r`, which Kotlin writes into `w` with `writes`, in field order. + /// records' too, and each word of an opaque value, a JNI parameter `arg` gains, numbered + /// from `n`, and each other field read from `r`, which Kotlin writes into `w` with + /// `writes`, in field order. fn flat_in( &mut self, i: usize, @@ -2878,13 +2897,22 @@ impl<'a> Gen<'a> { r: &str, ) -> String { let abi = self.abi; + if let Some(opaque) = abi.api.records[i].opaque { + let mut words = Vec::new(); + for h in holders(&opaque) { + words.push(format!("p{n}")); + *n += 1; + arg.jni.push("jlong"); + arg.native.push("Long".to_string()); + arg.exprs.push(format!("{e}.{h}")); + } + return from_kotlin(&opaque, &words); + } let mut fields = Vec::new(); for (k, field) in abi.api.records[i].fields.iter().enumerate() { let e = format!("{e}.{}", field_name(&field.name)); let value = match &field.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => { - self.flat_in(*j, &e, (&mut *arg, &mut *n), (w, &mut *writes), r) - } + Type::Record(j) => self.flat_in(*j, &e, (&mut *arg, &mut *n), (w, &mut *writes), r), ty if scalar(abi, ty) => { let p = format!("p{n}"); *n += 1; @@ -2915,7 +2943,8 @@ impl<'a> Gen<'a> { } /// The Kotlin value of the record `i` Rust returned as the C value `v`: each scalar, - /// nested records' too, from the next of the slots `a` the glue sets with `slots`, and + /// nested records' too, and each word of an opaque value, from the next of the slots + /// `a` the glue sets with `slots`, and /// each other field from `r`, which the glue writes with `puts`, in field order. fn flat_out( &mut self, @@ -2925,13 +2954,22 @@ impl<'a> Gen<'a> { (r, puts): (&str, &mut Vec), ) -> String { let abi = self.abi; + let class = self.qualified(&abi.record(i)); + if let Some(opaque) = abi.api.records[i].opaque { + let words: Vec = (0..opaque.words()) + .map(|k| { + let slot = format!("{a}[{}]", slots.len()); + slots.push(to_kotlin(&opaque, v, k)); + slot + }) + .collect(); + return format!("{class}({})", words.join(", ")); + } let mut fields = Vec::new(); for (k, field) in abi.api.records[i].fields.iter().enumerate() { let v = format!("{v}.f{k}"); fields.push(match &field.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => { - self.flat_out(*j, &v, (a, &mut *slots), (r, &mut *puts)) - } + Type::Record(j) => self.flat_out(*j, &v, (a, &mut *slots), (r, &mut *puts)), ty if scalar(abi, ty) => { let slot = format!("{a}[{}]", slots.len()); let (rust, kt) = match ty { @@ -2966,7 +3004,7 @@ impl<'a> Gen<'a> { } }); } - format!("{}({})", self.qualified(&abi.record(i)), fields.join(", ")) + format!("{class}({})", fields.join(", ")) } } @@ -2979,20 +3017,27 @@ fn scalar(abi: &Abi<'_>, ty: &Type) -> bool { } } -/// Whether the record `i`, or one it nests, holds a field that crosses encoded. +/// Whether the record `i`, or one it nests, holds a field that crosses encoded: an opaque +/// value holds none. fn rest(abi: &Abi<'_>, i: usize) -> bool { + if abi.api.records[i].opaque.is_some() { + return false; + } abi.api.records[i].fields.iter().any(|f| match &f.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => rest(abi, *j), + Type::Record(j) => rest(abi, *j), ty => !scalar(abi, ty), }) } /// The JVM parameter slots the record `i` takes flattened: two for each `long` or `double` /// scalar, one for any other, and two for its other fields, if any: their `byte[]` and the -/// arrays and text they name. +/// arrays and text they name. An opaque value takes two for each word. fn weight(abi: &Abi<'_>, i: usize) -> usize { + if let Some(opaque) = abi.api.records[i].opaque { + return 2 * opaque.words() as usize; + } let fields = abi.api.records[i].fields.iter().map(|f| match &f.ty { - Type::Record(j) if abi.api.records[*j].opaque.is_none() => weight(abi, *j) - 2 * usize::from(rest(abi, *j)), + Type::Record(j) => weight(abi, *j) - 2 * usize::from(rest(abi, *j)), Type::F64 => 2, Type::Int(int) | Type::NonZero(int) if jni_int(*int) == "jlong" => 2, ty if scalar(abi, ty) => 1, @@ -3008,16 +3053,14 @@ fn room(unflattened: usize, future: bool, written: bool) -> usize { 255usize.saturating_sub(unflattened + usize::from(future) + usize::from(written)) } -/// The JVM parameter slots the C parameter `c` takes as a native method's at most: two for -/// a `long` or `double`, as an opaque value Kotlin holds in a word is, none for what never -/// crosses, five for bytes (what holds them, a `long` owner, and two `int`s; text takes -/// one), two for an encoded value's `byte[]` and the arrays and text it names (a callback -/// takes one), and one for anything else, such as an opaque value's `long[]`. -fn c_slots(abi: &Abi<'_>, c: &Ty) -> usize { +/// The JVM parameter slots the C parameter `c` takes as a native method's at most, before +/// a record or an opaque value is flattened: two for a `long` or `double`, none for what +/// never crosses, five for bytes (what holds them, a `long` owner, and two `int`s; text +/// takes one), two for an encoded value's `byte[]` and the arrays and text it names (a +/// callback takes one), and one for anything else. +fn c_slots(c: &Ty) -> usize { match c { Ty::Void | Ty::Out(_) | Ty::Data | Ty::Poll => 0, - Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some_and(|o| word(&o)) => 2, - Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some() => 1, Ty::Int(int) if jni_int(*int) == "jlong" => 2, Ty::F64 | Ty::Handle { .. } | Ty::Future(_) => 2, Ty::Buf => 5, @@ -3151,10 +3194,7 @@ fn abi_bound(abi: &Abi<'_>, int: Int) -> String { /// The JNI type and the Kotlin native type of the C type `c`, of IR type `ty`. fn jni_type(abi: &Abi<'_>, c: &Ty, ty: &Type) -> (&'static str, &'static str) { match c { - Ty::Struct(_) | Ty::In(_) if let Some(opaque) = opaque_of(abi, c) => match word(&opaque) { - true => ("jlong", "Long"), - false => ("jlongArray", "LongArray"), - }, + Ty::Struct(_) | Ty::In(_) if opaque_of(abi, c).is_some_and(|o| one_word(&o)) => ("jlong", "Long"), Ty::Void => ("()", "Unit"), Ty::Bool => ("jboolean", "Boolean"), Ty::Int(int) => match jni_int(*int) { @@ -3193,40 +3233,46 @@ fn opaque_of(abi: &Abi<'_>, c: &Ty) -> Option { .and_then(|i| abi.api.records[i].opaque) } -/// The property of an opaque value's class holding it. -fn holder(opaque: &Opaque) -> &'static str { +/// The properties of an opaque value's class holding it, a word each: a value class's +/// `bits`, or `w0` and on. +fn holders(opaque: &Opaque) -> Vec { match word(opaque) { - true => "bits", - false => "words", + true => vec!["bits".to_string()], + false => (0..opaque.words()).map(|k| format!("w{k}")).collect(), } } -/// Whether Kotlin holds `opaque` in a `Long`, with no allocation: it fits one and is -/// dense, so values Rust calls equal have equal bits, as the value class compares them. +/// Whether Kotlin holds `opaque` in a value class over a `Long`, with no allocation: it +/// fits one and is dense, so values Rust calls equal have equal bits, as the value class +/// compares them. fn word(opaque: &Opaque) -> bool { opaque.compared() } -/// The Rust expression taking the opaque value Kotlin passed as `p`, as its C struct. -fn from_kotlin(opaque: &Opaque, p: &str) -> String { - match word(opaque) { - true => format!("rt::from_word({p})"), - false => format!("unsafe {{ rt::from_words::<_, {}>(env, {p}) }}", opaque.words()), - } +/// Whether `opaque` crosses JNI as one `long` wherever it crosses alone. +fn one_word(opaque: &Opaque) -> bool { + opaque.words() == 1 } -/// The JNI value Kotlin takes the opaque value's C struct `e` as. -fn to_kotlin(opaque: &Opaque, e: &str) -> String { - match word(opaque) { - true => format!("rt::to_word({e})"), - false => format!("rt::to_words::<_, {}>(env, {e})", opaque.words()), - } +/// The Rust expression taking the opaque value Kotlin passed as the `long`s `words`, as +/// its C struct. +fn from_kotlin(opaque: &Opaque, words: &[String]) -> String { + format!("rt::from_words::<_, {}>([{}])", opaque.words(), words.join(", ")) +} + +/// The JNI `long` word `k` of the opaque value's C struct `e`, as Kotlin holds it. +fn to_kotlin(opaque: &Opaque, e: &str, k: u64) -> String { + format!("rt::to_words::<_, {}>({e})[{k}]", opaque.words()) } /// The Rust expression returning to Kotlin a value `ret` of type `ok` that C returns as `c`. fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { match c { - Ty::Struct(_) if let Some(opaque) = opaque_of(abi, c) => to_kotlin(&opaque, "ret"), + Ty::Struct(_) if let Some(opaque) = opaque_of(abi, c) + && one_word(&opaque) => + { + to_kotlin(&opaque, "ret", 0) + } Ty::Void | Ty::Bool | Ty::F32 | Ty::F64 | Ty::Enum(_) => "ret".to_string(), Ty::Int(int) => format!("ret as {}", jni_int(*int)), Ty::Char => "ret as jint".to_string(), diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 22150ebbc..3818b9f7b 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -282,6 +282,14 @@ fun script() { val shifted = shifted(moment) { m -> m.after(500u) } println("shifted ${shifted.millis()} ${shifted == moment.after(500u)}") println("wrapped ${moment.after(ULong.MAX_VALUE).millis()} ${moment == shifted}") + // A record holding one crosses as its words, in and out, and a call with no slots + // left for one passes it encoded. + val clocked = clockedAfter(Clocked(moment, 1u), 500u) + check(clocked == Clocked(moment.after(500u), 2u) && clocked.at.millis() == 2000uL, "a record's moment crosses as its words") + check(crammed(moment, shifted, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL) == 1500uL + 2000uL + 124uL, "a crammed call passes its last moment encoded") + // One of 64 words is passed as its words, but compared encoded. + val broad = Wide.new(ULong.MAX_VALUE) + check(broad.sum() == 2016uL - 64uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") // A padded value crosses with its padding zeroed, and one whose bytes vary is a handle. val gap = Gap.new(7u, 3u) From 4e9891016a7cadf53b403873988fb57a4970e537 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:18:39 -0800 Subject: [PATCH 3/9] style(ffi): rustfmt Co-Authored-By: Claude Opus 5.5 --- ffi/src/kotlin.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 5154374c6..8278e9a07 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -864,7 +864,9 @@ impl<'a> Gen<'a> { _ => wrap(e), } } - Ty::Struct(name) if opaque_of(self.abi, c).is_some_and(|o| one_word(&o)) => format!("{}({e})", self.qualified(name)), + Ty::Struct(name) if opaque_of(self.abi, c).is_some_and(|o| one_word(&o)) => { + format!("{}({e})", self.qualified(name)) + } Ty::Buf => match (decode(ty), matches!(ty.base(), Type::Option(_)), lent) { (Some(decode), true, _) => format!("{e}?.{decode}"), (Some(decode), false, _) => format!("{e}!!.{decode}"), @@ -888,8 +890,9 @@ impl<'a> Gen<'a> { match c { Ty::Int(int) => to_signed(*int, e), Ty::Buf => format!("{e}.encodeToByteArray()"), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) - && one_word(&opaque) => + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => { format!("{e}.{}", holders(&opaque)[0]) } @@ -1356,7 +1359,11 @@ impl<'a> Gen<'a> { let others: Vec = holders.iter().map(|h| format!("other.{h}")).collect(); ( vec![("jlong", "Long"); words.len()], - format!("crate::{c}_eq(&{}, &{})", from_kotlin(&opaque, a), from_kotlin(&opaque, b)), + format!( + "crate::{c}_eq(&{}, &{})", + from_kotlin(&opaque, a), + from_kotlin(&opaque, b) + ), format!("_Native.{bare}_eq({}, {})", holders.join(", "), others.join(", ")), ) } @@ -1541,7 +1548,10 @@ impl<'a> Gen<'a> { fn opaque(&mut self, c: &str, name: &str, opaque: &Opaque, docs: &str, body: &str) { let words = opaque.words(); let holders = holders(opaque); - let fields: Vec = holders.iter().map(|h| format!("@JvmField internal val {h}: Long")).collect(); + let fields: Vec = holders + .iter() + .map(|h| format!("@JvmField internal val {h}: Long")) + .collect(); let head = match word(opaque) { true => format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), false => format!("class {name} internal constructor({})", fields.join(", ")), @@ -1882,8 +1892,9 @@ impl<'a> Gen<'a> { Ty::Enum(_) => ("i", format!("p{k}")), Ty::Handle { .. } => ("j", format!("p{k} as usize as jlong")), Ty::Buf => ("l", format!("unsafe {{ rt::lent(env, p{k}) }}")), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, c) - && one_word(&opaque) => + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => { ("j", to_kotlin(&opaque, &format!("p{k}"), 0)) } @@ -1928,8 +1939,9 @@ impl<'a> Gen<'a> { Ty::Char => "ret as u32".to_string(), // A buffer Rust frees, as `buf_copy` makes one. Ty::Buf => "crate::rt::Buf::vec(rt::bytes(env, ret).unwrap_or_default())".to_string(), - Ty::Struct(_) if let Some(opaque) = opaque_of(self.abi, &c_ok) - && one_word(&opaque) => + Ty::Struct(_) + if let Some(opaque) = opaque_of(self.abi, &c_ok) + && one_word(&opaque) => { from_kotlin(&opaque, &["ret".to_string()]) } @@ -3268,8 +3280,9 @@ fn to_kotlin(opaque: &Opaque, e: &str, k: u64) -> String { /// The Rust expression returning to Kotlin a value `ret` of type `ok` that C returns as `c`. fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { match c { - Ty::Struct(_) if let Some(opaque) = opaque_of(abi, c) - && one_word(&opaque) => + Ty::Struct(_) + if let Some(opaque) = opaque_of(abi, c) + && one_word(&opaque) => { to_kotlin(&opaque, "ret", 0) } From 2ec35316116e01c677fe60a5d883b32a4f775ce2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:42:44 -0800 Subject: [PATCH 4/9] feat(ffi): a Kotlin result of a value returns it directly Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 13 +++++++++ ffi/src/kotlin.rs | 54 +++++++++++++++++++++++++++++-------- ffi/tests/api.kt | 3 +++ 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 9711519c6..744dad4f1 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1226,6 +1226,19 @@ impl Moment { } } +/// `ticks` of `rate` a second, failing at a rate of zero: a value past a word in a `Result`. +pub fn moment_at(ticks: u64, rate: u64) -> Result { + Moment::new(ticks, rate).ok_or_else(|| "a rate of zero".to_string()) +} + +/// The stamp `millis` from zero, failing at zero: a value of a word in a `Result`. +pub fn stamp_at(millis: u64) -> Result { + match millis { + 0 => Err("zero".to_string()), + millis => Ok(Stamp::from_millis(millis)), + } +} + /// The moment `shift` returns for `moment`, which C copies in and out. pub fn shifted(moment: Moment, shift: impl Fn(Moment) -> Moment) -> Moment { shift(moment) diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 8278e9a07..51a1b58e9 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -2486,12 +2486,25 @@ impl<'a> Gen<'a> { self.refused_first(&bare, format!("try {{ {raw} }} finally {{ {} }}", after.join("; "))) }; value = format!("({raw}) as {ok_kt}"); - } else if let Some(c_ok) = direct(&outs, &written, &function.ok, function.err.as_ref()) { - // A result of a scalar, a handle, or nothing returns its value directly, raising - // its error as a `_Native.__Failed` Kotlin catches. + } else if let Some(c_ok) = direct(abi, &outs, &written, &function.ok, function.err.as_ref()) + .filter(|c| self.room > 0 || opaque_of(abi, c).is_none_or(|o| one_word(&o))) + { + // A result of a scalar, a handle, an opaque value, or nothing returns its value + // directly, raising its error as a `_Native.__Failed` Kotlin catches; an opaque + // value past a word sets its words into this thread's slots. let err_ty = function.err.as_ref().expect("a direct return is a result's"); - let (jni, native) = jni_type(abi, &c_ok, &ok); - let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); + let words = opaque_of(abi, &c_ok).filter(|o| !one_word(o)); + let (jni, native) = match words { + Some(_) => ("()", "Unit"), + None => jni_type(abi, &c_ok, &ok), + }; + let mut params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); + let a = self.fresh("a"); + if let Some(opaque) = &words { + params.push(("jlongArray", "kotlin.LongArray")); + exprs.push(a.clone()); + self.slots = self.slots.max(opaque.words() as usize); + } let mut ptrs = Vec::new(); let mut decl = Vec::new(); for (name, _) in &outs { @@ -2499,8 +2512,13 @@ impl<'a> Gen<'a> { ptrs.push(format!("o_{name}.as_mut_ptr()")); } let ok_name = &outs[0].0; - let ret = match c_ok { - Ty::Void => String::new(), + let ret = match (&c_ok, &words) { + (Ty::Void, _) => String::new(), + (_, Some(opaque)) => format!( + "let ret = o_{ok_name}.assume_init();\n\t\trt::slots(env, p{}, &rt::to_words::<_, {}>(ret));", + params.len() - 1, + opaque.words() + ), _ => format!( "let ret = o_{ok_name}.assume_init();\n\t\t{}", ret_expr(abi, &c_ok, &ok) @@ -2534,8 +2552,20 @@ impl<'a> Gen<'a> { .replace("try {\n\t", "try {\n\ttry {\n\t\t") .replacen("\n} finally", &format!("\n\t}} catch (f: _Native.__Failed) {{\n\t\t_Native.__Reader(f.error).let {{ {r} -> throw {exception}({e}) }}\n\t}}\n}} finally"), 1)), }; - value = match ok { - Type::Unit => caught, + value = match (&ok, &words) { + (Type::Unit, _) => caught, + (_, Some(opaque)) => { + let made: Vec = (0..opaque.words()).map(|k| format!("{a}[{k}]")).collect(); + format!( + "_Native.__slots.get()!!.let {{ {a} ->\n{}\n\t{}({})\n}}", + indent_by(&caught, 1), + match &c_ok { + Ty::Struct(name) => self.qualified(name), + _ => unreachable!("an opaque value is a struct"), + }, + made.join(", ") + ) + } _ => self.lift(&ok, &c_ok, &format!("({caught})"), false), }; } else if !outs.is_empty() { @@ -3301,8 +3331,9 @@ fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { } /// The C type of the value a call returns directly, raising its error, if it returns a -/// result of a scalar, a handle, or nothing and writes back no argument: `Void` for nothing. -fn direct(outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Option<&Type>) -> Option { +/// result of a scalar, a handle, an opaque value, or nothing and writes back no argument: +/// `Void` for nothing. +fn direct(abi: &Abi<'_>, outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Option<&Type>) -> Option { if err.is_none() || !written.is_empty() { return None; } @@ -3312,6 +3343,7 @@ fn direct(outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Opt Ty::Bool | Ty::Int(_) | Ty::F32 | Ty::F64 | Ty::Char | Ty::Enum(_) | Ty::Handle { .. } => { Some((**c).clone()) } + Ty::Struct(_) if opaque_of(abi, c).is_some() => Some((**c).clone()), _ => None, }, _ => None, diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 3818b9f7b..60bc9428d 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -287,6 +287,9 @@ fun script() { val clocked = clockedAfter(Clocked(moment, 1u), 500u) check(clocked == Clocked(moment.after(500u), 2u) && clocked.at.millis() == 2000uL, "a record's moment crosses as its words") check(crammed(moment, shifted, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL) == 1500uL + 2000uL + 124uL, "a crammed call passes its last moment encoded") + // A `Result` of one returns it directly, or throws. + check(momentAt(1500u, 1000u) == moment && stampAt(5u) == Stamp.fromMillis(5u), "a result's value returns directly") + check(runCatching { momentAt(1u, 0u) }.isFailure && runCatching { stampAt(0u) }.isFailure, "a result's error throws") // One of 64 words is passed as its words, but compared encoded. val broad = Wide.new(ULong.MAX_VALUE) check(broad.sum() == 2016uL - 64uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") From 5f31c4cd2552fc669f18193075bc5de583660815 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:57:43 -0800 Subject: [PATCH 5/9] docs(ffi): Kotlin values measured; options passed flat as a follow-up Co-Authored-By: Claude Opus 5.5 --- bench/ffi/README.md | 13 ++++++++++--- quest/m1/ffi-speed/kotlin-options.md | 19 +++++++++++++++++++ quest/m1/ffi-speed/kotlin-values.md | 19 ------------------- 3 files changed, 29 insertions(+), 22 deletions(-) create mode 100644 quest/m1/ffi-speed/kotlin-options.md delete mode 100644 quest/m1/ffi-speed/kotlin-values.md diff --git a/bench/ffi/README.md b/bench/ffi/README.md index 7a0fce907..fb22a15c9 100644 --- a/bench/ffi/README.md +++ b/bench/ffi/README.md @@ -417,7 +417,7 @@ same amount; measure both, CPU first, at the load beside them. ### Copy values A `Copy` type with private fields, such as `Timestamp`, crosses by value: a struct of its -bytes in C, C++, Swift, Go, and Dart, a class over a `LongArray` in Kotlin (a word value +bytes in C, C++, Swift, Go, and Dart, a class of a `Long` per word in Kotlin (a word value class when it fits one), and a class of the runtime's `Value` holding its bytes in Python. Measured 2026-11-13 at rust2 `7766768f`, moq `ffcb7cd9`, on an AMD Ryzen 9 9950X (32 threads), Linux, at a load average of 13 to 15, the median of 3 rounds, in CPU time: @@ -429,8 +429,15 @@ Linux, at a load average of 13 to 15, the median of 3 rounds, in CPU time: | stamped minus write | 0 | 3 | 1 | 33 | 45 | 150 (35 wall) | 160 | C, C++, and Swift pay nothing for the timestamp; Go and Dart pay about their getter's call, -the `from_micros` itself. Kotlin's 35 ns wall is its call, and its CPU column adds the -collector's work on each `LongArray`. Python's is a call and a new object. The handle's cost +the `from_micros` itself. Kotlin's 35 ns wall was its call, and its CPU column adds the +collector's work on each `LongArray`. Since its value is a class of a `Long` per word, and a +`Result` of one returns its words through the thread's slots rather than encoded, the +stamped write costs Kotlin 30 ns of wall time over the write, against 270 on main's build: +measured 2026-11-14 at rust2 `2ec35316`, moq `ffcb7cd9`, on the same host, interleaved over 7 +rounds at a load average of 6 to 17, the medians of each round's difference. Its CPU time, +which counts the JIT's and collector's threads, ranged from 30 to 300 ns at that load. +The thread allocates 32 B a stamped frame over the write, the `Timestamp` itself, which +`write_frame` keeps from the JIT's escape analysis, against 112 on main's. Python's is a call and a new object. The handle's cost in the tables above came from another load, so Python's was also measured against main's build on the same host, interleaved over 5 rounds at a load of 10 to 12: stamped minus write fell from 205 ns to 166, and the stamped write from 441 to 391. diff --git a/quest/m1/ffi-speed/kotlin-options.md b/quest/m1/ffi-speed/kotlin-options.md new file mode 100644 index 000000000..2177ceb16 --- /dev/null +++ b/quest/m1/ffi-speed/kotlin-options.md @@ -0,0 +1,19 @@ +# [S] Kotlin options passed flat + +## Goal + +A [rust2-ffi](/ffi/README.md) Kotlin binding passes an `Option` of a record or an opaque +value as its JNI scalars, a `bool` and the value's own, as it passes one bare, instead of +encoded into a `byte[]`. moq's `group::Producer::write_frame` takes an `Option`, +so [the binding benchmark](/bench/ffi/README.md)'s write allocates 208 B a call in Kotlin +(the thread's allocated bytes over the case, measured 2026-11-14), a writer and its array +among them, and costs 220 ns against C's 163. The write then allocates no more than its +frame's bytes take. + +## Plan + +- Generalize `flat_in` in `ffi/src/kotlin.rs` to an `Option` of a record or an opaque value, + as `flat_out` already returns one: a `jboolean`, then the value's scalars, zero for `None`, + within the 255 JVM slots a method takes, and encoded past them. +- Measure the write's wall time, CPU time, and allocated bytes against main's, interleaved. + diff --git a/quest/m1/ffi-speed/kotlin-values.md b/quest/m1/ffi-speed/kotlin-values.md deleted file mode 100644 index 036c0590d..000000000 --- a/quest/m1/ffi-speed/kotlin-values.md +++ /dev/null @@ -1,19 +0,0 @@ -# [S] Kotlin values without a LongArray - -## Goal - -A [rust2-ffi](/ffi/README.md) Kotlin binding holds a `Copy` value over 8 bytes, such as -moq's 16-byte `Timestamp`, in one object with no array beside it. Today it is a class -over a `LongArray`, two allocations per value, so -[the binding benchmark](/bench/ffi/README.md)'s stamped write costs 150 ns of CPU more -than the plain write in Kotlin (35 wall), against Swift's 1. The stamped write then costs -within its `from_micros` call of the plain write, as Go's and Dart's do. - -## Plan - -- One `Long` field per 8-byte word in the value's class, passed to and from JNI as that - many `jlong` arguments and a returned struct's words written into the class's fields, - so HotSpot's escape analysis can drop a value that does not escape. -- `equals` and `hashCode` keep today's rules, so only the storage changes. -- Re-measure the stamped write, CPU and wall, on HotSpot and on ART in the nightly - emulator job. From afd915db27a50e050fc0972f7c4d9a10a0b5c626 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:01:52 -0800 Subject: [PATCH 6/9] style(ffi): rustfmt Co-Authored-By: Claude Opus 5.5 --- ffi/src/kotlin.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 51a1b58e9..0e2901661 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -3333,7 +3333,13 @@ fn ret_expr(abi: &Abi<'_>, c: &Ty, ok: &Type) -> String { /// The C type of the value a call returns directly, raising its error, if it returns a /// result of a scalar, a handle, an opaque value, or nothing and writes back no argument: /// `Void` for nothing. -fn direct(abi: &Abi<'_>, outs: &[(String, Ty)], written: &[(String, Type)], ok: &Type, err: Option<&Type>) -> Option { +fn direct( + abi: &Abi<'_>, + outs: &[(String, Ty)], + written: &[(String, Type)], + ok: &Type, + err: Option<&Type>, +) -> Option { if err.is_none() || !written.is_empty() { return None; } From cfa46aa5d1fe213e751e9d14d82eb6dc7ebe8bcc Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:13:47 -0800 Subject: [PATCH 7/9] fix(ffi): a Kotlin value past 127 words makes with no constructor of a parameter each Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 6 ++-- ffi/src/kotlin.rs | 64 +++++++++++++++++++++++++++---------- ffi/tests/api.kt | 4 +-- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 744dad4f1..60bbf5b0c 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1283,11 +1283,11 @@ impl LongArray { } } -/// A value of 64 words: Kotlin passes one as its words, but two, as its `==` takes, past a -/// JVM method's 255 slots, so encoded. +/// A value of 128 words, past what a JVM method's 255 slots hold as `long`s: Kotlin makes +/// one with no constructor of a parameter each, and passes one encoded. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Wide { - words: [u64; 64], + words: [u64; 128], } impl Wide { diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 0e2901661..2a961c1f7 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -864,8 +864,12 @@ impl<'a> Gen<'a> { _ => wrap(e), } } - Ty::Struct(name) if opaque_of(self.abi, c).is_some_and(|o| one_word(&o)) => { - format!("{}({e})", self.qualified(name)) + Ty::Struct(name) + if let Some(opaque) = opaque_of(self.abi, c) + && one_word(&opaque) => + { + let class = self.qualified(name); + self.made(&class, &opaque, &[e.to_string()]) } Ty::Buf => match (decode(ty), matches!(ty.base(), Type::Option(_)), lent) { (Some(decode), true, _) => format!("{e}?.{decode}"), @@ -1548,16 +1552,27 @@ impl<'a> Gen<'a> { fn opaque(&mut self, c: &str, name: &str, opaque: &Opaque, docs: &str, body: &str) { let words = opaque.words(); let holders = holders(opaque); - let fields: Vec = holders + // Set after a constructor of none, as a constructor of a parameter each would pass + // the 255 JVM slots a method takes past 127 words. + let fields: String = holders .iter() - .map(|h| format!("@JvmField internal val {h}: Long")) + .map(|h| format!("\t@JvmField internal var {h}: Long = 0L\n")) .collect(); - let head = match word(opaque) { - true => format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), - false => format!("class {name} internal constructor({})", fields.join(", ")), + let (head, body) = match word(opaque) { + true => ( + format!("@kotlin.jvm.JvmInline\nvalue class {name} internal constructor(internal val bits: Long)"), + body.to_string(), + ), + false => ( + format!("class {name} internal constructor()"), + match body.is_empty() { + true => format!(" {{\n{fields}}}"), + false => body.replacen(" {\n", &format!(" {{\n{fields}\n"), 1), + }, + ), }; let write: String = holders.iter().map(|h| format!("\tw.i64(v.{h})\n")).collect(); - let read = format!("{name}({})", vec!["r.i64()"; holders.len()].join(", ")); + let read = self.made(name, opaque, &vec!["r.i64()".to_string(); holders.len()]); let _ = write!(self.types, "{docs}{head}{body}\n\n"); let _ = write!( self.top, @@ -1569,6 +1584,21 @@ impl<'a> Gen<'a> { ); } + /// The Kotlin expression making the opaque value of class `class` from the `Long` + /// expressions `words`, evaluated in order. + fn made(&mut self, class: &str, opaque: &Opaque, words: &[String]) -> String { + if word(opaque) { + return format!("{class}({})", words[0]); + } + let v = self.fresh("v"); + let sets: Vec = holders(opaque) + .iter() + .zip(words) + .map(|(h, w)| format!("{v}.{h} = {w}")) + .collect(); + format!("{class}().also {{ {v} -> {} }}", sets.join("; ")) + } + fn enumeration(&mut self, i: usize) { let abi = self.abi; let e = &abi.api.enums[i]; @@ -2555,15 +2585,15 @@ impl<'a> Gen<'a> { value = match (&ok, &words) { (Type::Unit, _) => caught, (_, Some(opaque)) => { - let made: Vec = (0..opaque.words()).map(|k| format!("{a}[{k}]")).collect(); + let words: Vec = (0..opaque.words()).map(|k| format!("{a}[{k}]")).collect(); + let class = match &c_ok { + Ty::Struct(name) => self.qualified(name), + _ => unreachable!("an opaque value is a struct"), + }; + let made = self.made(&class, opaque, &words); format!( - "_Native.__slots.get()!!.let {{ {a} ->\n{}\n\t{}({})\n}}", - indent_by(&caught, 1), - match &c_ok { - Ty::Struct(name) => self.qualified(name), - _ => unreachable!("an opaque value is a struct"), - }, - made.join(", ") + "_Native.__slots.get()!!.let {{ {a} ->\n{}\n\t{made}\n}}", + indent_by(&caught, 1) ) } _ => self.lift(&ok, &c_ok, &format!("({caught})"), false), @@ -3005,7 +3035,7 @@ impl<'a> Gen<'a> { slot }) .collect(); - return format!("{class}({})", words.join(", ")); + return self.made(&class, &opaque, &words); } let mut fields = Vec::new(); for (k, field) in abi.api.records[i].fields.iter().enumerate() { diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 60bc9428d..508557d8e 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -290,9 +290,9 @@ fun script() { // A `Result` of one returns it directly, or throws. check(momentAt(1500u, 1000u) == moment && stampAt(5u) == Stamp.fromMillis(5u), "a result's value returns directly") check(runCatching { momentAt(1u, 0u) }.isFailure && runCatching { stampAt(0u) }.isFailure, "a result's error throws") - // One of 64 words is passed as its words, but compared encoded. + // One of 128 words is made with no constructor of a parameter each, and passed encoded. val broad = Wide.new(ULong.MAX_VALUE) - check(broad.sum() == 2016uL - 64uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") + check(broad.sum() == 8001uL - 1uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") // A padded value crosses with its padding zeroed, and one whose bytes vary is a handle. val gap = Gap.new(7u, 3u) From 083bc8900e7fb73ab28897bda6cd4934a12b593c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:20:16 -0800 Subject: [PATCH 8/9] fix(ffi): Kotlin's generated code names no annotation or `also` an export can shadow An exported type named `JvmField` or `JvmStatic` shadowed the unqualified annotations, and an opaque type's member `also` won over the extension that sets a wide value's words. Qualify every annotation and make wide values through an `_also` alias. Record the maintainer's keep of the kotlin-options follow-up. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 27 ++++++++++++++++-- ffi/runtime/rt.kt | 6 ++-- ffi/src/kotlin.rs | 41 ++++++++++++++++------------ quest/m1/ffi-speed/kotlin-options.md | 1 + 4 files changed, 52 insertions(+), 23 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 60bbf5b0c..cc3bf26ff 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1266,8 +1266,9 @@ impl Gap { } } -/// A value named as Kotlin's `LongArray`, which holds a returned value's words, with a method named -/// as C++'s member holding its bytes: each generator keeps its own apart. +/// A value named as Kotlin's `LongArray`, which holds a returned value's words, with methods named +/// as C++'s member holding its bytes and Kotlin's `also`, which makes a value past a word: each +/// generator keeps its own apart. #[derive(Clone, Copy, Debug, PartialEq)] pub struct LongArray { words: [u64; 2], @@ -1281,6 +1282,28 @@ impl LongArray { pub fn c_(&self) -> u64 { self.words[0].wrapping_add(self.words[1]) } + + /// Calls `f` with its low word. + pub fn also(&self, f: impl Fn(u64)) { + f(self.words[0]) + } +} + +/// A type named as the annotation Kotlin's fields take, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JvmField { + pub n: u32, +} + +/// A type named as the annotation Kotlin's static methods take, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JvmStatic { + pub n: u32, +} + +/// The sum of a `JvmField` and a `JvmStatic`. +pub fn jvm_sum(field: JvmField, method: JvmStatic) -> u32 { + field.n.wrapping_add(method.n) } /// A value of 128 words, past what a JVM method's 255 slots hold as `long`s: Kotlin makes diff --git a/ffi/runtime/rt.kt b/ffi/runtime/rt.kt index 21b9751b3..e04a8f82c 100644 --- a/ffi/runtime/rt.kt +++ b/ffi/runtime/rt.kt @@ -375,7 +375,7 @@ abstract class __Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owne val QUEUE = java.lang.ref.ReferenceQueue() /** One lock and list of the tracked. */ class Stripe { - @JvmField var head: __Cleanup? = null + @kotlin.jvm.JvmField var head: __Cleanup? = null } // A power of two, past the cores a phone or most servers have. @@ -400,7 +400,7 @@ class __Handle(owner: Any, internal val raw: Long, private val free: __Drop?, pr __Cleanup(if (free == null) null else owner) { // The holds, one for the owner until closed and one per call, shifted past a bit set // once closed: one word, so a handle allocates nothing beside itself. - @Volatile @JvmField internal var state = HELD + @kotlin.concurrent.Volatile @kotlin.jvm.JvmField internal var state = HELD init { if (free != null) track() @@ -524,7 +524,7 @@ class __Signal : java.util.concurrent.atomic.AtomicReference(null), Waker override fun wake() { val parked = getAndSet(WOKEN) if (parked !is kotlinx.coroutines.CancellableContinuation<*>) return - @Suppress("UNCHECKED_CAST") + @kotlin.Suppress("UNCHECKED_CAST") val c = parked as kotlinx.coroutines.CancellableContinuation // Never resumed in place, since the next poll would run inside Rust's wake, which may // hold a lock that poll takes: a dispatcher that would resume here is made to defer, diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 2a961c1f7..f97840ac0 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -88,8 +88,8 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result 0 { let _ = write!( helpers, - "\t/** This thread's slots a returned record's scalars cross in, read before its next call. */\n\t// A field, not a function, so no exported function's name can clash with it.\n\t@JvmField val __slots = object : java.lang.ThreadLocal() {{\n\t\t// Not `withInitial`, which Android lacks before API 26.\n\t\toverride fun initialValue() = kotlin.LongArray({n})\n\t}}\n\n", + "\t/** This thread's slots a returned record's scalars cross in, read before its next call. */\n\t// A field, not a function, so no exported function's name can clash with it.\n\t@kotlin.jvm.JvmField val __slots = object : java.lang.ThreadLocal() {{\n\t\t// Not `withInitial`, which Android lacks before API 26.\n\t\toverride fun initialValue() = kotlin.LongArray({n})\n\t}}\n\n", n = g.slots ); } @@ -131,13 +131,13 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result Gen<'a> { // the 255 JVM slots a method takes past 127 words. let fields: String = holders .iter() - .map(|h| format!("\t@JvmField internal var {h}: Long = 0L\n")) + .map(|h| format!("\t@kotlin.jvm.JvmField internal var {h}: Long = 0L\n")) .collect(); let (head, body) = match word(opaque) { true => ( @@ -1596,7 +1599,9 @@ impl<'a> Gen<'a> { .zip(words) .map(|(h, w)| format!("{v}.{h} = {w}")) .collect(); - format!("{class}().also {{ {v} -> {} }}", sets.join("; ")) + // Through the alias, which no exported member's name takes, as a member `also` would + // win over the extension. + format!("{class}()._also {{ {v} -> {} }}", sets.join("; ")) } fn enumeration(&mut self, i: usize) { @@ -2021,7 +2026,7 @@ impl<'a> Gen<'a> { // A closure's function type is erased, so the cast cannot check it. let cast_line = match method { Some(_) => format!("\t\tval o = o as {cast}\n"), - None => format!("\t\t@Suppress(\"UNCHECKED_CAST\")\n\t\tval o = o as {cast}\n"), + None => format!("\t\t@kotlin.Suppress(\"UNCHECKED_CAST\")\n\t\tval o = o as {cast}\n"), }; let body = match finally.is_empty() { true => format!("{cast_line}\t\treturn {lowered}"), @@ -2037,7 +2042,7 @@ impl<'a> Gen<'a> { }; let _ = write!( self.natives, - "\t@JvmStatic private fun {dispatcher}({}){ret_decl} {{\n{body}\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic private fun {dispatcher}({}){ret_decl} {{\n{body}\n\t}}\n\n", kt_params.join(", ") ); } @@ -2074,7 +2079,7 @@ impl<'a> Gen<'a> { let args: Vec = (0..params.len()).map(|n| format!("p{n}")).collect(); let _ = write!( self.natives, - "\t@JvmStatic fun {bare}({}): {} {{\n\t\tcheck({}uL, \"{}_{bare}\")\n\t\treturn {external}({})\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic fun {bare}({}): {} {{\n\t\tcheck({}uL, \"{}_{bare}\")\n\t\treturn {external}({})\n\t}}\n\n", kt.join(", "), ret.1, self.on.0 & api.all().0, @@ -2087,7 +2092,7 @@ impl<'a> Gen<'a> { let bare = external.as_str(); let _ = write!( self.natives, - "\t@JvmStatic external fun {bare}({}): {}\n\n", + "\t@kotlin.jvm.JvmStatic external fun {bare}({}): {}\n\n", kt.join(", "), ret.1 ); @@ -2402,7 +2407,7 @@ impl<'a> Gen<'a> { }; let _ = write!( self.natives, - "\t@Suppress(\"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\t{pending}\n{}\t\treturn __Ready({last})\n\t}}\n\n", + "\t@kotlin.Suppress(\"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\t{pending}\n{}\t\treturn __Ready({last})\n\t}}\n\n", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); } @@ -2488,7 +2493,7 @@ impl<'a> Gen<'a> { let make = self.tuple_class(elements); let _ = write!( self.natives, - "\t@JvmStatic private fun {factory}({}): Any {{\n\t\t{failure}\n\t\treturn {make}({})\n\t}}\n\n", + "\t@kotlin.jvm.JvmStatic private fun {factory}({}): Any {{\n\t\t{failure}\n\t\treturn {make}({})\n\t}}\n\n", fields.join(", "), lifted.join(", ") ); @@ -2627,7 +2632,7 @@ impl<'a> Gen<'a> { } let _ = write!( self.natives, - "\t@Suppress(\"UNCHECKED_CAST\", \"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n{}\t}}\n\n", + "\t@kotlin.Suppress(\"UNCHECKED_CAST\", \"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n{}\t}}\n\n", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); let mut params = params; @@ -2727,7 +2732,7 @@ impl<'a> Gen<'a> { let read = self.read_value(&ok, "r"); let _ = write!( self.natives, - "\t@Suppress(\"UNUSED_PARAMETER\")\n\t@JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\treturn {read}\n\t}}\n\n" + "\t@kotlin.Suppress(\"UNUSED_PARAMETER\")\n\t@kotlin.jvm.JvmStatic private fun {factory}(buffer: java.nio.ByteBuffer, back: kotlin.Array?): Any? {{\n\t\tval r = __Reader(buffer)\n\t\treturn {read}\n\t}}\n\n" ); let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); self.native(&bare, ¶ms, ("jobject", "Any?"), &format!( diff --git a/quest/m1/ffi-speed/kotlin-options.md b/quest/m1/ffi-speed/kotlin-options.md index 2177ceb16..531d0cf94 100644 --- a/quest/m1/ffi-speed/kotlin-options.md +++ b/quest/m1/ffi-speed/kotlin-options.md @@ -15,5 +15,6 @@ frame's bytes take. - Generalize `flat_in` in `ffi/src/kotlin.rs` to an `Option` of a record or an opaque value, as `flat_out` already returns one: a `jboolean`, then the value's scalars, zero for `None`, within the 255 JVM slots a method takes, and encoded past them. +- Kept by the maintainer on 2026-11-14 ([decision](https://github.com/kixel-ai/rust2/pull/820#issuecomment-6886625138)). - Measure the write's wall time, CPU time, and allocated bytes against main's, interleaved. From 3d2765f242df49e52e0344202350113254903b29 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:41:51 -0800 Subject: [PATCH 9/9] fix(ffi): qualify the runtime's last `@OptIn` An exported type named `OptIn` shadowed it, as Pullfrog found. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 12 +++++++++--- ffi/runtime/rt.kt | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index d463dd69a..f567b3bee 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -1295,9 +1295,15 @@ pub struct JvmStatic { pub n: u32, } -/// The sum of a `JvmField` and a `JvmStatic`. -pub fn jvm_sum(field: JvmField, method: JvmStatic) -> u32 { - field.n.wrapping_add(method.n) +/// A type named as the annotation Kotlin opts in to an API with, which the binding qualifies. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OptIn { + pub n: u32, +} + +/// The sum of a `JvmField`, a `JvmStatic`, and an `OptIn`. +pub fn jvm_sum(field: JvmField, method: JvmStatic, opt: OptIn) -> u32 { + field.n.wrapping_add(method.n).wrapping_add(opt.n) } /// A value of 128 words, past what a JVM method's 255 slots hold as `long`s: Kotlin makes diff --git a/ffi/runtime/rt.kt b/ffi/runtime/rt.kt index e04a8f82c..2c695527e 100644 --- a/ffi/runtime/rt.kt +++ b/ffi/runtime/rt.kt @@ -575,7 +575,7 @@ class __Pollable( // The caller's job reaches it as it starts cancelling, not once its children finish, // which only the internal overload of invokeOnCompletion tells. - @OptIn(kotlinx.coroutines.InternalCoroutinesApi::class) + @kotlin.OptIn(kotlinx.coroutines.InternalCoroutinesApi::class) fun poll(given: Long): Boolean { val old: Long synchronized(this) {