diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 119a8842b..7f052287e 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -3456,3 +3456,23 @@ pub struct Qualifiers { pub api: f64, pub kotlin: f64, } + +/// An object named as a class of Kotlin's runtime once was, which keeps its name now the +/// runtime's take a leading `__`. +pub struct Handle { + count: u32, +} + +impl Handle { + pub fn new(count: u32) -> Self { + Handle { count } + } + + pub fn count(&self) -> u32 { + self.count + } + + pub async fn later(count: u32) -> Self { + Handle { count } + } +} diff --git a/ffi/runtime/jni.rs b/ffi/runtime/jni.rs index e5d8d2ae4..9702cc561 100644 --- a/ffi/runtime/jni.rs +++ b/ffi/runtime/jni.rs @@ -805,7 +805,7 @@ fn caught(env: *mut JNIEnv, what: &str, cache: &OnceLock, name: &CStr) -> static FAILED: OnceLock = OnceLock::new(); -/// Raise the error a function returned, encoded in `w`, as the `_Native.Failed` Kotlin turns +/// Raise the error a function returned, encoded in `w`, as the `_Native.__Failed` Kotlin turns /// into its exception: a call's success path then returns its value with no `byte[]`. pub fn raise(env: *mut JNIEnv, w: Writer) { let id = method(env, &FAILED, c"__failed", c"([B)Ljava/lang/Throwable;"); diff --git a/ffi/runtime/rt.kt b/ffi/runtime/rt.kt index 2a07a6c8e..21b9751b3 100644 --- a/ffi/runtime/rt.kt +++ b/ffi/runtime/rt.kt @@ -3,7 +3,7 @@ // objects own, what frees them once collected, and the waker futures park on. /** Encodes values as the library's JNI glue decodes them: little-endian, field by field. */ -class Writer { +class __Writer { private var b: java.nio.ByteBuffer = java.nio.ByteBuffer.allocate(64).order(java.nio.ByteOrder.LITTLE_ENDIAN) private fun room(n: Int) { @@ -184,19 +184,19 @@ class Writer { } } - private var held: java.util.ArrayList? = null + private var held: java.util.ArrayList<__Handle>? = null // What holds Rust's bytes encoded in place, which the GC must not free before [release]. private var kept: java.util.ArrayList? = null /** An object's handle, held until [release], or 0 for none. */ - fun handle(v: Handle?) { + fun handle(v: __Handle?) { if (v == null) { i64(0L) return } i64(v.hold()) - (held ?: java.util.ArrayList().also { held = it }).add(v) + (held ?: java.util.ArrayList<__Handle>().also { held = it }).add(v) } fun finish(): ByteArray = b.array().copyOf(b.position()) @@ -208,7 +208,7 @@ class Writer { } /** Run [block] with this writer, releasing its handles once it returns. */ - inline fun use(block: (Writer) -> R): R { + inline fun use(block: (__Writer) -> R): R { try { return block(this) } finally { @@ -218,7 +218,7 @@ class Writer { } /** Decodes what the library's JNI glue encodes. */ -class Reader(private val b: java.nio.ByteBuffer) { +class __Reader(private val b: java.nio.ByteBuffer) { constructor(bytes: ByteArray) : this(java.nio.ByteBuffer.wrap(bytes)) init { b.order(java.nio.ByteOrder.LITTLE_ENDIAN) } @@ -282,7 +282,7 @@ class Reader(private val b: java.nio.ByteBuffer) { /** Bytes Rust handed over, copied or lent by their owner, or null for none. */ fun owned(): Bytes? = when (val n = b.getInt()) { -1 -> null - LENT -> Bytes(Lent(b.getLong()), b.getInt()) + LENT -> Bytes(__Lent(b.getLong()), b.getInt()) else -> Bytes(ByteArray(n).also { b.get(it) }) } @@ -336,12 +336,12 @@ class Reader(private val b: java.nio.ByteBuffer) { * reference, which one daemon thread takes off one queue, as every JVM and Android level * has. Freeing first is the fast path, and [untrack] makes it the only one. */ -abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owner, QUEUE) { +abstract class __Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owner, QUEUE) { // The GC enqueues only a reference still reachable, so each is linked from its stripe's // head until freed. The stripe is the making thread's, so threads making objects // at once rarely share a lock, and a free from any thread finds it in [stripe]. - private var prev: Cleanup? = null - private var next: Cleanup? = null + private var prev: __Cleanup? = null + private var next: __Cleanup? = null // Final, so a thread the object reaches unsafely still sees it. private val stripe = STRIPES[java.lang.Thread.currentThread().hashCode() and (STRIPES.size - 1)] @@ -375,7 +375,7 @@ abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owner, val QUEUE = java.lang.ref.ReferenceQueue() /** One lock and list of the tracked. */ class Stripe { - @JvmField var head: Cleanup? = null + @JvmField var head: __Cleanup? = null } // A power of two, past the cores a phone or most servers have. @@ -383,7 +383,7 @@ abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owner, init { val thread = java.lang.Thread({ - while (true) (QUEUE.remove() as Cleanup).collected() + while (true) (QUEUE.remove() as __Cleanup).collected() }, "rust2-ffi cleaner") thread.isDaemon = true thread.start() @@ -396,8 +396,8 @@ abstract class Cleanup(owner: Any?) : java.lang.ref.PhantomReference(owner, * only once no call does, and a call after [close] throws. An owned one is closed once * the GC collects [owner], if nothing closed it. */ -class Handle(owner: Any, internal val raw: Long, private val free: Drop?, private val type: String) : - Cleanup(if (free == null) null else owner) { +class __Handle(owner: Any, internal val raw: Long, private val free: __Drop?, private val type: String) : + __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 @@ -454,14 +454,14 @@ class Handle(owner: Any, internal val raw: Long, private val free: Drop?, privat private companion object { const val CLOSED = 1L const val HELD = 2L - val STATE: java.util.concurrent.atomic.AtomicLongFieldUpdater = - java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater(Handle::class.java, "state") + val STATE: java.util.concurrent.atomic.AtomicLongFieldUpdater<__Handle> = + java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater(__Handle::class.java, "state") } } /** A waker Rust returned: [wake] wakes it through Rust until [close], or the GC, drops it. */ -class Returned(raw: Long) : Waker, AutoCloseable { - private val handle = Handle(this, raw, Drop { __waker_drop(it) }, "Waker") +class __Returned(raw: Long) : Waker, AutoCloseable { + private val handle = __Handle(this, raw, __Drop { __waker_drop(it) }, "Waker") override fun wake() = handle.hold { __waker_wake(it) } @@ -469,7 +469,7 @@ class Returned(raw: Long) : Waker, AutoCloseable { } /** Frees a raw handle: a `fun interface`, so the handle crosses unboxed. */ -fun interface Drop { +fun interface __Drop { fun drop(raw: Long) } @@ -479,13 +479,13 @@ fun interface Drop { * returns: a fence on every JVM and Android level, where `Reference.reachabilityFence` * needs API 28. */ -class Lent(internal val owner: Long) { +class __Lent(internal val owner: Long) { init { - Free(this, owner) + __Free(this, owner) } } -private class Free(lent: Lent, private val owner: Long) : Cleanup(lent) { +private class __Free(lent: __Lent, private val owner: Long) : __Cleanup(lent) { init { track() } @@ -509,18 +509,18 @@ const val TEXT = -4 fun owned(given: Any?): Bytes? = when (given) { null -> null is ByteArray -> Bytes(given) - else -> (given as kotlin.LongArray).let { Bytes(Lent(it[0]), it[1].toInt()) } + else -> (given as kotlin.LongArray).let { Bytes(__Lent(it[0]), it[1].toInt()) } } /** Run [block] with the raw handle of [handle], or 0 for none, held until it returns. */ -inline fun hold(handle: Handle?, block: (Long) -> R): R = when (handle) { +inline fun hold(handle: __Handle?, block: (Long) -> R): R = when (handle) { null -> block(0L) else -> handle.hold(block) } /** A waker a future parks on, which latches a wake that lands before it parks. */ // The atomic itself, so a call allocates one object for it. -class Signal : java.util.concurrent.atomic.AtomicReference(null), Waker { +class __Signal : java.util.concurrent.atomic.AtomicReference(null), Waker { override fun wake() { val parked = getAndSet(WOKEN) if (parked !is kotlinx.coroutines.CancellableContinuation<*>) return @@ -561,7 +561,7 @@ class Signal : java.util.concurrent.atomic.AtomicReference(null), Waker { * or by Rust, it ends unfinished: Rust never sees it done, so a call the caller cancelled * reports the caller's cancel. */ -class Pollable( +class __Pollable( private val body: suspend () -> Unit, private val context: kotlin.coroutines.CoroutineContext, ) : AutoCloseable { @@ -598,7 +598,7 @@ class Pollable( return false } - /** [context] without its job, on a dispatcher that defers, as [Signal] resumes on. */ + /** [context] without its job, on a dispatcher that defers, as [__Signal] resumes on. */ private fun dispatched(): kotlin.coroutines.CoroutineContext { val bare = context.minusKey(kotlinx.coroutines.Job) val dispatcher = bare[kotlin.coroutines.ContinuationInterceptor] as? kotlinx.coroutines.CoroutineDispatcher @@ -651,10 +651,10 @@ class Pollable( } /** A completed native future, including one whose value is null. */ -class Ready(val value: Any?) +class __Ready(val value: Any?) /** A native future still waiting on its waker node. */ -class Pending(val raw: Long, val node: Long) +class __Pending(val raw: Long, val node: Long) /** * Await the future the call that returned [first] made and polled once with [signal]: @@ -663,12 +663,12 @@ class Pending(val raw: Long, val node: Long) */ suspend fun await( first: Any?, - signal: Signal, + signal: __Signal, poll: (Long, Long) -> Any?, free: (Long) -> Unit, ): Any? { - if (first is Ready) return first.value - val pending = first as Pending + if (first is __Ready) return first.value + val pending = first as __Pending val raw = pending.raw val node = pending.node try { @@ -676,7 +676,7 @@ suspend fun await( signal.park() signal.reset() val done = poll(raw, node) - if (done != null) return (done as Ready).value + if (done != null) return (done as __Ready).value } } finally { free(raw) @@ -688,7 +688,7 @@ suspend fun await( * Equality as Rust's `==` has it, apart from the exported functions, which a nested object's * members never overload. */ -object Eq { +object __Eq { /** * Whether [a] and [b] are equal as Rust's `==` compares them: primitive arrays, lists, and * tuples by their contents, and floats by IEEE `==`, so NaN equals nothing and -0.0 equals diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index 54f5f9a8f..2f68fddac 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -136,7 +136,7 @@ pub fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result_native`, `_waker`, `_bytes`, `_mut`, and -/// `_bound`. +/// take. The runtime's helper classes, which `_Native` nests, take a leading `__`, which +/// neither an exported type's name nor its `_` import alias in the glue has, so they +/// need no place here. The runtime's own are the C ABI's: `Native`, `Waker`, `Bytes`, `Mut`, +/// and `Bound` are claimed as `_native`, `_waker`, `_bytes`, +/// `_mut`, and `_bound`. const TAKEN: &[&str] = &[ "Any", "AutoCloseable", "Boolean", "Byte", "ByteArray", - "Cleanup", "Double", "DoubleArray", - "Drop", - "Eq", "Exception", - "Failed", "Float", "FloatArray", - "Free", - "Handle", "Int", "IntArray", - "Lent", "Long", "LongArray", - "Pending", - "Pollable", - "Reader", - "Ready", - "Returned", "Short", "ShortArray", - "Signal", "StartSeekable", "String", "UByte", @@ -422,7 +410,6 @@ const TAKEN: &[&str] = &[ "UShort", "UShortArray", "Unit", - "Writer", "check", "error", ]; @@ -845,7 +832,7 @@ impl<'a> Gen<'a> { false => format!("r_{}({r})", abi.enumeration(*i)), }, Type::Object(i) => format!("{}({r}.i64())", self.qualified(&abi.object(*i))), - Type::Waker => format!("_Native.Returned({r}.i64())"), + Type::Waker => format!("_Native.__Returned({r}.i64())"), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("r_{}({r})", abi.range(ty)), Type::Tuple(elements) => { let read: Vec = elements.iter().map(|e| self.read(e, r, owned)).collect(); @@ -864,7 +851,7 @@ impl<'a> Gen<'a> { Ty::Bool | Ty::F32 | Ty::F64 | Ty::Char => e.to_string(), Ty::Int(int) => from_signed(*int, e), Ty::Enum(name) => format!("{}.of({e})", self.qualified(name)), - Ty::Waker => format!("_Native.Returned({e})"), + Ty::Waker => format!("_Native.__Returned({e})"), Ty::Handle { name, .. } => { let class = self.qualified(name); let wrap = |h: &str| match lent { @@ -888,7 +875,7 @@ impl<'a> Gen<'a> { _ => { let r = self.fresh("r"); let read = self.read(&strip_refs(ty), &r, !lent); - format!("_Native.Reader({e}).let {{ {r} -> {read} }}") + format!("_Native.__Reader({e}).let {{ {r} -> {read} }}") } } } @@ -904,7 +891,7 @@ impl<'a> Gen<'a> { Ty::Struct(_) => { let w = self.fresh("w"); let write = self.write_value(ty, &w, e); - format!("_Native.Writer().use {{ {w} -> {write}; {w}.finish() }}") + format!("_Native.__Writer().use {{ {w} -> {write}; {w}.finish() }}") } _ => e.to_string(), } @@ -1042,7 +1029,7 @@ impl<'a> Gen<'a> { arg.jni.extend(["jbyteArray", "jobjectArray"]); arg.native .extend(["ByteArray", "kotlin.Array?"].map(str::to_string)); - arg.open = Some(format!("_Native.Writer().use {{ {w} ->")); + arg.open = Some(format!("_Native.__Writer().use {{ {w} ->")); arg.inside.extend(writes); arg.exprs.push(format!("{w}.finish()")); arg.exprs.push(format!("{w}.refs()")); @@ -1068,7 +1055,7 @@ impl<'a> Gen<'a> { let close = self.close(ty, e); arg.after.push(close); } - arg.open = Some(format!("_Native.Writer().use {{ {w} ->")); + arg.open = Some(format!("_Native.__Writer().use {{ {w} ->")); let value = self.write_value(ty, &w, e); arg.inside.push(value); // Then the arrays and text it names, which Rust copies from once. @@ -1125,7 +1112,7 @@ impl<'a> Gen<'a> { true => "_context()", false => "_noContext", }; - arg.exprs.push(format!("_Native.Pollable({e}, {context})")); + arg.exprs.push(format!("_Native.__Pollable({e}, {context})")); arg.rust_args.push(format!("rt::future(env, {p})")); } Ty::Void | Ty::Future(_) | Ty::Poll | Ty::Out(_) | Ty::Data => { @@ -1260,7 +1247,7 @@ impl<'a> Gen<'a> { let _ = write!(self.types, "data class {name}({fields})\n\n"); let _ = write!( self.top, - "internal fun w_{c}(w: _Native.Writer, v: {name}) {{\n\t{write}\n}}\n\ninternal fun r_{c}(r: _Native.Reader): {name} = {read}\n\n" + "internal fun w_{c}(w: _Native.__Writer, v: {name}) {{\n\t{write}\n}}\n\ninternal fun r_{c}(r: _Native.__Reader): {name} = {read}\n\n" ); } @@ -1319,7 +1306,7 @@ impl<'a> Gen<'a> { let write = self.write_value(ty, "w", "this"); ( vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], - format!("_Native.Writer().use {{ w ->\n\t\t{write}"), + format!("_Native.__Writer().use {{ w ->\n\t\t{write}"), "w.finish(), w.refs()".to_string(), "&rt::Reader::new(env, &rt::bytes(env, p0).unwrap_or_default(), p1).get()".to_string(), ) @@ -1402,7 +1389,7 @@ impl<'a> Gen<'a> { "jbyteArray", "ByteArray", format!("let mut w = rt::Writer::default();\n\t\tw.put(crate::{c}_default());\n\t\tw.array(env)"), - self.read_value(ty, &format!("_Native.Reader(_Native.{bare}_default())")), + self.read_value(ty, &format!("_Native.__Reader(_Native.{bare}_default())")), ), }; self.native(&format!("{bare}_default"), &[], (jni, native), &rust); @@ -1515,7 +1502,7 @@ impl<'a> Gen<'a> { let reads: Vec = record.fields.iter().map(|f| self.read_value(&f.ty, "r")).collect(); let _ = write!( self.top, - "internal fun w_{c}(w: _Native.Writer, v: {name}) {{\n{}}}\n\ninternal fun r_{c}(r: _Native.Reader): {name} = {name}({})\n\n", + "internal fun w_{c}(w: _Native.__Writer, v: {name}) {{\n{}}}\n\ninternal fun r_{c}(r: _Native.__Reader): {name} = {name}({})\n\n", writes.iter().map(|w| format!("\t{w}\n")).collect::(), reads.join(", ") ); @@ -1553,7 +1540,7 @@ impl<'a> Gen<'a> { let _ = write!(self.types, "{docs}{head}{body}\n\n"); let _ = write!( self.top, - "internal fun w_{c}(w: _Native.Writer, v: {name}) {{\n{write}}}\n\ninternal fun r_{c}(r: _Native.Reader): {name} = {read}\n\n" + "internal fun w_{c}(w: _Native.__Writer, v: {name}) {{\n{write}}}\n\ninternal fun r_{c}(r: _Native.__Reader): {name} = {read}\n\n" ); let _ = write!( self.glue, @@ -1717,7 +1704,7 @@ impl<'a> Gen<'a> { ); let _ = write!( self.top, - "internal fun w_{c}(w: _Native.Writer, v: {name}) {{\n\twhen (v) {{\n{}\n\t}}\n}}\n\ninternal fun r_{c}(r: _Native.Reader): {name} = when (r.i32()) {{\n{}\n\telse -> error(\"{c}: an invalid tag\")\n}}\n\n", + "internal fun w_{c}(w: _Native.__Writer, v: {name}) {{\n\twhen (v) {{\n{}\n\t}}\n}}\n\ninternal fun r_{c}(r: _Native.__Reader): {name} = when (r.i32()) {{\n{}\n\telse -> error(\"{c}: an invalid tag\")\n}}\n\n", writes.join("\n"), reads.join("\n").replace("\t\t", "\t") ); @@ -1745,7 +1732,7 @@ impl<'a> Gen<'a> { &format!("crate::{c}_free(p0 as usize as _)"), ); let mut body = vec![format!( - "\tinternal val handle = _Native.Handle(this, raw, if (lent) null else _Native.Drop {{ _Native.{bare}_free(it) }}, \"{name}\")\n\n\t/** Free the handle once no call holds it: a call after this throws. */\n\toverride fun close() = handle.close()\n" + "\tinternal val handle = _Native.__Handle(this, raw, if (lent) null else _Native.__Drop {{ _Native.{bare}_free(it) }}, \"{name}\")\n\n\t/** Free the handle once no call holds it: a call after this throws. */\n\toverride fun close() = handle.close()\n" )]; let mut statics = Vec::new(); self.traits(&ty, &c, object.traits, &mut body, &mut statics); @@ -2339,13 +2326,13 @@ impl<'a> Gen<'a> { } let last = lines.pop().expect("a future has a value"); let pending = if pending { - "if (!r.bool()) return Pending(r.i64(), r.i64())" + "if (!r.bool()) return __Pending(r.i64(), r.i64())" } else { "" }; 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@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", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); } @@ -2368,7 +2355,7 @@ impl<'a> Gen<'a> { self.refused_first(&bare, format!("try {{ {raw} }} finally {{ {} }}", after.join("; "))) }; let awaited = format!( - "_Native.Signal().let {{ {s} -> _Native.await({call}, {s}, {{ f, n -> _Native.{poll_bare}(f, n) }}, {{ _Native.{free_bare}(it) }}) }}", + "_Native.__Signal().let {{ {s} -> _Native.await({call}, {s}, {{ f, n -> _Native.{poll_bare}(f, n) }}, {{ _Native.{free_bare}(it) }}) }}", s = signal.as_deref().expect("a future takes a signal") ); value = if ok == Type::Unit { @@ -2414,7 +2401,7 @@ impl<'a> Gen<'a> { values.push("jvalue { l: error }".to_string()); let read = self.read_value(err.as_ref().expect("a result's error"), "r"); failure = format!( - "if (error != null) {{ val r = Reader(error); throw {}({read}) }}", + "if (error != null) {{ val r = __Reader(error); throw {}({read}) }}", exception.as_deref().expect("a result's exception") ); format!( @@ -2461,7 +2448,7 @@ impl<'a> Gen<'a> { 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. + // its error as a `_Native.__Failed` Kotlin catches. 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(); @@ -2497,7 +2484,7 @@ impl<'a> Gen<'a> { let exception = exception.as_deref().expect("a result's exception"); let raw = format!("_Native.{bare}({})", exprs.join(", ")); let caught = match after.is_empty() { - true => format!("try {{\n\t{raw}\n}} catch (f: _Native.Failed) {{\n\t_Native.Reader(f.error).let {{ {r} -> throw {exception}({e}) }}\n}}"), + true => format!("try {{\n\t{raw}\n}} catch (f: _Native.__Failed) {{\n\t_Native.__Reader(f.error).let {{ {r} -> throw {exception}({e}) }}\n}}"), false => self.refused_first( &bare, format!( @@ -2505,7 +2492,7 @@ impl<'a> Gen<'a> { after.join("\n\t") ) .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)), + .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, @@ -2540,7 +2527,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@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", lines.iter().map(|l| format!("\t\t{l}\n")).collect::() ); let mut params = params; @@ -2621,10 +2608,10 @@ impl<'a> Gen<'a> { let made = match (rest, flat.option) { (false, false) => format!("{call}.let {{ {make} }}"), (false, true) => format!("if ({call}) {make} else null"), - (true, false) => format!("_Native.Reader({call}).let {{ {r} -> {make} }}"), + (true, false) => format!("_Native.__Reader({call}).let {{ {r} -> {make} }}"), (true, true) => { let b = self.fresh("b"); - format!("{call}?.let {{ {b} -> _Native.Reader({b}).let {{ {r} -> {make} }} }}") + format!("{call}?.let {{ {b} -> _Native.__Reader({b}).let {{ {r} -> {make} }} }}") } }; value = match flat.slots.is_empty() { @@ -2640,7 +2627,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@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" ); let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); self.native(&bare, ¶ms, ("jobject", "Any?"), &format!( @@ -3601,10 +3588,10 @@ mod tests { assert_eq!(super::room(3, true, true), 250); } - /// Every class the runtime declares is taken, so an exported type of its name is renamed - /// rather than shadowed inside `Native`. + /// Every class the runtime declares takes a leading `__`, which neither an exported type's + /// Pascal-case name nor its `_` import alias has, so none shadows one inside `_Native`. #[test] - fn runtime_classes_taken() { + fn runtime_classes_prefixed() { for line in super::RUNTIME.lines() { let words: Vec<&str> = line.split_whitespace().collect(); let Some(at) = words @@ -3627,7 +3614,10 @@ mod tests { ) }) && !name.is_empty() { - assert!(super::taken(&name), "the runtime's class {name} is not in TAKEN"); + assert!( + name.starts_with("__"), + "the runtime's class {name} takes no leading `__`" + ); } } } diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index d82978add..acba4e7ee 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -1427,6 +1427,7 @@ fun clash() { check(Clash.String("hi").raw().toByteArray().decodeToString() == "hi", "clash bytes") val out = Mut(0u) check(Clash.Int(4).describe("t", 3u, Shape.SQUARE, out) == "t Int(4) 3 Square" && out.value == 6u, "clash describe") + check(Handle.new(5u).use { it.count() } == 5u && runBlocking { Handle.later(6u) }.use { it.count() } == 6u, "an object named as a former runtime class") } fun returns() { diff --git a/quest/m1/ffi-export/kotlin-runtime-names.md b/quest/m1/ffi-export/kotlin-runtime-names.md deleted file mode 100644 index 839193bd1..000000000 --- a/quest/m1/ffi-export/kotlin-runtime-names.md +++ /dev/null @@ -1,11 +0,0 @@ -# [S] Kotlin runtime helpers take underscore-prefixed names - -## Goal - -The Kotlin runtime's helper classes (`Reader`, `Handle`, `Ready`, ...) take `_`-prefixed names, so no exported type is renamed with a trailing `_` to dodge them and `TAKEN` in `ffi/src/kotlin.rs` no longer lists them. - -## Plan - -- ✅ keep (maintainer, 2026-11-13, when landing kixel-ai/rust2#750 with the reservation as is). -- Follow kixel-ai/rust2#777's naming, which did the same for `_Native` and its `_` import aliases. -- Rename each helper, drop it from `TAKEN`, and add a fixture exporting a type named like a former helper to prove it keeps its name.