//! Kotlin over the C ABI, through JNI: `kotlin/.kt`, and the JNI functions it //! calls, which the crate builds with its `kotlin` feature. //! //! Each name is its C name without the prefix, in a package of the prefix, as Kotlin //! spells it: `moq_track_producer` is `moq.TrackProducer`, and its method //! `moq_track_producer_append_group` is `TrackProducer.appendGroup`. A keyword is quoted //! in backticks, and a member named as one Kotlin gives every class takes a trailing `_`. //! An object is a class owning its handle, closed by `close`; a record a data class; an //! enum an enum class, or for one with data a sealed class of a class per variant; a trait //! an interface; a closure a function type; a reader a `SeekableByteChannel`; a future a //! `suspend fun`; an error an exception. The runtime they share, //! [`runtime/rt.kt`](../runtime/rt.kt), holds the codec, the handles, and the waker a //! future parks on; the glue's, [`runtime/jni.rs`](../runtime/jni.rs), the same on the //! Rust side. //! //! A value crosses JNI as a scalar, a handle as a `long`, bytes passed in as a `byte[]`, //! 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, 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}; use std::fmt::Write; use std::hash::Hasher; use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Ty, pascal}; use crate::ir::{Access, Family, Function, Int, Jni, Literal, Mutability, On, Opaque, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.kt"); /// The runtime's public types, at the generated file's top level. const TYPES: &str = include_str!("../runtime/types.kt"); pub(crate) const GLUE_RUNTIME: &str = include_str!("../runtime/jni.rs"); /// What the generator writes: the Kotlin file, the Rust module of JNI functions, and the /// R8 and ProGuard rules keeping what that module looks up by name. pub(crate) struct Output { pub(crate) names: BTreeMap, pub(crate) kotlin: String, pub(crate) glue: String, pub(crate) rules: String, } /// The Kotlin for `abi`, whose header's contract is `contract`, or the names two items /// claim alike. The Kotlin's own contract hashes the header's with everything it and its /// glue add, as JNI's signatures and encodings change with no C declaration changing. pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result { let mut g = Gen { locked: BTreeMap::new(), abi, classes: abi.classes(|_| (String::new(), 0), taken), types: String::new(), top: String::new(), natives: String::new(), glue: String::new(), exceptions: BTreeMap::new(), thrown: HashMap::new(), names: BTreeMap::new(), errors: Vec::new(), fresh: 0, params: Vec::new(), tuples: BTreeSet::new(), aliases: std::cell::RefCell::new(BTreeSet::new()), dispatchers: Vec::new(), suspends: false, reads: false, fails: false, on: On::ALL, slots: 0, room: 0, }; for name in g.classes.values() { g.names.insert(name.clone(), "a type".to_string()); } g.locked = crate::lock::types(abi, &g.classes); g.write(); if !g.errors.is_empty() { return Err(g.errors.join("\n")); } let p = &abi.prefix; let mut hasher = StableHasher::new(); hasher.write_u64(contract); for part in [ &g.types, &g.top, &g.natives, &g.glue, RUNTIME, GLUE_RUNTIME, BYTES, TYPES, ] { hasher.write(part.as_bytes()); } let contract = Hasher::finish(&hasher); let mut kotlin = format!( "// Generated by rust2-ffi: Kotlin over the C ABI of the pub API of {packages}. Do not edit.\n\n\ @file:kotlin.Suppress(\"ktlint\", \"NAME_SHADOWING\", \"RedundantVisibilityModifier\", \"unused\", \"UNUSED_VARIABLE\", \"UNCHECKED_CAST\")\n\ @file:kotlin.OptIn(kotlin.ExperimentalUnsignedTypes::class)\n\n\ package {p}\n\n" ); for import in IMPORTS { let _ = writeln!(kotlin, "import {import}"); } for name in g.aliases.borrow().iter() { // An alias hides the name it renames from the file, so the name is imported too. let _ = writeln!(kotlin, "import {p}.{name}\nimport {p}.{name} as _{name}"); } kotlin.push('\n'); kotlin.push_str(BUILTINS); kotlin.push_str( "/** Wakes a future's poller. Rust may call [wake] from any thread, any number of times. */\nfun interface Waker {\n\tfun wake()\n}\n\n", ); kotlin.push_str(BYTES); kotlin.push_str(TYPES); kotlin.push('\n'); kotlin.push_str( "/** A value a call takes `&mut`, which Rust writes back into [value] once it returns, errors included. */\nclass Mut(var value: T)\n\n", ); kotlin.push_str(&g.types); kotlin.push_str(&g.top); if g.reads { kotlin.push_str(START_SEEKABLE); } // What the glue calls to read a reader, and to take the error a closure or reader threw. let mut helpers = String::new(); let mut looked = vec!["__wake", "__free", "__poll", "__failed", "__refused", "__invalid"]; if g.reads { helpers.push_str(READS); looked.extend(["__read", "__seek", "__io_error"]); } if g.slots > 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@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 ); } if g.fails { let thrown = g.thrown.get("kotlin.String").expect("a closure's error is a String"); let _ = write!( helpers, "\t@kotlin.jvm.JvmStatic private fun __error(thrown: Throwable): ByteArray? = (thrown as? {thrown})?.error?.let {{ _utf8(it) }}\n\n" ); looked.push("__error"); } let _ = write!( kotlin, "/** The runtime's [_Native.__Eq], by a name no class, field, or member of the binding takes, since\n * each is in Pascal or camel case. */\ninternal val _eq = _Native.__Eq\n\ninternal object _Native {{\n\tinit {{\n\t\tSystem.loadLibrary(\"{p}\")\n\t\t// Checked before any other call, which it readies the library for: a Kotlin file\n\t\t// and a library from different builds must not mix.\n\t\tkotlin.check(__contract().toULong() == {}) {{ \"{p}.kt and the library are from different builds\" }}\n\t}}\n\n\t@kotlin.jvm.JvmStatic external fun __contract(): Long\n\n\t@kotlin.jvm.JvmStatic external fun __target(): Int\n\n\t@kotlin.jvm.JvmStatic external fun __usize_max(): Long\n\n\t/** The index of the library's target among those this file serves. */\n\tprivate val target = __target()\n\n\t/** Throws unless the library's target is among those of [on], as the item [what] is. */\n\tfun check(on: ULong, what: String) {{\n\t\tif ((on shr target) and 1uL == 0uL) throw kotlin.UnsupportedOperationException(\"$what: it is not on this library's target\")\n\t}}\n\n\t@kotlin.jvm.JvmStatic external fun __waker_new(waker: Waker): Long\n\n\t@kotlin.jvm.JvmStatic external fun __waker_free(node: Long)\n\n\t@kotlin.jvm.JvmStatic external fun __waker_wake(raw: Long)\n\n\t@kotlin.jvm.JvmStatic external fun __waker_drop(raw: Long)\n\n\t@kotlin.jvm.JvmStatic external fun __bytes_get(lent: __Lent, owner: Long, index: Int): Byte\n\n\t@kotlin.jvm.JvmStatic external fun __bytes_copy(lent: __Lent, owner: Long, start: Int, len: Int, destination: ByteArray, at: Int)\n\n\t@kotlin.jvm.JvmStatic external fun __bytes_free(owner: Long)\n\n\t@kotlin.jvm.JvmStatic private fun __wake(waker: Any) = (waker as Waker).wake()\n\n\t@kotlin.jvm.JvmStatic private fun __poll(pollable: Any, waker: Long): Boolean = (pollable as __Pollable).poll(waker)\n\n\t@kotlin.jvm.JvmStatic private fun __free(implementation: Any) {{\n\t\tif (implementation is AutoCloseable) implementation.close()\n\t}}\n\n\t/** The encoded error a native call raised, which its function throws as its exception. No stack trace: it is caught at once. */\n\tclass __Failed(@kotlin.jvm.JvmField val error: ByteArray) : kotlin.RuntimeException(null, null, false, false)\n\n\t@kotlin.jvm.JvmStatic private fun __failed(error: ByteArray): Throwable = __Failed(error)\n\n\t/** A call a failed run-time check refused, before it moved or changed anything. */\n\tclass __Refused(message: String) : kotlin.IllegalStateException(message)\n\n\t@kotlin.jvm.JvmStatic private fun __refused(message: String): Throwable = __Refused(message)\n\n\t/** A call refused before it moved or changed anything, as an argument holds a value its Rust type cannot. */\n\tclass __Invalid(message: String) : kotlin.IllegalArgumentException(message)\n\n\t@kotlin.jvm.JvmStatic private fun __invalid(message: String): Throwable = __Invalid(message)\n\n{helpers}{}{}}}\n", contract_literal(contract), g.natives, indent_by(RUNTIME, 1), ); let glue = format!( "//! Generated by rust2-ffi: the JNI functions `kotlin/{p}.kt` calls, over the C ABI of {packages}.\n\n\ #![allow(non_snake_case, non_upper_case_globals, unused_mut, unused_unsafe, unused_variables, clippy::all)]\n\n\ mod rt;\n\n\ #[allow(unused_imports, reason = \"a future's or closure's glue names it\")]\n\ use std::ffi::c_void;\n\ use rt::*;\n\n\ // No `JNI_OnLoad`, which the library may define for itself: _Native's first call notes\n\ // the JVM and the class.\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1contract(env: *mut JNIEnv, class: jclass) -> jlong {{\n\ \tunsafe {{ rt::load(env, class) }};\n\ \t0x{contract:016x}u64 as jlong\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub extern \"system\" fn Java_{pkg}__1Native__1_1target(_: *mut JNIEnv, _: jclass) -> jint {{\n\ \tcrate::{p}_target() as jint\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub extern \"system\" fn Java_{pkg}__1Native__1_1usize_1max(_: *mut JNIEnv, _: jclass) -> jlong {{\n\ \tusize::MAX as u64 as jlong\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub extern \"system\" fn Java_{pkg}__1Native__1_1waker_1new(env: *mut JNIEnv, _: jclass, waker: jobject) -> jlong {{\n\ \trt::node(env, waker) as usize as jlong\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1waker_1free(_: *mut JNIEnv, _: jclass, node: jlong) {{\n\ \tunsafe {{ rt::unref(node as usize as _) }}\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1waker_1wake(_: *mut JNIEnv, _: jclass, raw: jlong) {{\n\ \tunsafe {{ rt::wake_returned(raw) }}\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1waker_1drop(_: *mut JNIEnv, _: jclass, raw: jlong) {{\n\ \tunsafe {{ rt::drop_returned(raw) }}\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1bytes_1get(_: *mut JNIEnv, _: jclass, _: jobject, owner: jlong, index: jint) -> jbyte {{\n\ \tunsafe {{ rt::byte_at(owner, index) }}\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1bytes_1copy(env: *mut JNIEnv, _: jclass, _: jobject, owner: jlong, start: jint, len: jint, destination: jbyteArray, at: jint) {{\n\ \tunsafe {{ rt::copy(env, owner, start, len, destination, at) }}\n\ }}\n\n\ #[unsafe(no_mangle)]\n\ pub unsafe extern \"system\" fn Java_{pkg}__1Native__1_1bytes_1free(_: *mut JNIEnv, _: jclass, owner: jlong) {{\n\ \tunsafe {{ rt::free_bytes(owner) }}\n\ }}\n\n\ {}", g.glue, pkg = mangle(p), ); // The VM binds _Native's native methods by its name and theirs, and the glue looks up // each Kotlin function it calls by its own, which nothing in Kotlin calls. // A shrinker still strips _Native and its native methods where nothing reaches them. let mut rules = format!( "# Generated by rust2-ffi: the R8 and ProGuard rules keeping what the JNI glue of {packages} looks up by name. Do not edit.\n\n\ -keepnames class {p}._Native\n\n\ -keepclassmembernames class {p}._Native {{\n\tnative ;\n}}\n\n\ -keepclassmembers class {p}._Native {{\n" ); for name in looked.into_iter().chain(g.dispatchers.iter().map(String::as_str)) { let _ = writeln!(rules, "\tstatic *** {name}(...);"); } rules.push_str("}\n"); Ok(Output { names: g.locked, kotlin, glue, rules, }) } /// What the glue calls on a `SeekableByteChannel` a function reads: at most `len` bytes, /// none at its end, and where a seek from the start, the position, or the end lands, which /// fails as an `IOException` before the start or past `Long.MAX_VALUE`, as Rust's own /// readers do, but for a seek from the start a [`START_SEEKABLE`] channel takes; and the /// message of an `IOException` either throws, which Rust returns. A position crosses as a /// `Long`'s bits, unsigned. /// What a `SeekableByteChannel` Rust reads may also implement, to seek from its start past /// `Long.MAX_VALUE`. const START_SEEKABLE: &str = "/** * A channel Rust reads that also seeks to any offset from its start, as Rust's `SeekFrom::Start` * takes a `u64`, past the `Long` [java.nio.channels.SeekableByteChannel.position] takes. Rust * calls [seekStart] only for an offset past `Long.MAX_VALUE`; a channel without it fails that * seek. */ interface StartSeekable { /** Move to [offset] from the start, returning the position. */ fun seekStart(offset: ULong): ULong } "; const READS: &str = "\t@kotlin.jvm.JvmStatic private fun __read(channel: Any, len: Int): ByteArray { \t\tval buffer = java.nio.ByteBuffer.allocate(len) \t\t// Only -1 is the end: Rust's Read would take a read of no bytes for it. \t\tvar read = 0 \t\twhile (read == 0 && len > 0) read = (channel as java.nio.channels.SeekableByteChannel).read(buffer) \t\treturn if (read == len) buffer.array() else buffer.array().copyOf(maxOf(read, 0)) \t} \t@kotlin.jvm.JvmStatic private fun __seek(channel: Any, whence: Int, offset: Long): Long { \t\tval channel = channel as java.nio.channels.SeekableByteChannel \t\tval base = when (whence) { \t\t\t0 -> 0L \t\t\t1 -> channel.position() \t\t\telse -> channel.size() \t\t} \t\tval at = base + offset \t\t// From the start, a negative offset's bits are unsigned, past what a Long holds. \t\tif (whence == 0 && offset < 0) { \t\t\tval start = channel as? StartSeekable ?: throw java.io.IOException(\"a seek past Long.MAX_VALUE of a channel that is no StartSeekable\") \t\t\treturn start.seekStart(offset.toULong()).toLong() \t\t} \t\tif (at < 0 || (offset > 0 && at < base)) throw java.io.IOException(\"invalid seek to a negative or overflowing position\") \t\tchannel.position(at) \t\treturn at \t} \t@kotlin.jvm.JvmStatic private fun __io_error(thrown: Throwable): ByteArray? = \t\t(thrown as? java.io.IOException)?.let { (it.message ?: it.toString()).encodeToByteArray() } "; /// The builtins a method body calls whose names an export may take, so neither a parameter /// named `kotlin` nor an imported export shadows them. `_` then a lower-case letter is no /// export's, local's, or field's name. const BUILTINS: &str = "/** [kotlin.collections.List] of [n] items, each [item] of its index. */ internal inline fun _list(n: kotlin.Int, item: (kotlin.Int) -> T): kotlin.collections.List = kotlin.collections.List(n, item) /** An array of [values], for a call's written-back arguments. */ @kotlin.Suppress(\"UNCHECKED_CAST\") internal fun _arrayOf(vararg values: kotlin.Any): kotlin.Array = values as kotlin.Array /** The caller's context, which a foreign future runs in when its call suspends. */ internal suspend inline fun _context(): kotlin.coroutines.CoroutineContext = kotlin.coroutines.coroutineContext /** No context, which a foreign future runs in when its call does not suspend. */ internal val _noContext: kotlin.coroutines.CoroutineContext get() = kotlin.coroutines.EmptyCoroutineContext "; /// Each builtin a method body names as `_`, since a parameter named `kotlin` shadows a /// `kotlin.` qualifier. An alias hides the name it renames, so each is imported plainly too, /// which only names [`TAKEN`] keep from clashing with an export's import. const IMPORTS: &[&str] = &[ "kotlin.Double", "kotlin.Double as _Double", "kotlin.Float", "kotlin.Float as _Float", "kotlin.also", "kotlin.also as _also", "kotlin.coroutines.resume", "kotlin.time.toDuration", "kotlinx.coroutines.launch", ]; /// The bytes Rust returns, copied when short and otherwise lent. const BYTES: &str = "/** * Bytes Rust returned, or a record holds, read only through these methods: no view of * Rust's memory escapes, so nothing reads it once freed. Up to 1 KiB from Rust are copied * into Kotlin's memory. Longer ones stay in Rust's buffer, each read a crossing, and are * freed once the GC finds no `Bytes` reaching it, its slices included. */ class Bytes private constructor( \t// Kotlin's bytes, or null for Rust's. \tprivate val array: ByteArray?, \t// Rust's buffer, which every slice of it holds. \tprivate val lent: _Native.__Lent?, \t// Where these start in [array] or [lent]. \tprivate val offset: Int, \t/** How many bytes these hold. */ \tval size: Int, ) { \t/** [bytes] held without a copy, as a record passed in takes them. */ \tconstructor(bytes: ByteArray) : this(bytes, null, 0, bytes.size) \tinternal constructor(lent: _Native.__Lent, size: Int) : this(null, lent, 0, size) \t/** The byte at [index], throwing `IndexOutOfBoundsException` out of range. */ \toperator fun get(index: Int): Byte { \t\tif (index < 0 || index >= size) throw kotlin.IndexOutOfBoundsException(\"index $index of $size bytes\") \t\tval array = array ?: return lent!!.let { _Native.__bytes_get(it, it.owner, offset + index) } \t\treturn array[offset + index] \t} \t/** The bytes from [startIndex] until [endIndex], sharing these without a copy. */ \tfun slice(startIndex: Int, endIndex: Int = size): Bytes { \t\trange(startIndex, endIndex) \t\treturn Bytes(array, lent, offset + startIndex, endIndex - startIndex) \t} \t/** \t * Copy the bytes from [startIndex] until [endIndex] into [destination] at \t * [destinationOffset], returning it, as `ByteArray.copyInto` does. \t */ \tfun copyInto(destination: ByteArray, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size): ByteArray { \t\trange(startIndex, endIndex) \t\tval n = endIndex - startIndex \t\tif (destinationOffset < 0 || destinationOffset > destination.size - n) { \t\t\tthrow kotlin.IndexOutOfBoundsException(\"$n bytes at $destinationOffset of ${destination.size}\") \t\t} \t\tval array = array \t\tif (array != null) return array.copyInto(destination, destinationOffset, offset + startIndex, offset + endIndex) \t\tif (n > 0) lent!!.let { _Native.__bytes_copy(it, it.owner, offset + startIndex, n, destination, destinationOffset) } \t\treturn destination \t} \t/** What holds the bytes, kept alive across a call passing them: Kotlin's array or Rust's buffer. */ \tinternal val held: Any? get() = array ?: lent \t/** Rust's owner of the bytes, which a call passing them shares without a copy, or 0 for Kotlin's. */ \tinternal val owner: Long get() = lent?.owner ?: 0L \t/** Where the bytes start in what holds them. */ \tinternal val start: Int get() = offset \t/** The bytes, copied. */ \tfun toByteArray(): ByteArray = array?.copyOfRange(offset, offset + size) ?: copyInto(ByteArray(size)) \t/** Whether [other] holds the same bytes, wherever each keeps them. */ \toverride fun equals(other: Any?): Boolean = \t\tthis === other || other is Bytes && size == other.size && contents() == other.contents() \t/** A hash of the bytes, as [equals] compares them. */ \toverride fun hashCode(): Int = contents().hashCode() \t// The bytes in Kotlin's memory, Rust's copied across in one call. \tprivate fun contents(): java.nio.ByteBuffer = \t\tjava.nio.ByteBuffer.wrap(array ?: toByteArray(), if (array == null) 0 else offset, size) \tprivate fun range(startIndex: Int, endIndex: Int) { \t\tif (startIndex < 0 || startIndex > endIndex || endIndex > size) { \t\t\tthrow kotlin.IndexOutOfBoundsException(\"$startIndex until $endIndex of $size bytes\") \t\t} \t} } "; /// The names the generated code uses unqualified, which no exported type or function may /// 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", "Double", "DoubleArray", "Duration", "Exception", "Float", "FloatArray", "Int", "IntArray", "IpAddr", "Ipv4Addr", "Ipv6Addr", "Long", "LongArray", "PathBuf", "Short", "ShortArray", "SocketAddr", "SocketAddrV4", "SocketAddrV6", "StartSeekable", "String", "UByte", "UInt", "UIntArray", "ULong", "ULongArray", "UShort", "UShortArray", "Unit", "also", "check", "error", ]; /// Whether the runtime takes the top-level Kotlin name `name`: one of [`TAKEN`], or a /// tuple's class, `Tuple`. fn taken(name: &str) -> bool { let tuple = name .strip_prefix("Tuple") .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())); tuple || TAKEN.contains(&name) } /// How a function returns a record directly: in an `Option` or not, the slots `a` its /// scalars cross in and what the glue sets each to, the reader `r` of its other fields and /// the glue's writes of them, and the Kotlin value made of both. struct Flat { option: bool, a: String, r: String, slots: Vec, puts: Vec, make: String, } /// How a function's Kotlin form is held. #[derive(Clone, Copy, PartialEq, Eq)] enum Place { /// A member of a class, whose receiver is `this`. Member, /// In a companion object, or at the top level. Static, } /// One C parameter as Kotlin passes it and the glue takes it. #[derive(Default)] struct Arg { /// The Kotlin native method's parameter types. native: Vec, /// The glue's JNI parameter types. jni: Vec<&'static str>, /// The Kotlin expressions passed. exprs: Vec, /// The lambda the call runs in, holding what it passes until it returns, and the /// statements at its start. open: Option, inside: Vec, /// Kotlin statements once the call returns. after: Vec, /// The glue's statements that may refuse the call, throwing, which run before any /// other, so nothing they leave behind needs freeing. rust_check: Vec, /// The glue's statements before the call, and the C arguments it passes. rust_pre: Vec, rust_args: Vec, } struct Gen<'a> { locked: BTreeMap, abi: &'a Abi<'a>, /// Each exported type's name, by its C name. classes: HashMap, /// Types, then top-level functions and codecs, then the native methods. types: String, top: String, natives: String, glue: String, /// The exception class of each error type, by name. exceptions: BTreeMap, /// Each exception class's name, by the Kotlin type it throws. thrown: HashMap, /// Each top-level Kotlin name, with what claimed it. names: BTreeMap, errors: Vec, /// A counter for fresh Kotlin names. fresh: usize, /// The Kotlin parameters of the function being written, which a fresh name never takes. params: Vec, /// The arities a tuple class is written for: one, and past `Triple`. tuples: BTreeSet, /// The binding's own top-level names the code reaches through [`Gen::own`]'s `_` alias. aliases: std::cell::RefCell>, /// The Kotlin functions the glue calls, which the rules keep. dispatchers: Vec, /// Whether the function being written suspends, so a future it takes runs in its /// caller's context. suspends: bool, /// Whether a function takes a reader, which the glue reads through `_Native`. reads: bool, /// Whether a closure fails by throwing, which the glue catches through `_Native`. fails: bool, /// The targets of the item being written, whose native methods check theirs. on: On, /// The most scalars a returned record crosses in, which each thread's slots hold. slots: usize, /// The JVM parameter slots the function being written may still spend on a record's /// scalars. room: usize, } impl<'a> Gen<'a> { /// The Kotlin call `raw`, then `after`, which closes what it moved out, however it ended /// unless a failed check refused it, or an argument held a value its Rust type cannot, /// which throws `_Native.__Invalid` first: either moved nothing. It binds no name a parameter /// `after` closes may take: its exception's is fresh, and its result is `_`. fn moving(&mut self, raw: &str, after: &[String]) -> String { let after = after.join("; "); let thrown = self.fresh("e"); format!( "try {{\n{}\n}} catch ({thrown}: Throwable) {{\n\tif ({thrown} !is _Native.__Refused && {thrown} !is _Native.__Invalid) {{ {after} }}\n\tthrow {thrown}\n}}.also {{ _ -> {after} }}", indent_by(raw, 1) ) } fn fresh(&mut self, base: &str) -> String { loop { self.fresh += 1; let name = format!("{base}{}", self.fresh); if !self.params.contains(&name) { return name; } } } /// A C name without the prefix. fn bare<'n>(&self, c: &'n str) -> &'n str { &c[self.abi.prefix.len() + 1..] } /// The Kotlin name of the C type `c`. fn class(&self, c: &str) -> String { self.classes.get(c).cloned().unwrap_or_else(|| pascal(self.bare(c))) } /// [`Gen::class`] through its `_` alias, as every type and constructor the generated /// code names is: a variant class nested in a sealed class shadows a bare name inside /// its body, and a field or parameter named as the package would shadow a qualifier. fn qualified(&self, c: &str) -> String { self.own(&self.class(c)) } /// The Kotlin type `kt` without the qualifiers [`Gen::kt`] adds to builtins and the /// binding's own types, as it read before it qualified them. fn unqualified(&self, kt: &str) -> String { let mut out = String::new(); let mut rest = kt; while !rest.is_empty() { let at_word = out .chars() .next_back() .is_none_or(|c| !c.is_alphanumeric() && c != '_' && c != '.'); if at_word && let Some(after) = rest.strip_prefix('_') && let ident = &after[..after .find(|c: char| !c.is_alphanumeric() && c != '_') .unwrap_or(after.len())] && self.aliases.borrow().contains(ident) { rest = after; } else if at_word && let Some(after) = rest.strip_prefix("kotlin.") && after.starts_with(|c: char| c.is_ascii_uppercase()) && !after.starts_with("Pair") && !after.starts_with("Triple") { rest = after; } else { let c = rest.chars().next().unwrap(); out.push(c); rest = &rest[c.len_utf8()..]; } } out } /// The top-level `name` of the binding's own, by its alias `_`, which the file /// imports: no exported name, in Pascal or camel case, starts with `_` and a letter. fn own(&self, name: &str) -> String { self.aliases.borrow_mut().insert(name.to_string()); format!("_{name}") } /// The top-level Kotlin name `what` takes, `name` unless that is taken. fn claim(&mut self, name: &str, what: String) -> String { abi::claim(&mut self.names, taken, name, what) } /// Whether a value of `ty` must compare through [`Gen::contents`] to match Rust's `==`: it holds /// a primitive array, which a data class compares by identity, or a float, which it /// compares by `Double.equals` after `===`, so NaN equals itself and -0.0 differs from 0.0. fn by_contents(&self, ty: &Type) -> bool { ty.holds_block() || self.abi.api.holds_float(ty) } /// The `equals` and `hashCode` of the class `name` of `fields`, by their contents. A variant /// class may be named as anything they name, such as `Any`, `Int`, or `Native`, so they /// reach the runtime through `_eq` and qualify each type; a qualifier in an expression, /// such as `kotlin.`, would be shadowed by a field of its name. fn contents(name: &str, fields: &[String]) -> String { let this: Vec = fields.iter().map(|f| format!("this.{f}")).collect(); let same: Vec = fields .iter() .map(|f| format!("_eq.same(this.{f}, other.{f})")) .collect(); format!( "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {name} && {}\n\n\toverride fun hashCode(): kotlin.Int = _eq.hashOf({})\n", same.join(" && "), this.join(", ") ) } /// The class of a tuple of `n`: of one, of two or three that must compare by /// [`Gen::by_contents`], or past `Triple`. It is 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) { let params: Vec = (1..=n).map(|k| format!("T{k}")).collect(); let fields: Vec = (0..n).map(|k| format!("\tval {}: T{},\n", ordinal(k), k + 1)).collect(); let contents = Self::contents( &format!("{name}<{}>", vec!["*"; n].join(", ")), &(0..n).map(ordinal).collect::>(), ); let _ = write!( self.types, "/** A tuple of {n}, as `Pair` and `Triple` are of two and three. */\ndata class {name}<{}>(\n{}) {{\n{contents}}}\n\n", params.join(", "), fields.concat(), ); } name } /// The Kotlin class of a tuple of `elements`: `Pair` or `Triple`, unless an element /// must compare by [`Gen::by_contents`], which theirs cannot, else a `TupleN`. fn tuple_name(&self, elements: &[Type]) -> String { match elements.len() { 2 | 3 if elements.iter().any(|e| self.by_contents(e)) => self.own(&format!("Tuple{}", elements.len())), 2 => "kotlin.Pair".to_string(), 3 => "kotlin.Triple".to_string(), n => self.own(&format!("Tuple{n}")), } } /// [`Gen::tuple_name`], declaring the `TupleN` it names. fn tuple_class(&mut self, elements: &[Type]) -> String { let name = self.tuple_name(elements); if !name.starts_with("kotlin.") { self.tuple(elements.len()); } name } /// The Kotlin type of a tuple of `elements`, whose Kotlin types are `kts`. fn tuple_of(&mut self, elements: &[Type], kts: Vec) -> String { format!("{}<{}>", self.tuple_class(elements), kts.join(", ")) } /// The Kotlin type of `ty` as a value, owning what it holds. fn kt(&mut self, ty: &Type) -> String { let abi = self.abi; match ty { Type::Const(_) => unreachable!("a const argument is no value"), Type::Array(n) => Abi::array_class(*n), Type::Unit => "kotlin.Unit".to_string(), Type::Bool => "kotlin.Boolean".to_string(), Type::Int(int) | Type::NonZero(int) => format!("kotlin.{}", kt_int(*int)), Type::F32 => "kotlin.Float".to_string(), Type::F64 => "kotlin.Double".to_string(), Type::Char => "kotlin.Int".to_string(), Type::Str | Type::String => "kotlin.String".to_string(), Type::Slice | Type::Vec | Type::Bytes => self.own("Bytes"), Type::Path | Type::PathBuf => self.own("PathBuf"), Type::U128 => "java.math.BigInteger".to_string(), Type::Duration => self.own("Duration"), Type::SocketAddr(family) => self.own(&format!("SocketAddr{}", family_suffix(*family))), Type::IpAddr(family) => self.own(&format!("Ip{}Addr", family_suffix(*family).to_lowercase())), Type::List(..) if let Some(inner) = ty.block() => format!("kotlin.{}", block(inner).kt), Type::List(_, inner) => format!("kotlin.collections.List<{}>", self.kt(inner)), Type::Waker => self.own("Waker"), Type::Reader => "java.nio.channels.SeekableByteChannel".to_string(), Type::Future => "suspend () -> kotlin.Unit".to_string(), Type::Jni(Jni::Object) => "kotlin.Any?".to_string(), Type::Jni(Jni::Env) => unreachable!("Kotlin passes no env of its own"), Type::Option(inner) => format!("{}?", self.kt(inner)), Type::Box(inner) | Type::Ref(_, inner) => self.kt(inner), Type::Record(i) => self.qualified(&abi.record(*i)), Type::Enum(i) => self.qualified(&abi.enumeration(*i)), Type::Object(i) => self.qualified(&abi.object(*i)), Type::Callback(i, _) => self.qualified(&abi.callback(*i)), Type::Closure(closure_) => { let (params, ret) = (&closure_.params, &closure_.ok); let params: Vec = params.iter().map(|p| self.kt_param(p)).collect(); format!("({}) -> {}", params.join(", "), self.kt(ret)) } Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => self.qualified(&abi.range(ty)), Type::Tuple(elements) => { let kts: Vec = elements.iter().map(|e| self.kt(e)).collect(); self.tuple_of(elements, kts) } } } /// The Kotlin type of a parameter of type `ty`, either way: one Rust writes back is a /// `Mut`. fn kt_param(&mut self, ty: &Type) -> String { match ty { Type::List(..) if let Some(inner) = ty.block() => format!("kotlin.{}", block(inner).kt), Type::List(_, inner) => format!("kotlin.collections.List<{}>", self.kt_param(inner)), Type::Option(inner) => format!("{}?", self.kt_param(inner)), Type::Ref(_, inner) if ty.written() => format!("{}<{}>", self.own("Mut"), self.kt_param(inner)), Type::Box(inner) | Type::Ref(_, inner) => self.kt_param(inner), Type::Tuple(elements) => { let kts: Vec = elements.iter().map(|e| self.kt_param(e)).collect(); self.tuple_of(elements, kts) } _ => self.kt(ty), } } /// Kotlin statements writing the Kotlin value `e` of type `ty` into the writer `w`. fn write_value(&mut self, ty: &Type, w: &str, e: &str) -> String { let abi = self.abi; match ty { Type::Bool => format!("{w}.bool({e})"), Type::Int(int) => { let (method, _) = wire_int(*int); format!("{w}.{method}({})", to_signed(*int, e)) } Type::NonZero(int) => { let (method, _) = wire_int(*int); format!("{w}.{method}({})", non_zero(&to_signed(*int, e))) } Type::F32 => format!("{w}.f32({e})"), Type::F64 => format!("{w}.f64({e})"), Type::Char => format!("{w}.i32({})", scalar_value(e)), Type::Str | Type::String => format!("{w}.string({e})"), Type::Path | Type::PathBuf => format!("{w}.path({e})"), Type::Slice | Type::Vec | Type::Bytes => format!("{w}.bytes({e})"), Type::U128 => format!("{w}.u128({e})"), Type::Array(_) => format!("{w}.raw({e}.bytes)"), Type::Duration => format!("{w}.duration({e})"), Type::SocketAddr(family) => format!("{w}.socketAddr{}({e})", family_suffix(*family)), Type::IpAddr(family) => format!("{w}.ip{}Addr({e})", family_suffix(*family).to_lowercase()), Type::List(..) if let Some(inner) = ty.block() => format!("{w}.block({})", block(inner).signed(e)), Type::List(_, inner) => { let (l, v) = (self.fresh("l"), self.fresh("v")); let item = self.write_value(inner, w, &v); format!("{e}.let {{ {l} -> {w}.i32({l}.size); for ({v} in {l}) {{ {item} }} }}") } Type::Option(inner) => match inner.base() { Type::Object(_) => format!("{w}.handle({e}?.handle)"), base if Abi::is_buf(base) => self.write_value(base, w, e), // None is a length of -1. Type::List(..) => { let v = self.fresh("v"); let some = self.write_value(inner, w, &v); format!("{e}.let {{ {v} -> if ({v} == null) {w}.i32(-1) else {some} }}") } _ => { let v = self.fresh("v"); let some = self.write_value(inner, w, &v); format!("{e}.let {{ {v} -> if ({v} == null) {w}.bool(false) else {{ {w}.bool(true); {some} }} }}") } }, Type::Box(inner) | Type::Ref(_, inner) => self.write_value(inner, w, e), Type::Record(i) => format!("w_{}({w}, {e})", abi.record(*i)), Type::Enum(i) => match abi.api.enums[*i].plain() { true => format!("{w}.i32({e}.value)"), false => format!("w_{}({w}, {e})", abi.enumeration(*i)), }, Type::Object(_) => format!("{w}.handle({e}.handle)"), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("w_{}({w}, {e})", abi.range(ty)), Type::Tuple(elements) => { let t = self.fresh("t"); let writes: Vec = (elements.iter().enumerate()) .map(|(k, ty)| self.write_value(ty, w, &format!("{t}.{}", ordinal(k)))) .collect(); format!("{e}.let {{ {t} -> {} }}", writes.join("; ")) } other => unreachable!("{other:?} is never encoded"), } } /// A Kotlin expression reading a value of type `ty`, owned, from the reader `r`. fn read_value(&mut self, ty: &Type, r: &str) -> String { self.read(ty, r, true) } /// [`Self::read_value`], reading bytes as a `Bytes` Rust handed over if `owned`, or as /// a parameter's `ByteArray`, copied, if not. fn read(&mut self, ty: &Type, r: &str, owned: bool) -> String { let abi = self.abi; match ty { Type::Unit => "Unit".to_string(), Type::Bool => format!("{r}.bool()"), Type::Int(int) | Type::NonZero(int) => { let (method, _) = wire_int(*int); from_signed(*int, &format!("{r}.{method}()")) } Type::F32 => format!("{r}.f32()"), Type::F64 => format!("{r}.f64()"), Type::Char => format!("{r}.i32()"), Type::Str | Type::String => format!("{r}.string()!!"), Type::Path | Type::PathBuf => format!("{r}.path()!!"), Type::Slice | Type::Vec | Type::Bytes if owned => format!("{r}.owned()!!"), Type::Slice | Type::Vec | Type::Bytes => format!("{r}.lent()!!"), Type::U128 => format!("{r}.u128()"), Type::Array(n) => format!("{}({r}.raw({n}))", Abi::array_class(*n)), Type::Duration => format!("{r}.duration()"), Type::SocketAddr(family) => format!("{r}.socketAddr{}()", family_suffix(*family)), Type::IpAddr(family) => format!("{r}.ip{}Addr()", family_suffix(*family).to_lowercase()), Type::List(..) if let Some(inner) = ty.block() => block(inner).read(r, &format!("{r}.i32()")), Type::List(_, inner) => { let item = self.read(inner, r, owned); format!("_list({r}.i32()) {{ {item} }}") } Type::Option(inner) => match inner.base() { Type::Object(i) => { let class = self.qualified(&abi.object(*i)); format!("{r}.i64().let {{ h -> if (h == 0L) null else {class}(h) }}") } Type::Str | Type::String => format!("{r}.string()"), Type::Path | Type::PathBuf => format!("{r}.path()"), list @ Type::List(..) if let Some(item) = list.block() => { let n = self.fresh("n"); format!( "{r}.i32().let {{ {n} -> if ({n} < 0) null else {} }}", block(item).read(r, &n) ) } Type::List(_, item) => { let n = self.fresh("n"); let item = self.read(item, r, owned); format!("{r}.i32().let {{ {n} -> if ({n} < 0) null else _list({n}) {{ {item} }} }}") } base if Abi::is_buf(base) && owned => format!("{r}.owned()"), base if Abi::is_buf(base) => format!("{r}.lent()"), _ => format!("(if ({r}.bool()) {} else null)", self.read(inner, r, owned)), }, Type::Box(inner) | Type::Ref(_, inner) => self.read(inner, r, owned), Type::Record(i) => format!("r_{}({r})", abi.record(*i)), Type::Enum(i) => match abi.api.enums[*i].plain() { true => format!("{}.of({r}.i32())", self.qualified(&abi.enumeration(*i))), 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::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(); format!("{}({})", self.tuple_class(elements), read.join(", ")) } other => unreachable!("{other:?} is never decoded"), } } /// The Kotlin value of the JNI scalar or `byte[]` `e`, of IR type `ty` and C type `c`, /// which Rust returned or lent. A lent object is wrapped as lent, and lent bytes are a /// parameter's, copied; returned bytes cross as their owner, unless text. fn lift(&mut self, ty: &Type, c: &Ty, e: &str, lent: bool) -> String { match c { Ty::Void => e.to_string(), 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::Handle { name, .. } => { let class = self.qualified(name); let wrap = |h: &str| match lent { true => format!("{class}({h}, true)"), false => format!("{class}({h})"), }; match ty.base() { Type::Option(_) => format!("{e}.let {{ h -> if (h == 0L) null else {} }}", wrap("h")), _ => wrap(e), } } 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 (copied(ty), matches!(ty.base(), Type::Option(_)), lent) { (Some(true), true, _) => format!("{e}?.decodeToString()"), (Some(true), false, _) => format!("{e}!!.decodeToString()"), (Some(false), true, _) => format!("{e}?.let {{ {}.of(it) }}", self.own("PathBuf")), (Some(false), false, _) => format!("{}.of({e}!!)", self.own("PathBuf")), (None, true, true) => format!("{e}?.let {{ {}(it) }}", self.own("Bytes")), (None, false, true) => format!("{}({e}!!)", self.own("Bytes")), (None, true, false) => format!("_Native.owned({e})"), (None, false, false) => format!("_Native.owned({e})!!"), }, _ => { let r = self.fresh("r"); let read = self.read(&strip_refs(ty), &r, !lent); format!("_Native.__Reader({e}).let {{ {r} -> {read} }}") } } } /// The Kotlin expression passing `e` of type `ty` back to Rust as the C type `c`, as a /// callback or closure returns it: a scalar, a string's bytes, an opaque value's word /// or words, or any other value encoded. fn lower_ret(&mut self, c: &Ty, ty: &Type, e: &str) -> String { match c { Ty::Int(int) => to_signed(*int, e), Ty::Char => scalar_value(e), Ty::Buf if copied(ty) == Some(false) => format!("{e}.bytes"), Ty::Buf => format!("_utf8({e})"), 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); format!("_Native.__Writer().use {{ {w} -> {write}; {w}.finish() }}") } _ => e.to_string(), } } /// How Kotlin passes the value `e` of IR type `ty` as the C parameter `c`, named /// `name` in C, and how the glue takes it. `callback` names the parameter's closure /// trampoline, if one. fn arg(&mut self, ty: &Type, c: &Ty, e: &str, n: &mut usize, trampoline: Option<&str>) -> Arg { let abi = self.abi; let mut arg = Arg::default(); let p = format!("p{n}"); *n += 1; // A block crosses JNI as the primitive array of its width, copied in one call. if let (Ty::Struct(_), Some(inner)) = (c, ty.base().block()) { let b = block(inner); arg.jni.push(b.jni); arg.native.push(b.signed.to_string()); arg.exprs.push(b.signed(e)); arg.rust_pre .push(format!("let b{p} = rt::block::<{}>(env, {p});", b.rust)); arg.rust_args.push(format!("rt::list(&b{p})")); return arg; } let (jni, native) = jni_type(self.abi, c, ty); arg.jni.push(jni); arg.native.push(native.to_string()); match c { Ty::Bool => { arg.exprs.push(e.to_string()); arg.rust_args.push(p); } Ty::Int(int) => { let signed = to_signed(*int, e); arg.exprs.push(match ty.base() { Type::NonZero(_) => non_zero(&signed), _ => signed, }); arg.rust_args.push(from_jni(*int, &p)); } Ty::F32 | Ty::F64 => { arg.exprs.push(e.to_string()); arg.rust_args.push(p); } Ty::Char => { arg.exprs.push(scalar_value(e)); arg.rust_args.push(format!("{p} as u32")); } Ty::Enum(_) => { arg.exprs.push(format!("{e}.value")); arg.rust_args.push(p); } // A local reference, which the native call lends. Ty::Jni(_) => { arg.exprs.push(e.to_string()); arg.rust_args.push(format!("{p} as _")); } Ty::Handle { .. } => { let h = self.fresh("h"); let option = matches!(ty.base(), Type::Option(_)); arg.open = Some(match option { true => format!("_Native.hold({e}?.handle) {{ {h} ->"), false => format!("{e}.handle.hold {{ {h} ->"), }); // Taken by value, the value moves out, leaving the handle only to free. if moved(abi, ty) { arg.after.push(match option { true => format!("{e}?.handle?.abandon()"), false => format!("{e}.handle.abandon()"), }); } arg.exprs.push(h); arg.rust_args.push(format!("{p} as usize as _")); } // Text crosses as the `String`, encoded once into a buffer Rust takes, and a path // as its bytes, copied once. Ty::Buf if let Some(text) = copied(ty) => { let option = matches!(ty.base(), Type::Option(_)); match text { true => { *arg.jni.last_mut().expect("pushed above") = "jstring"; *arg.native.last_mut().expect("pushed above") = "String?".to_string(); arg.exprs.push(e.to_string()); arg.rust_check.push(format!( "let Some(b{p}) = rt::text(env, {p}) else {{\n\t\t\treturn rt::raised();\n\t\t}};" )); } false => { arg.exprs.push(match option { true => format!("{e}?.bytes"), false => format!("{e}.bytes"), }); arg.rust_pre.push(format!("let b{p} = rt::bytes(env, {p});")); } } arg.rust_args.push(format!("rt::buf(b{p})")); } // Bytes cross as what holds them, Rust's owner or 0, where they start, and how // many, or -1 for none: Rust takes a copy of Kotlin's, or shares its own. Ty::Buf => { arg.jni .splice(arg.jni.len() - 1.., ["jobject", "jlong", "jint", "jint"]); arg.native.splice( arg.native.len() - 1.., ["Any?", "Long", "Int", "Int"].map(str::to_string), ); let (q, r, s) = (format!("p{n}"), format!("p{}", *n + 1), format!("p{}", *n + 2)); *n += 3; arg.exprs.extend(match matches!(ty.base(), Type::Option(_)) { true => [ format!("{e}?.held"), format!("{e}?.owner ?: 0L"), format!("{e}?.start ?: 0"), format!("{e}?.size ?: -1"), ], false => [ format!("{e}.held"), format!("{e}.owner"), format!("{e}.start"), format!("{e}.size"), ], }); arg.rust_pre .push(format!("let b{p} = unsafe {{ rt::passed(env, {p}, {q}, {r}, {s}) }};")); arg.rust_args.push(format!("b{p}")); } Ty::Struct(name) if matches!(ty.base(), Type::Callback(..)) => { arg.exprs.push(e.to_string()); arg.rust_args.push(format!( "crate::{name} {{ vtable: &VTABLE_{name}, data: rt::global(env, {p}) }}" )); } // A record crosses as its scalars, and its other fields encoded into one `byte[]`; // an opaque value as the words Kotlin holds it in; an `Option` of either as whether // it is `Some`, then the value's, zero for `None`. 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 Some((i, option)) = direct_record(ty) && let Some(left) = self .room .checked_sub((weight(abi, i) + usize::from(option)).saturating_sub(c_slots(c))) => { self.room = left; arg.jni.clear(); arg.native.clear(); *n -= 1; let (w, r) = (self.fresh("w"), format!("r{p}")); // The encoded fields' writes can run Kotlin code, such as a custom `List`'s // iterator, before the scalars are read: a `Mut`'s value is read once, first. let raw = e; let held = rest(abi, i) && raw.contains('.'); let snap = match held { true => self.fresh("v"), false => raw.to_string(), }; let e = snap.as_str(); let mut writes = Vec::new(); let value = match option { false => self.flat_in(i, e, (&mut arg, n), (&w, &mut writes), &r), // Each of the value's scalars reads it through `o`, bound only when `Some`. true => { let some = format!("p{n}"); *n += 1; arg.jni.push("jboolean"); arg.native.push("Boolean".to_string()); arg.exprs.push(format!("{e} != null")); let o = self.fresh("o"); let start = arg.exprs.len(); let value = self.flat_in(i, &o, (&mut arg, n), (&w, &mut writes), &r); for (expr, native) in arg.exprs[start..].iter_mut().zip(&arg.native[start..]) { *expr = format!("({e}?.let {{ {o} -> {expr} }} ?: {})", zero(native)); } if !writes.is_empty() { writes = vec![format!("{e}?.let {{ {o} ->\n{}\n}}", writes.join("\n"))]; } let option = match c { Ty::In(inner) => inner, c => c, }; let Ty::Struct(option) = option else { unreachable!("an option crosses as its struct") }; format!( "crate::{option} {{ some: {some}, value: if {some} {{ {value} }} else {{ unsafe {{ std::mem::zeroed() }} }} }}" ) } }; if rest(abi, i) { // Then the arrays and text the rest names, which Rust copies from once. let (b, q) = (format!("p{n}"), format!("p{}", *n + 1)); *n += 2; arg.jni.extend(["jbyteArray", "jobjectArray"]); arg.native .extend(["ByteArray", "kotlin.Array?"].map(str::to_string)); arg.open = Some(format!("_Native.__Writer().use {{ {w} ->")); if held { arg.inside.push(format!("val {e} = {raw}")); } arg.inside.extend(writes); arg.exprs.push(format!("{w}.finish()")); arg.exprs.push(format!("{w}.refs()")); arg.rust_check.push(format!( "let b{p} = rt::bytes(env, {b}).unwrap_or_default();\n\t\tlet Some(mut {r}) = rt::Reader::{}(env, &b{p}, {q}) else {{\n\t\t\treturn rt::raised();\n\t\t}};", // Read through a pointer, Rust keeps nothing of it. match c { Ty::In(_) => "new", _ => "taking", } )); } arg.rust_pre.push(format!("let a{p} = {value};")); arg.rust_args.push(match c { Ty::In(_) => format!("&a{p}"), _ => format!("a{p}"), }); } Ty::U128 | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) | Ty::In(_) => { let w = self.fresh("w"); // Taken by value, each object in a list moves out, as one passed alone does. if moved(abi, ty) { let close = self.close(ty, e); arg.after.push(close); } 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. arg.jni.push("jobjectArray"); arg.native.push("kotlin.Array?".to_string()); let q = format!("p{n}"); *n += 1; arg.exprs.push(format!("{w}.finish()")); arg.exprs.push(format!("{w}.refs()")); arg.rust_check.push(format!( "let b{p} = rt::bytes(env, {p}).unwrap_or_default();\n\t\tlet Some(mut r{p}) = rt::Reader::{}(env, &b{p}, {q}) else {{\n\t\t\treturn rt::raised();\n\t\t}};", // Read through a pointer, Rust keeps nothing of it. match c { Ty::In(_) => "new", _ => "taking", } )); arg.rust_pre.push(format!("let a{p} = r{p}.get();")); arg.rust_args.push(match c { Ty::In(_) => format!("&a{p}"), _ => format!("a{p}"), }); } Ty::Fn(..) => { let trampoline = trampoline.expect("a closure has its trampoline"); arg.exprs.push(e.to_string()); arg.rust_args.push(format!("Some({trampoline})")); match ty { // Rust keeps it past the call, until it frees it, from any thread. Type::Closure(closure) if closure.kept => { arg.rust_args.push(format!("rt::global(env, {p})")); arg.rust_args.push("Some(rt::free_global)".to_string()); } _ => { arg.rust_pre.push(format!("let g{p} = rt::Global::new(env, {p});")); arg.rust_args.push(format!("g{p}.0")); } } } Ty::Waker => { arg.exprs.push(e.to_string()); arg.rust_args.push(format!("rt::waker(env, {p})")); } // Lent for the call, so held no longer. Ty::ForeignReader => { self.reads = true; arg.exprs.push(e.to_string()); arg.rust_pre.push(format!("let g{p} = rt::Global::new(env, {p});")); arg.rust_args.push(format!("rt::reader(g{p}.0)")); } // Run in the caller's context when it suspends, as Rust holds it no longer than the // call's future. Ty::ForeignFuture => { let context = match self.suspends { true => "_context()", false => "_noContext", }; arg.exprs.push(format!("_Native.__Pollable({e}, {context})")); arg.rust_args.push(format!("rt::future(env, {p})")); } // A value's `&mut self` is handed back, through `&self`. Ty::Void | Ty::Future(_) | Ty::Poll | Ty::Status | Ty::Out(_) | Ty::InOut(_) | Ty::Data => { unreachable!("{c:?} is no parameter Kotlin passes") } } arg } fn write(&mut self) { let abi = self.abi; let api = abi.api; if abi.ranges.values().any(|ty| matches!(ty, Type::Bound(_))) { self.types.push_str( "/** What a range's start or end bound does: nothing, include its value, or exclude it. */\nenum class Bound {\n\tUNBOUNDED,\n\tINCLUDED,\n\tEXCLUDED,\n}\n\n", ); } for (c, ty) in &abi.ranges.clone() { self.range(c, ty); } for c in abi.options.clone().keys() { self.glue_option(c); } for (c, elements) in &abi.tuples.clone() { self.glue_tuple(c, elements); } for (c, n) in &abi.arrays { let class = Abi::array_class(*n); let _ = write!( self.types, "/** A Rust `[u8; {n}]`: exactly {n} bytes, copied in and out, so it never changes. */\nclass {class}(bytes: ByteArray) {{\n\tinternal val bytes: ByteArray = bytes.copyOf()\n\n\tinit {{\n\t\tkotlin.require(bytes.size == {n}) {{ \"${{bytes.size}} bytes, not {n}\" }}\n\t}}\n\n\toperator fun get(index: Int): Byte = bytes[index]\n\n\tfun toByteArray(): ByteArray = bytes.copyOf()\n\n\toverride fun equals(other: Any?): Boolean = other is {class} && bytes.contentEquals(other.bytes)\n\n\toverride fun hashCode(): Int = bytes.contentHashCode()\n\n\toverride fun toString(): String = bytes.joinToString(\"\") {{ \"%02x\".format(it) }}\n}}\n\n" ); let _ = write!( self.glue, "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\tSelf {{ items: r.get() }}\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n\t\tw.put(self.items);\n\t}}\n}}\n\n" ); } for constant in &api.constants { let name = self.bare(&abi.name(&constant.path)).to_uppercase(); self.locked .insert(format!("const {}", constant.path.join("::")), name.clone()); let (ty, value) = match constant.value { Literal::Bool(b) => ("Boolean".to_string(), b.to_string()), Literal::Int(int, v) => (kt_int(int).to_string(), int_literal(int, v)), }; let _ = write!( self.top, "{}const val {name}: {ty} = {value}\n\n", docs(&constant.docs, "") ); } for i in 0..api.records.len() { self.record(i); } for i in 0..api.enums.len() { self.enumeration(i); } for i in 0..api.objects.len() { self.object(i); } for i in 0..api.callbacks.len() { self.callback(i); } let mut top = Vec::new(); for function in &api.functions { if let Some(code) = self.function(function, None, None, Place::Static, &[]) { top.push(code); } } for code in top { self.top.push_str(&code); self.top.push('\n'); } for (name, ty) in &self.exceptions.clone() { let kt = self.kt(ty); let message = match ty { Type::Str | Type::String => "error", _ => "error.toString()", }; let _ = write!( self.types, "/** A `{kt}` Rust returned as an error. */\nclass {name}(val error: {kt}) : Exception() {{\n\toverride val message: String\n\t\tget() = {message}\n}}\n\n" ); } } /// A Kotlin data class for a range, bound, or pair of bounds, and its codec. fn range(&mut self, c: &str, ty: &Type) { let name = self.class(c); let (fields, write, read) = match ty { Type::Range(int) => { let kt = kt_int(*int); let (m, _) = wire_int(*int); ( format!("val start: {kt}, val end: {kt}"), format!( "w.{m}({}); w.{m}({})", to_signed(*int, "v.start"), to_signed(*int, "v.end") ), format!( "{name}({}, {})", from_signed(*int, &format!("r.{m}()")), from_signed(*int, &format!("r.{m}()")) ), ) } Type::Bound(int) => { let kt = kt_int(*int); let (m, _) = wire_int(*int); ( format!("val kind: Bound, val value: {kt}"), format!("w.i32(v.kind.ordinal); w.{m}({})", to_signed(*int, "v.value")), format!( "{name}(Bound.entries[r.i32()], {})", from_signed(*int, &format!("r.{m}()")) ), ) } Type::Bounds(int) => { let bound = abi_bound(self.abi, *int); let class = self.class(&bound); ( format!("val start: {class}, val end: {class}"), format!("w_{bound}(w, v.start); w_{bound}(w, v.end)"), format!("{name}(r_{bound}(r), r_{bound}(r))"), ) } other => unreachable!("{other:?} is no range"), }; 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" ); } /// The glue's codec for an option struct. fn glue_option(&mut self, c: &str) { let _ = write!( self.glue, "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\tlet some: bool = r.get();\n\t\tSelf {{ some, value: if some {{ r.get() }} else {{ unsafe {{ std::mem::zeroed() }} }} }}\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n\t\tw.put(self.some);\n\t\tif self.some {{\n\t\t\tw.put(self.value);\n\t\t}}\n\t}}\n}}\n\n" ); } /// 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 /// it holds a handle. fn traits(&mut self, ty: &Type, c: &str, t: crate::ir::Traits, body: &mut Vec, statics: &mut Vec) { let class = self.qualified(c); let bare = self.bare(c).to_string(); let object = matches!(ty, Type::Object(_)); let opaque = match ty { 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 // words, or encoded, which the glue reads first. let mut pre = String::new(); let (params, open, arg, rust_self): (Vec<(&str, &str)>, _, _, _) = match (object, opaque) { (true, _) => ( vec![("jlong", "Long")], "handle.hold { h ->".to_string(), "h".to_string(), "p0 as usize as _".to_string(), ), (false, Some(opaque)) if fits(1) => { let words: Vec = (0..opaque.words()).map(|k| format!("p{k}")).collect(); ( vec![("jlong", "Long"); words.len()], "run {".to_string(), holders(&opaque).join(", "), format!("&{}", from_kotlin(&opaque, &words)), ) } (false, _) => { let write = self.write_value(ty, "w", "this"); pre = "let b = rt::bytes(env, p0).unwrap_or_default();\n\t\tlet Some(mut r) = rt::Reader::new(env, &b, p1) else {\n\t\t\treturn rt::raised();\n\t\t};\n\t\t".to_string(); ( vec![("jbyteArray", "ByteArray"), ("jobjectArray", "kotlin.Array?")], format!("_Native.__Writer().use {{ w ->\n\t\t{write}"), "w.finish(), w.refs()".to_string(), "&r.get()".to_string(), ) } }; // Each borrows its handles shared, throwing a failed check. let status = self.abi.traits_status_of(ty); let checked = |call: &str, name: &str, then: &str| match status { true => format!( "{pre}let mut status = 0;\n\t\tlet ret = {}, &mut status);\n\t\tif status != 0 {{\n\t\t\treturn rt::refuse(env, status, \"{name}\");\n\t\t}}\n\t\t{then}", call.strip_suffix(')').expect("a call") ), false => format!("{pre}let ret = {call};\n\t\t{then}"), }; let unary = |g: &mut Self, suffix: &str, sig: &str| { g.native( &format!("{bare}_{suffix}"), ¶ms, ("jbyteArray", "ByteArray?"), &checked( &format!("crate::{c}_{suffix}({rust_self})"), &format!("{c}_{suffix}"), "rt::owned(env, ret)", ), ); format!("\t{sig} = {open}\n\t\t_Native.{bare}_{suffix}({arg})!!.decodeToString()\n\t}}\n") }; // The hash agreeing with an `equals` through Rust's `PartialEq`: Rust's own `Hash`, // folded as `Long.hashCode` folds it, or else one for every value. let hash_code = |g: &mut Self| { if !t.hash { return "\t/** One for every value: Rust's `PartialEq` comes with no `Hash`. */\n\toverride fun hashCode(): kotlin.Int = 0\n".to_string(); } let call = format!("crate::{c}_hash({rust_self})"); let body = checked(&call, &format!("{c}_hash"), "ret as jlong"); g.native(&format!("{bare}_hash"), ¶ms, ("jlong", "Long"), &body); format!( "\t/** Rust's `Hash`, as `Long.hashCode` folds it. */\n\toverride fun hashCode(): kotlin.Int = {open}\n\t\t_Native.{bare}_hash({arg}).hashCode()\n\t}}\n" ) }; if t.display { // Final, so a data class variant of a sealed class keeps it rather than making // its own. body.push(unary(self, "to_string", "final override fun toString(): kotlin.String")); } if t.debug { body.push(unary( self, "debug", "/** Rust's `Debug` form. */\n\tfun debug(): kotlin.String", )); } if object && t.clone { self.native( &format!("{bare}_clone"), &[("jlong", "Long")], ("jlong", "Long"), &checked( &format!("crate::{c}_clone(p0 as usize as _)"), &format!("{c}_clone"), "ret as usize as jlong", ), ); body.push(format!( "\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; any // other through Rust, passing both values' words, or both encoded. if let Some(opaque) = opaque.filter(|opaque| t.eq && !word(opaque)) { 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 Some(mut r) = rt::Reader::new(env, &b, p1) else { return rt::raised() }; 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); let hash = hash_code(self); body.push(format!( "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {class} && {kt}\n\n{hash}" )); } if object && t.eq { self.native( &format!("{bare}_eq"), &[("jlong", "Long"), ("jlong", "Long")], ("jboolean", "Boolean"), &checked( &format!("crate::{c}_eq(p0 as usize as _, p1 as usize as _)"), &format!("{c}_eq"), "ret", ), ); let hash = hash_code(self); body.push(format!( "\toverride fun equals(other: kotlin.Any?): kotlin.Boolean =\n\t\tother is {class} && handle.hold {{ a -> other.handle.hold {{ b -> _Native.{bare}_eq(a, b) }} }}\n\n{hash}" )); } if t.default { let (jni, native, rust, lift) = match ty { Type::Object(_) => ( "jlong", "Long", format!("crate::{c}_default() as usize as jlong"), format!("{class}(_Native.{bare}_default())"), ), Type::Enum(i) if self.abi.api.enums[*i].plain() => ( "jint", "Int", format!("crate::{c}_default()"), format!("{class}.of(_Native.{bare}_default())"), ), _ => ( "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.native(&format!("{bare}_default"), &[], (jni, native), &rust); statics.push(format!( "\t\t/** Rust's `Default`. */\n\t\tfun default(): {class} = {lift}\n" )); } } fn record(&mut self, i: usize) { let abi = self.abi; let record = &abi.api.records[i]; self.on = record.on; let c = abi.record(i); let name = self.class(&c); let rust = abi.api.rust(&record.path, &record.args); let ty = Type::Record(i); let fields: Vec<(String, String)> = record .fields .iter() .map(|f| (field_name(&f.name), self.kt(&f.ty))) .collect(); let mut body = Vec::new(); let mut statics = Vec::new(); 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.extend(holders(&opaque).iter().map(|h| format!("val {h}"))); } let owner = Ty::Struct(c.clone()); for method in &record.methods { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, }; // What the type declares before it, which its name keeps apart from. let taken: Vec = match place { Place::Member => (members.iter().cloned()) .chain(body.iter().filter_map(|b| member_name(b))) .collect(), Place::Static => statics.iter().filter_map(|s| member_name(s)).collect(), }; if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), } } } // A data class compares arrays by identity and floats by their bits, and Rust both by IEEE `==`. if record.fields.iter().any(|f| self.by_contents(&f.ty)) { let fields: Vec = fields.iter().map(|(f, _)| f.clone()).collect(); body.push(Self::contents(&name, &fields)); } members.extend(body.iter().filter_map(|b| member_name(b))); self.distinct(&rust, &members); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } let docs = docs(&record.docs, ""); let body = match body.is_empty() { true => String::new(), false => format!(" {{\n{}}}", body.join("\n")), }; if let Some(opaque) = record.opaque { self.opaque(&c, &name, &opaque, &docs, &body); return; } match fields.is_empty() { true => { let _ = write!( self.types, "{docs}class {name} {}\n\n", match body.is_empty() { true => format!( "{{\n\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {name}\n\n\toverride fun hashCode(): kotlin.Int = 0\n}}" ), false => body.replacen( " {\n", &format!( " {{\n\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {name}\n\n\toverride fun hashCode(): kotlin.Int = 0\n\n" ), 1 ), } ); } false => { let params: Vec = fields .iter() .zip(&record.fields) .map(|((f, kt), field)| format!("{}\tval {f}: {kt},", docs_inline(&field.docs, "\t"))) .collect(); let _ = write!( self.types, "{docs}data class {name}(\n{}\n){body}\n\n", params.join("\n") ); } } // The codec. let writes: Vec = record .fields .iter() .map(|f| { let e = format!("v.{}", field_name(&f.name)); self.write_value(&f.ty, "w", &e) }) .collect(); 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", writes.iter().map(|w| format!("\t{w}\n")).collect::(), reads.join(", ") ); let fields: Vec = (0..record.fields.len()).map(|n| format!("f{n}: r.get()")).collect(); let puts: String = record .fields .iter() .enumerate() .map(|(n, f)| format!("\t\t{};\n", put(&f.ty, &format!("self.f{n}")))) .collect(); let _ = write!( self.glue, "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\tlet _ = &r;\n\t\tSelf {{ {} }}\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n\t\tlet _ = &w;\n{puts}\t}}\n}}\n\n", fields.join(", ") ); } /// 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 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 holders = holders(opaque); // 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!("\t@kotlin.jvm.JvmField internal var {h}: Long = 0L\n")) .collect(); 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 = self.made(name, opaque, &vec!["r.i64()".to_string(); holders.len()]); 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" ); let _ = write!( self.glue, "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\trt::read_words::<_, {words}>(r)\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n\t\trt::write_words::<_, {words}>(w, self);\n\t}}\n}}\n\n" ); } /// 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(); // 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) { let abi = self.abi; let e = &abi.api.enums[i]; self.on = e.on; let c = abi.enumeration(i); let name = self.class(&c); let rust = abi.api.rust(&e.path, &e.args); let ty = Type::Enum(i); let mut body = Vec::new(); let mut statics = Vec::new(); self.traits(&ty, &c, e.traits, &mut body, &mut statics); let owner = abi.ty(&ty); for method in &e.methods { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, }; // What the type declares before it, which its name keeps apart from. let taken: Vec = match place { Place::Member => body.iter().filter_map(|b| member_name(b)).collect(), Place::Static => statics.iter().filter_map(|s| member_name(s)).collect(), }; if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), } } } let mut members: Vec = body.iter().filter_map(|b| member_name(b)).collect(); if e.plain() { members.push("fun of".to_string()); members.push("val value".to_string()); self.distinct(&rust, &members); // An entry the library's target lacks is refused as it crosses, when its value is read. let entries: Vec = (e.variants.iter()) .map(|v| { let entry = abi::snake(&v.name).to_uppercase(); match abi.api.everywhere(v.on) { true => format!("\t{entry}({}),", v.discriminant), false => format!( "\t{entry}({}) {{\n\t\toverride val value: Int\n\t\t\tget() = super.value.also {{ _Native.check({}uL, \"{c}.{}\") }}\n\t}},", v.discriminant, v.on.0 & abi.api.all().0, v.name ), } }) .collect(); let open = match e.variants.iter().all(|v| abi.api.everywhere(v.on)) { true => "", false => "open ", }; let cases: Vec = e .variants .iter() .map(|v| format!("\t\t\t{} -> {}", v.discriminant, abi::snake(&v.name).to_uppercase())) .collect(); statics.push(format!( "\t\tinternal fun of(value: Int): {name} = when (value) {{\n{}\n\t\t\telse -> error(\"{c}: an invalid value\")\n\t\t}}\n", cases.join("\n") )); let entries = entries.join("\n"); let entries = entries.strip_suffix(',').unwrap_or(&entries); let _ = write!( self.types, "{}enum class {name}(internal {open}val value: Int) {{\n{entries};\n\n{}\tcompanion object {{\n{}\t}}\n}}\n\n", docs(&e.docs, ""), body.iter().map(|b| format!("{b}\n")).collect::(), statics.join("\n") ); return; } let mut variants = Vec::new(); let mut writes = Vec::new(); let mut reads = Vec::new(); let mut glue_reads = Vec::new(); let mut glue_writes = Vec::new(); for (n, variant) in e.variants.iter().enumerate() { let vname = pascal(&variant.name); members.push(format!("class {vname}")); let fields: Vec = variant .fields .iter() .map(|f| format!("val {}: {}", field_name(&f.name), self.kt(&f.ty))) .collect(); let mut write = vec![format!("w.i32({n})")]; // A value of a variant the library's target lacks is refused as it crosses. if !abi.api.everywhere(variant.on) { let on = variant.on.0 & abi.api.all().0; write.insert(0, format!("_Native.check({on}uL, \"{c}.{}\")", variant.name)); } for f in &variant.fields { let e = format!("v.{}", field_name(&f.name)); write.push(self.write_value(&f.ty, "w", &e)); } let read: Vec = variant.fields.iter().map(|f| self.read_value(&f.ty, "r")).collect(); match variant.fields.is_empty() { true => { variants.push(format!("\tdata object {vname} : {name}()\n")); writes.push(format!("\t\t{name}.{vname} -> {}", write.join("\n\t\t"))); reads.push(format!("\t\t{n} -> {name}.{vname}")); glue_reads.push(format!( "\t\t\t{n} => Self {{ tag, u: unsafe {{ std::mem::zeroed() }} }}," )); } false => { let body = match variant.fields.iter().any(|f| self.by_contents(&f.ty)) { true => { let names: Vec = variant.fields.iter().map(|f| field_name(&f.name)).collect(); format!(" {{\n{}\t}}", indent(&Self::contents(&vname, &names))) } false => String::new(), }; variants.push(format!( "\tdata class {vname}({}) : {name}(){body}\n", fields.join(", ") )); writes.push(format!( "\t\tis {name}.{vname} -> {{\n\t\t\t{}\n\t\t}}", write.join("\n\t\t\t") )); reads.push(format!("\t\t{n} -> {name}.{vname}({})", read.join(", "))); let payload = abi::payload(&c, &variant.name); let fields: Vec = (0..variant.fields.len()).map(|k| format!("f{k}: r.get()")).collect(); glue_reads.push(format!( "\t\t\t{n} => Self {{ tag, u: crate::{c}_union {{ v{n}: crate::{payload} {{ {} }} }} }},", fields.join(", ") )); let puts: Vec = variant .fields .iter() .enumerate() .map(|(k, f)| format!("{};", put(&f.ty, &format!("p.f{k}")))) .collect(); glue_writes.push(format!( "\t\t\t{n} => {{\n\t\t\t\tlet p = unsafe {{ self.u.v{n} }};\n\t\t\t\t{}\n\t\t\t}}", puts.join("\n\t\t\t\t") )); } } } self.distinct(&rust, &members); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } let mut all = variants; all.extend(body); let _ = write!( self.types, "{}sealed class {name} {{\n{}}}\n\n", docs(&e.docs, ""), all.join("\n") ); 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", writes.join("\n"), reads.join("\n").replace("\t\t", "\t") ); let _ = write!( self.glue, "impl Wire for crate::{c} {{\n\tfn read(r: &mut Reader<'_>) -> Self {{\n\t\tlet tag: i32 = r.get();\n\t\tmatch tag {{\n{}\n\t\t\t_ => crate::rt::fail(\"jni\", \"an enum's tag is invalid\"),\n\t\t}}\n\t}}\n\n\tfn write(self, w: &mut Writer) {{\n\t\tw.put(self.tag);\n\t\tmatch self.tag {{\n{}\n\t\t\t_ => {{}}\n\t\t}}\n\t}}\n}}\n\n", glue_reads.join("\n"), glue_writes.join("\n") ); } fn object(&mut self, i: usize) { let abi = self.abi; let object = &abi.api.objects[i]; self.on = object.on; let c = abi.object(i); let name = self.class(&c); let bare = self.bare(&c).to_string(); let rust = abi.api.rust(&object.path, &object.args); let ty = Type::Object(i); self.native( &format!("{bare}_free"), &[("jlong", "Long")], ("()", "Unit"), &format!("crate::{c}_free(p0 as usize as _)"), ); let mut body = vec![match abi.checked[i] { true => { self.native( &format!("{bare}_drop"), &[("jlong", "Long")], ("()", "Unit"), &format!( "let mut status = 0;\n\t\tcrate::{c}_drop(p0 as usize as _, &mut status);\n\t\tif status != 0 {{\n\t\t\treturn rt::refuse(env, status, \"{c}_drop\");\n\t\t}}" ), ); format!( "\tinternal val handle = _Native.__Handle(this, raw, if (lent) null else _Native.__Drop {{ _Native.{bare}_free(it) }}, \"{name}\", if (lent) null else _Native.__Close {{ _Native.{bare}_drop(it) }})\n\n\t/** Drop the value now, as Rust's drop does, and free the handle once no call holds it: a call after this throws, and one still borrowing the value makes this throw. */\n\toverride fun close() = handle.close()\n" ) } false => 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 now: a call after this throws, and one still running makes this throw. */\n\toverride fun close() = handle.close()\n" ), }]; let mut statics = Vec::new(); self.traits(&ty, &c, object.traits, &mut body, &mut statics); let owner = Ty::Handle { name: c.clone(), constant: false, }; for method in &object.methods { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, }; // What the type declares before it, which its name keeps apart from. let taken: Vec = match place { Place::Member => body.iter().filter_map(|b| member_name(b)).collect(), Place::Static => statics.iter().filter_map(|s| member_name(s)).collect(), }; if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), } } } let mut members: Vec = body.iter().filter_map(|b| member_name(b)).collect(); members.extend(statics.iter().filter_map(|s| member_name(s))); self.distinct(&rust, &members); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } let text = format!("{rust}\n\n{}", object.docs); let _ = write!( self.types, "{}class {name} internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable {{\n{}}}\n\n", docs(text.trim(), ""), body.join("\n") ); } fn callback(&mut self, i: usize) { let abi = self.abi; let callback = &abi.api.callbacks[i]; self.on = callback.on; let c = abi.callback(i); let name = self.class(&c); let bare = self.bare(&c).to_string(); let rust = callback.path.join("::"); let mut body = Vec::new(); let mut table = vec!["free: Some(rt::free_callback)".to_string()]; let mut members = Vec::new(); for (n, method) in callback.methods.iter().enumerate() { let member = member(&abi::snake(method.name()), &[]); crate::lock::function(&mut self.locked, method, &member); members.push(format!("fun {member}")); let params: Vec = (method.params.iter().zip(locals(&method.params))) .map(|(p, name)| format!("{name}: {}", self.kt_param(&p.ty))) .collect(); let ret = self.kt(&method.ok); body.push(format!( "{}\tfun {member}({}){}", docs(&method.docs, "\t"), params.join(", "), match method.ok { Type::Unit => String::new(), _ => format!(": {ret}"), } )); let c_params: Vec = method.params.iter().map(|p| abi.ty(&p.ty)).collect(); let c_ret = abi.ty(&method.ok); let lent: Vec = method.params.iter().map(|p| p.ty.clone()).collect(); let dispatcher = format!("{bare}__{}", abi::snake(method.name())); let trampoline = format!("kt_{c}_{n}"); self.trampoline( &trampoline, &dispatcher, &format!("{rust}::{}", method.name()), (&lent, &method.ok, None), (&c_params, &c_ret), (&name, Some(&member)), ); table.push(format!("{}: Some({trampoline})", method.name())); } self.distinct(&rust, &members); let text = format!( "{rust}: implemented in Kotlin. Rust calls its methods from any thread, and once it\ndrops the implementation, closes it if it is `AutoCloseable`.\n\n{}", callback.docs ); let _ = write!( self.types, "{}interface {name} {{\n{}\n}}\n\n", docs(text.trim(), ""), body.join("\n\n") ); let _ = write!( self.glue, "static VTABLE_{c}: crate::{c}_vtable = crate::{c}_vtable {{ {} }};\n\n", table.join(", ") ); } /// The Rust function C calls for a callback's method or a closure, named `trampoline`, /// which calls the Kotlin dispatcher `dispatcher` with the Kotlin value Rust holds: /// for a callback, an implementation of the interface `cast` whose method `method` it /// calls, and for a closure, a value of the function type `cast`. A closure returning a /// `Result` fails by throwing the exception `thrown`, whose error the glue writes /// through C's last out pointer, after the one its value goes through. fn trampoline( &mut self, trampoline: &str, dispatcher: &str, what: &str, (lent, ret, thrown): (&[Type], &Type, Option<&str>), (c_params, c_ret): (&[Ty], &Ty), (cast, method): (&str, Option<&str>), ) { self.dispatchers.push(dispatcher.to_string()); let mut rust_params = vec!["data: *mut c_void".to_string()]; let mut jvalues = vec!["jvalue { l: data.cast() }".to_string()]; let mut kt_params = vec!["o: Any".to_string()]; let mut sig = String::from("(Ljava/lang/Object;"); let mut pre = Vec::new(); let mut args = Vec::new(); let mut finally = Vec::new(); for (k, (ty, c)) in lent.iter().zip(c_params).enumerate() { let rust_ty = rust_c(self.abi, c); rust_params.push(format!("p{k}: {rust_ty}")); let (jni, native) = jni_type(self.abi, c, ty); sig.push_str(descriptor(jni)); kt_params.push(format!("p{k}: {native}")); let (field, value) = match c { Ty::Bool => ("z", format!("p{k}")), Ty::Int(int) => (jvalue_field(jni), format!("p{k} as {}", jni_int(*int))), Ty::F32 => ("f", format!("p{k}")), Ty::F64 => ("d", format!("p{k}")), Ty::Char => ("i", format!("p{k} as jint")), 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) => { ("j", to_kotlin(&opaque, &format!("p{k}"), 0)) } _ => ( "l", format!("{{ let mut w = rt::Writer::default(); w.put(p{k}); w.array(env) }}"), ), }; jvalues.push(format!("jvalue {{ {field}: {value} }}")); match c { Ty::Handle { .. } => { let l = format!("l{k}"); let lifted = self.lift(ty, c, &format!("p{k}"), true); pre.push(format!("val {l} = {lifted}")); finally.push(format!("{l}.handle.end()")); args.push(l); } _ => args.push(self.lift(ty, c, &format!("p{k}"), true)), } } sig.push(')'); // A `Result` returns whether it is ok, writing its value and its error through the // out pointers after the parameters. let outs = &c_params[lent.len()..]; for (k, c) in outs.iter().enumerate() { rust_params.push(format!("o{k}: {}", rust_c(self.abi, c))); } let c_ok = match (thrown, outs) { (None, _) => c_ret.clone(), (Some(_), [Ty::Out(ok), _]) => (**ok).clone(), (Some(_), _) => Ty::Void, }; let (ret_jni, ret_native) = jni_type(self.abi, &c_ok, ret); sig.push_str(descriptor(ret_jni)); let call_kind = call_method(ret_jni); let rust_ret = rust_c(self.abi, c_ret); let back = match &c_ok { Ty::Void => String::new(), Ty::Bool => "ret".to_string(), Ty::Int(int) => from_jni(*int, "ret"), Ty::F32 | Ty::F64 => "ret".to_string(), 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) => { 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::plain(&rt::bytes(env, ret).unwrap_or_default()).get()".to_string(), _ => unreachable!("a callback or closure returns no {c_ok:?}"), }; let back = match thrown { None => back, Some(_) => { let err = outs.len() - 1; let ok = match c_ok { Ty::Void => String::new(), _ => format!("unsafe {{ o0.write({back}) }};\n\t\t"), }; format!( "if let Some(error) = rt::thrown(env, \"{what}\") {{\n\t\t\tunsafe {{ o{err}.write(crate::rt::Buf::vec(error)) }};\n\t\t\treturn false;\n\t\t}}\n\t\t{ok}true" ) } }; let invoke = format!( "let ret = unsafe {{ ((**env).v1_2.CallStatic{call_kind}MethodA)(env, rt::class(), id, args.as_ptr()) }};" ); let _ = write!( self.glue, "static M_{trampoline}: std::sync::OnceLock = std::sync::OnceLock::new();\n\nunsafe extern \"C\" fn {trampoline}({}) -> {rust_ret} {{\n\trt::upcall(\"{what}\", |env| {{\n\t\tlet id = rt::method(env, &M_{trampoline}, c\"{dispatcher}\", c\"{sig}\");\n\t\tlet args = [{}];\n\t\t{invoke}\n\t\tlet _ = &ret;\n\t\t{back}\n\t}})\n}}\n\n", rust_params.join(", "), jvalues.join(", ") ); if thrown.is_some() { self.fails = true; } let call = match method { Some(method) => format!("o.{method}"), None => "o".to_string(), }; let result = format!("{call}({})", args.join(", ")); let lowered = self.lower_ret(&c_ok, ret, &result); let ret_decl = match c_ok { Ty::Void => String::new(), _ => format!(": {ret_native}"), }; // 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@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}"), false => format!( "{cast_line}\t\t{}\n\t\ttry {{\n\t\t\treturn {lowered}\n\t\t}} finally {{\n\t\t\t{}\n\t\t}}", pre.join("\n\t\t"), finally.join("\n\t\t\t") ), }; let body = match c_ok { Ty::Void => body.replacen("return ", "", 1), _ => body, }; let _ = write!( self.natives, "\t@kotlin.jvm.JvmStatic private fun {dispatcher}({}){ret_decl} {{\n{body}\n\t}}\n\n", kt_params.join(", ") ); } /// A native method `bare`, taking `params` and returning `ret` (JNI type, Kotlin /// type), whose glue runs `body` with each parameter named `p0`, `p1`, ... /// `code`, which closes moved arguments however the call ends, behind the check that /// refuses a call off its target, so a refused call leaves them open. fn refused_first(&self, bare: &str, code: String) -> String { let api = self.abi.api; match api.everywhere(self.on) { true => code, false => format!( "run {{\n\t_Native.check({}uL, \"{}_{bare}\")\n{}\n}}", self.on.0 & api.all().0, self.abi.prefix, indent_by(&code, 1) ), } } fn native(&mut self, bare: &str, params: &[(&str, &str)], ret: (&str, &str), body: &str) { let kt: Vec = params .iter() .enumerate() .map(|(n, (_, k))| format!("p{n}: {k}")) .collect(); // On a target its item is not on, the native method throws before it calls in. let api = self.abi.api; let external = match api.everywhere(self.on) { true => bare.to_string(), false => { let external = format!("{bare}__on"); let args: Vec = (0..params.len()).map(|n| format!("p{n}")).collect(); let _ = write!( self.natives, "\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, self.abi.prefix, args.join(", ") ); external } }; let bare = external.as_str(); let _ = write!( self.natives, "\t@kotlin.jvm.JvmStatic external fun {bare}({}): {}\n\n", kt.join(", "), ret.1 ); let rust: Vec = params .iter() .enumerate() .map(|(n, (j, _))| format!("p{n}: {j}")) .collect(); let mut all = vec!["env: *mut JNIEnv".to_string(), "_: jclass".to_string()]; all.extend(rust); let _ = write!( self.glue, "#[unsafe(no_mangle)]\npub unsafe extern \"system\" fn Java_{}__1Native_{}({}) -> {} {{\n\tlet _ = env;\n\tunsafe {{\n\t\t{body}\n\t}}\n}}\n\n", mangle(&self.abi.prefix), mangle(bare), all.join(", "), ret.0 ); } /// The exception Kotlin throws for an error of type `e`, declared once. fn exception(&mut self, e: &Type) -> String { let kt = self.kt(e); if let Some(name) = self.thrown.get(&kt) { self.locked.insert(crate::lock::error_key(self.abi, e), name.clone()); return name.clone(); } // Named by the type as it reads unqualified, so qualifying it renames no exception. let bare = self.unqualified(&kt); let name = format!("{}Exception", bare.replace(['?', '<', '>', ',', ' ', '.'], "")); let name = self.claim(&name, format!("the exception of `{kt}`")); self.locked.insert(crate::lock::error_key(self.abi, e), name.clone()); self.exceptions.insert(name.clone(), e.clone()); self.thrown.insert(kt, name.clone()); name } /// Check that no two members of the type `rust` share a Kotlin name. fn distinct(&mut self, rust: &str, members: &[String]) { let mut seen = BTreeSet::new(); for member in members { if !seen.insert(member) { let name = member.split(' ').next_back().unwrap_or(member); self.errors.push(format!( "two members of `{rust}` are both `{name}` in Kotlin, which rust2-ffi should keep apart" )); } } } /// `function`'s Kotlin form, a member of `owner` (whose IR type is `owner_ty`) if it /// has one, apart from the members `taken` names, with its native methods and glue. fn function( &mut self, function: &Function, owner: Option<&Ty>, owner_ty: Option<&Type>, place: Place, taken: &[String], ) -> Option { let on = std::mem::replace(&mut self.on, function.on); let code = self.function_on(function, owner, owner_ty, place, taken); self.on = on; code } fn function_on( &mut self, function: &Function, owner: Option<&Ty>, owner_ty: Option<&Type>, place: Place, taken: &[String], ) -> Option { let abi = self.abi; // A value is immutable in Kotlin, so its `&mut self` method returns it as the call // left it, calling the C function in place on a copy it hands back. let handed = (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); let (back, export, handed) = match handed { Some((back, export, handed)) => (Some(back), export, Some(handed)), None => (None, abi.export(function, owner), None), }; let function = back.as_ref().unwrap_or(function); self.params = locals(&function.params); let written = function .params .iter() .any(|p| matches!(&p.ty, Type::Ref(..)) && p.ty.written()); self.room = room( export.call.params.iter().map(|(_, c)| c_slots(c)).sum(), export.future.is_some(), written, ); let c_name = export.call.name.clone(); let bare = self.bare(&c_name).to_string(); let owner_c = match owner { Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), _ => None, }; let own = match &owner_c { Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), None => None, }; let reserved: &[&str] = match owner_ty { Some(Type::Object(_)) => &["close", "equals", "hashCode", "toString", "handle"], Some(Type::Record(_)) => &["copy", "equals", "hashCode", "toString"], // A plain enum is a Kotlin enum, which has its own. Some(Type::Enum(i)) if abi.api.enums[*i].plain() => &[ "equals", "hashCode", "toString", "of", "value", "name", "ordinal", "compareTo", ], Some(_) => &["equals", "hashCode", "toString"], None => &[], }; // Named as Rust's path is, whatever C's clashes rename. let named = self.bare(&export.named).to_string(); let snake = own.unwrap_or(&named); let member = member(snake, reserved); let mut n = 0; let mut args: Vec = Vec::new(); let mut c_params = export.call.params.iter(); self.suspends = export.future.is_some(); let receiver = function.receiver.filter(|_| owner.is_some()); if let Some(receiver) = receiver { let (_, c) = c_params.next().expect("a method has its receiver"); let ty = owner_ty.expect("a method has its type").clone(); let arg = match c { Ty::Handle { .. } => { let mut arg = Arg::default(); let p = format!("p{n}"); n += 1; arg.jni.push("jlong"); arg.native.push("Long".to_string()); // Qualified, and named fresh, apart from the parameters in scope. let h = self.fresh("h"); arg.open = Some(format!("this.handle.hold {{ {h} ->")); arg.exprs.push(h); arg.rust_args.push(format!("{p} as usize as _")); let copy = matches!(ty, Type::Object(i) if abi.api.objects[i].copy); if receiver == Receiver::Owned && !copy { arg.after.push("this.handle.abandon()".to_string()); } arg } _ => self.arg(&ty, c, "this", &mut n, None), }; args.push(arg); } let mut kt_params = Vec::new(); let mut closures = Vec::new(); let names = self.params.clone(); // Each parameter Rust writes back, by its Kotlin name, and what it holds. let mut written: Vec<(String, Type)> = Vec::new(); for (param, name) in function.params.iter().zip(&names) { let (_, c) = c_params.next().expect("each parameter has its C one"); // The env of the thread calling, which JNI passes the native method. if param.ty == Type::Jni(Jni::Env) { args.push(Arg { rust_args: vec!["env as _".to_string()], ..Arg::default() }); continue; } kt_params.push(format!("{name}: {}", self.kt_param(¶m.ty))); let trampoline = match (¶m.ty, c) { (Type::Closure(closure), Ty::Fn(..)) => { c_params.next().expect("a closure has its data"); if closure.kept { c_params.next().expect("a kept closure has its free"); } let t = format!("kt_{c_name}_{}", abi::escape(¶m.name)); closures.push((param, c.clone(), t.clone())); Some(t) } _ => None, }; match ¶m.ty { Type::Ref(_, inner) if param.ty.written() => { written.push((name.clone(), (**inner).clone())); args.push(self.arg(inner, c, &format!("{name}.value"), &mut n, None)); } _ => args.push(self.arg(¶m.ty, c, name, &mut n, trampoline.as_deref())), } } for (param, c, trampoline) in closures { let (Type::Closure(closure_), Ty::Fn(c_lent, c_ret)) = (¶m.ty, &c) else { unreachable!() }; let (lent, ret) = (&closure_.params, &closure_.ok); let kt = self.kt(¶m.ty); let dispatcher = format!("{bare}__{}", abi::snake(¶m.name)); // Its error is the exception Kotlin throws for a function's `String` one. let thrown = closure_.err.as_ref().map(|err| self.exception(err)); self.trampoline( &trampoline, &dispatcher, &c_name, (lent, ret, thrown.as_deref()), (c_lent, c_ret), (&kt, None), ); } let outs: Vec<(String, Ty)> = c_params.filter(|(_, ty)| !abi::is_status(ty)).cloned().collect(); // A failed check writes its status, which the glue throws once the call returns. let status = export.call.status().is_some(); let check = match status { true => format!("\n\t\tif status != 0 {{\n\t\t\treturn rt::refuse(env, status, \"{c_name}\");\n\t\t}}"), false => String::new(), }; let native_params: Vec<(&str, String)> = args .iter() .flat_map(|a| a.jni.iter().copied().zip(a.native.iter().cloned())) .collect(); let mut exprs: Vec = args.iter().flat_map(|a| a.exprs.clone()).collect(); // A future's call also takes the signal its waker parks, if its first poll pends. let signal = export.future.is_some().then(|| self.fresh("s")); exprs.extend(signal.clone()); let mut rust_pre: Vec = (args.iter().flat_map(|a| &a.rust_check)) .chain(args.iter().flat_map(|a| &a.rust_pre)) .cloned() .collect(); if status { rust_pre.push("let mut status = 0;".to_string()); } 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 crosses as its element, written through its one out // pointer, and is wrapped back into the tuple class its parameters take; one behind a // reference or `Box` is returned as a struct, so crosses as a tuple. let single = match &function.ok { Type::Tuple(elements) if elements.len() == 1 => Some(self.tuple_class(elements)), _ => None, }; 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(&strip_refs(&function.ok)); // What crosses: a tuple of one's element, before it is wrapped. let ok_kt = self.kt(&ok); 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; 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 => direct_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)| { let (a, r) = (self.fresh("a"), self.fresh("r")); let (mut slots, mut puts) = (Vec::new(), Vec::new()); let v = match option { true => "ret.value", false => "ret", }; let make = self.flat_out(i, v, (&a, &mut slots), (&r, &mut puts)); if !slots.is_empty() { exprs.push(a.clone()); self.slots = self.slots.max(slots.len()); } Flat { option, a, r, slots, puts, make, } }); // The native call, closing what it moves out once it returns. let call = match after.is_empty() { true => format!("_Native.{bare}({})", exprs.join(", ")), false => format!("_Native.{bare}({}).also {{ {} }}", exprs.join(", "), after.join("; ")), }; // The value the function returns, or, returning nothing, its statement. let value; // The C call, with the out pointers after its arguments. let status_arg = status.then(|| "&mut status".to_string()); // A future that is not `Send` made from none is made on a home, so a coroutine that // resumes on another thread still polls it there. let made = match (&export.future, export.homed_call()) { (Some(_), Some(homed)) => homed.name, _ => c_name.clone(), }; let rust_call = |outs: &[String]| { let args: Vec = rust_args.iter().chain(outs).chain(&status_arg).cloned().collect(); let call = match &handed { Some(h) => h.call(&args), None => format!("crate::{made}({})", args.join(", ")), }; // An exception the Rust left pending, which the C function dropped its result // for, is thrown once the native method returns with nothing else done. match function.jni() { true => format!("{{ let ret = {call}; if rt::pending(env) {{ return std::mem::zeroed(); }} ret }}"), false => call, } }; if let Some(abi::Future { poll, free, .. }) = &export.future { // The call makes the future and polls it once, returning its result if ready, or // else the future, which a native poll and free take. let poll_bare = self.bare(&poll.name).to_string(); let free_bare = self.bare(&free.name).to_string(); // A future that is not `Send` takes a status its poll writes on another thread. let ps = match poll.status() { Some(_) => ", ps", None => "", }; let poll_outs: Vec<(String, Ty)> = poll.params[2..] .iter() .filter(|(_, ty)| *ty != Ty::Out(Box::new(Ty::Status))) .cloned() .collect(); let (decl, ptrs, write) = self.glue_outs(&poll_outs, &[], &function.ok, function.err.as_ref()); let ok_set = match function.err.is_some() { true => "let ok = ret == 1;\n\t", false => "", }; let _ = write!( self.glue, "unsafe fn jni_{}(f: *mut c_void, waker: crate::rt::Waker, w: &mut rt::Writer, ps: &mut i32) -> bool {{\n\tlet _ = (&w, &ps);\n\tunsafe {{\n\t{decl}\n\tlet ret = crate::{}(f as _, waker{}{ps});\n\tif ret == 0 {{\n\t\treturn false;\n\t}}\n\t{ok_set}{write}\n\ttrue\n\t}}\n}}\n\nunsafe fn jni_{}(f: *mut c_void) {{\n\tunsafe {{ crate::{}(f as _) }}\n}}\n\n", poll.name, poll.name, ptrs.iter().map(|p| format!(", {p}")).collect::(), free.name, free.name, ); let mut params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); params.push(("jobject", "Waker")); let p_signal = format!("p{}", params.len() - 1); let start_factory = format!("{bare}__return"); let poll_factory = format!("{poll_bare}__return"); for (factory, pending) in [(&start_factory, true), (&poll_factory, false)] { self.dispatchers.push(factory.clone()); let mut lines = self.lift_result(&ok, err.as_ref(), exception.as_deref(), "r"); if ok == Type::Unit { lines.push("Unit".to_string()); } let last = lines.pop().expect("a future has a value"); let pending = if pending { "if (!r.bool()) return __Pending(r.i64(), r.i64())" } else { "" }; let _ = write!( self.natives, "\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::() ); } self.native(&bare, ¶ms, ("jobject", "Any?"), &format!( "{}\n\t\tlet f = {};{check}\n\t\tlet Some(w) = rt::start(env, f.cast(), {p_signal}, jni_{}, jni_{}, \"{}\") else {{ return std::ptr::null_mut() }};\n\t\tstatic FACTORY: std::sync::OnceLock = std::sync::OnceLock::new();\n\t\tw.value(env, &FACTORY, c\"{start_factory}\", std::ptr::null_mut())", rust_pre.join("\n\t\t"), rust_call(&[]), poll.name, free.name, poll.name)); self.native(&poll_bare, &[("jlong", "Long"), ("jlong", "Long")], ("jobject", "Any?"), &format!( "match rt::poll(env, p0 as usize as _, p1 as usize as _, jni_{}, \"{}\") {{\n\t\t Some(w) => {{\n\t\t\t\tstatic FACTORY: std::sync::OnceLock = std::sync::OnceLock::new();\n\t\t\t\tw.value(env, &FACTORY, c\"{poll_factory}\", std::ptr::null_mut())\n\t\t\t}},\n\t\t\tNone => std::ptr::null_mut(),\n\t\t}}", poll.name, poll.name)); self.native( &free_bare, &[("jlong", "Long")], ("()", "Unit"), &format!("jni_{}(p0 as usize as _)", free.name), ); let raw = format!("_Native.{bare}({})", exprs.join(", ")); let call = if after.is_empty() { raw } else { { let moving = self.moving(&raw, &after); self.refused_first(&bare, moving) } }; let awaited = format!( "_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 { format!("{awaited}.let {{ }}") } else { format!("({awaited}) as {ok_kt}") }; } else if written.is_empty() && matches!(&function.ok, Type::Tuple(elements) if elements.len() > 1 && elements.iter().map(|ty| match abi.ty(ty) { Ty::Int(Int::I64 | Int::U64 | Int::Isize | Int::Usize) | Ty::F64 | Ty::Handle { .. } => 2, _ => 1 }).sum::() + usize::from(err.is_some()) <= 255 && elements.iter().all(|ty| matches!(abi.ty(ty), Ty::Bool | Ty::Int(_) | Ty::F32 | Ty::F64 | Ty::Char | Ty::Enum(_) | Ty::Handle { .. }))) { let Type::Tuple(elements) = &function.ok else { unreachable!() }; let factory = format!("{bare}__return"); self.dispatchers.push(factory.clone()); let mut fields = Vec::new(); let mut values = Vec::new(); let mut lifted = Vec::new(); let mut sig = "(".to_string(); for (k, ty) in elements.iter().enumerate() { let c = abi.ty(ty); let (jni, native) = jni_type(abi, &c, ty); fields.push(format!("p{k}: {native}")); sig.push_str(descriptor(jni)); lifted.push(self.lift(&strip_refs(ty), &c, &format!("p{k}"), false)); let field = match c { Ty::Bool => "z", Ty::F32 => "f", Ty::F64 => "d", Ty::Char | Ty::Enum(_) => "i", _ => jvalue_field(jni), }; values.push(format!( "jvalue {{ {field}: if success {{ let ret = o_{}.assume_init(); {} }} else {{ std::mem::zeroed() }} }}", outs[k].0, ret_expr(abi, &c, ty) )); } let mut failure = String::new(); let error = if let Some(err_ty) = function.err.as_ref() { fields.push("error: ByteArray?".to_string()); sig.push_str("[B"); 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}) }}", exception.as_deref().expect("a result's exception") ); format!( "let error = if success {{ std::ptr::null_mut() }} else {{ let mut w = rt::Writer::default(); {}; w.array(env) }};", put( err_ty, &format!("o_{}.assume_init()", outs.last().expect("an error out").0) ) ) } else { String::new() }; sig.push_str(")Ljava/lang/Object;"); let make = self.tuple_class(elements); let _ = write!( self.natives, "\t@kotlin.jvm.JvmStatic private fun {factory}({}): Any {{\n\t\t{failure}\n\t\treturn {make}({})\n\t}}\n\n", fields.join(", "), lifted.join(", ") ); let decl = outs .iter() .map(|(name, _)| format!("let mut o_{name} = std::mem::MaybeUninit::zeroed();")) .collect::>() .join("\n\t\t"); let ptrs = outs .iter() .map(|(name, _)| format!("o_{name}.as_mut_ptr()")) .collect::>(); let invoke = rust_call(&ptrs); let success = if err.is_some() { invoke } else { format!("{{ {invoke}; true }}") }; let params = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect::>(); self.native(&bare, ¶ms, ("jobject", "Any"), &format!("{}\n\t\t{decl}\n\t\tlet success = {success};{check}\n\t\t{error}\n\t\tlet args = [{}];\n\t\tstatic FACTORY: std::sync::OnceLock = std::sync::OnceLock::new();\n\t\tlet id = rt::method(env, &FACTORY, c\"{factory}\", c\"{sig}\");\n\t\t((**env).v1_2.CallStaticObjectMethodA)(env, rt::class(), id, args.as_ptr())", rust_pre.join("\n\t\t"), values.join(", "))); let raw = format!("_Native.{bare}({})", exprs.join(", ")); let raw = if after.is_empty() { raw } else { { let moving = self.moving(&raw, &after); self.refused_first(&bare, moving) } }; value = format!("({raw}) as {ok_kt}"); } 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 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 { decl.push(format!("let mut o_{name} = std::mem::MaybeUninit::zeroed();")); ptrs.push(format!("o_{name}.as_mut_ptr()")); } let ok_name = &outs[0].0; 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) ), }; let err_name = &outs[outs.len() - 1].0; self.native( &bare, ¶ms, (jni, native), &format!( "{}\n\t\t{}\n\t\tlet ok = {};{check}\n\t\tif !ok {{\n\t\t\tlet mut w = rt::Writer::default();\n\t\t\t{};\n\t\t\trt::raise(env, w);\n\t\t\treturn std::mem::zeroed();\n\t\t}}\n\t\t{ret}", rust_pre.join("\n\t\t"), decl.join("\n\t\t"), rust_call(&ptrs), put(err_ty, &format!("o_{err_name}.assume_init()")), ), ); let r = self.fresh("r"); let e = self.read_value(err.as_ref().expect("a result's error"), &r); let exception = exception.as_deref().expect("a result's exception"); let raw = format!("_Native.{bare}({})", exprs.join(", ")); let caught = format!( "try {{\n\t{raw}\n}} catch (f: _Native.__Failed) {{\n\t_Native.__Reader(f.error).let {{ {r} -> throw {exception}({e}) }}\n}}" ); let caught = match after.is_empty() { true => caught, false => { let moving = self.moving(&caught, &after); self.refused_first(&bare, moving) } }; value = match (&ok, &words) { (Type::Unit, _) => caught, (_, Some(opaque)) => { 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{made}\n}}", indent_by(&caught, 1) ) } _ => self.lift(&ok, &c_ok, &format!("({caught})"), false), }; } else if !outs.is_empty() { let types: Vec<&Type> = written.iter().map(|(_, ty)| ty).collect(); let (decl, ptrs, write) = self.glue_outs(&outs, &types, &function.ok, function.err.as_ref()); let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); // Only a result's write reads whether it returned ok; a value C returns, beside // what Rust wrote back, follows what it wrote. let returned = function.err.is_none() && !matches!(function.ok, Type::Unit | Type::Tuple(_)); let (ret_set, write) = match (function.err.is_some(), returned) { (true, _) => ("let ok = ", write), (false, true) => ("let ret = ", format!("{write}\n\t\t{};", put(&function.ok, "ret"))), (false, false) => ("", write), }; let factory = format!("{bare}__return"); self.dispatchers.push(factory.clone()); let mut lines = Vec::new(); // What Rust wrote back comes first, read whether or not the call failed. for (k, (_, ty)) in written.iter().enumerate() { let read = self.read_value(ty, "r"); let kt = self.kt_param(ty); lines.push(format!("(back!![{k}] as Mut<{kt}>).value = {read}")); } lines.extend(self.lift_result(&ok, err.as_ref(), exception.as_deref(), "r")); if ok == Type::Unit { lines.push("return Unit".to_string()); } else if let Some(last) = lines.last_mut() { *last = format!("return {last}"); } let _ = write!( self.natives, "\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; let back = if written.is_empty() { "std::ptr::null_mut()".to_string() } else { let arg = format!("p{}", params.len()); params.push(("jobjectArray", "kotlin.Array")); arg }; self.native( &bare, ¶ms, ("jobject", "Any?"), &format!( "{}\n\t\t{decl}\n\t\t{ret_set}{};{check}\n\t\tlet mut w = rt::Writer::default();\n\t\t{write}\n\t\tstatic FACTORY: std::sync::OnceLock = std::sync::OnceLock::new();\n\t\tw.value(env, &FACTORY, c\"{factory}\", {back})", rust_pre.join("\n\t\t"), rust_call(&ptrs)), ); let mut call_args = exprs.clone(); if !written.is_empty() { call_args.push(format!( "_arrayOf({})", written .iter() .map(|(name, _)| name.as_str()) .collect::>() .join(", ") )); } let raw = format!("_Native.{bare}({})", call_args.join(", ")); let raw = if after.is_empty() { raw } else { { let moving = self.moving(&raw, &after); self.refused_first(&bare, moving) } }; value = match ok { Type::Unit => format!("{raw}.let {{ }}"), _ => format!("({raw}) as {ok_kt}"), }; } else if let Some(flat) = flat { let mut params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); let rest = !flat.puts.is_empty(); let mut body = vec![rust_pre.join("\n\t\t"), format!("let ret = {};{check}", rust_call(&[]))]; if flat.option { body.push(format!( "if !ret.some {{\n\t\t\treturn {};\n\t\t}}", match rest { true => "std::ptr::null_mut()", false => "false", } )); } // Encoding the other fields can drop an owner whose Kotlin `close()` returns a // record of its own into this thread's slots, so the slots are written after. if rest { body.push("let mut w = rt::Writer::default();".to_string()); body.extend(flat.puts.iter().map(|p| format!("{p};"))); } if !flat.slots.is_empty() { params.push(("jlongArray", "kotlin.LongArray")); body.push(format!( "rt::slots(env, p{}, &[{}]);", params.len() - 1, flat.slots.join(", ") )); } if rest { body.push("w.array(env)".to_string()); } else if flat.option { body.push("true".to_string()); } let ret = match (rest, flat.option) { (false, false) => ("()", "Unit"), (false, true) => ("jboolean", "Boolean"), (true, false) => ("jbyteArray", "ByteArray"), (true, true) => ("jbyteArray", "ByteArray?"), }; self.native(&bare, ¶ms, ret, &body.join("\n\t\t")); let (make, r) = (&flat.make, &flat.r); 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, true) => { let b = self.fresh("b"); format!("{call}?.let {{ {b} -> _Native.__Reader({b}).let {{ {r} -> {make} }} }}") } }; value = match flat.slots.is_empty() { true => made, false => format!("_Native.__slots.get()!!.let {{ {} -> {made} }}", flat.a), }; } else if jni_type(abi, &export.call.ret, &ok).0 == "jbyteArray" && export.call.ret != Ty::Buf && ok.block().is_none() { let factory = format!("{bare}__return"); self.dispatchers.push(factory.clone()); let read = self.read_value(&ok, "r"); let _ = write!( self.natives, "\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!( "{}\n\t\tlet ret = {};{check}\n\t\tlet mut w = rt::Writer::default();\n\t\t{};\n\t\tstatic FACTORY: std::sync::OnceLock = std::sync::OnceLock::new();\n\t\tw.value(env, &FACTORY, c\"{factory}\", std::ptr::null_mut())", rust_pre.join("\n\t\t"), rust_call(&[]), put(&function.ok, "ret"))); let raw = format!("_Native.{bare}({})", exprs.join(", ")); let raw = if after.is_empty() { raw } else { { let moving = self.moving(&raw, &after); self.refused_first(&bare, moving) } }; value = format!("({raw}) as {ok_kt}"); } else { let c_ret = export.call.ret.clone(); // A block returns as the primitive array of its width, copied in one call. let returned = ok.block().map(block).filter(|_| matches!(c_ret, Ty::Struct(_))); let (jni, native) = match c_ret { _ if let Some(b) = &returned => (b.jni, b.signed), // Bytes cross copied or as their owner. Ty::Buf if copied(&ok).is_none() => ("jobject", "Any?"), Ty::Waker => ("jlong", "Long"), _ => jni_type(abi, &c_ret, &ok), }; let params: Vec<(&str, &str)> = native_params.iter().map(|(j, k)| (*j, k.as_str())).collect(); let ret_expr = match &c_ret { _ if returned.is_some() => "rt::new_block(env, ret)".to_string(), _ => ret_expr(abi, &c_ret, &ok), }; self.native( &bare, ¶ms, (jni, native), &format!( "{}\n\t\tlet ret = {};{check}\n\t\t{ret_expr}", rust_pre.join("\n\t\t"), rust_call(&[]) ), ); value = match (&ok, &returned) { (Type::Unit, _) => call, (_, Some(b)) => b.unsigned(&call), _ => self.lift(&ok, &c_ret, &call, false), }; } let value = match &single { Some(class) => format!("{class}({value})"), None => value, }; // Wrap the value in each argument's holds, innermost last. let mut code = value; for arg in args.iter().rev() { let mut inner = arg.inside.clone(); inner.push(code); code = match &arg.open { Some(open) => format!("{open}\n{}\n}}", indent_by(&inner.join("\n"), 1)), None => inner.join("\n"), }; } let mut text = function.docs.clone(); if handed.is_some() { text.push_str( "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", ); } for (param, name) in function.params.iter().zip(&names) { if let Type::Closure(closure_) = ¶m.ty { let lent = &closure_.params; text.push_str(&match closure_.kept { true => format!( "\n\nRust keeps `{name}` past the call, calling it from any thread, one call at a time, until it lets go of it." ), false => format!("\n\nRust calls `{name}` only during the call, from any thread."), }); if lent.iter().any(|p| matches!(p.base(), Type::Object(_))) { text.push_str(&format!( "\nAn object it lends lives only for that call of `{name}`: keep none past it." )); } if let Some(err) = &closure_.err { let thrown = self.exception(err); text.push_str(&format!( "\nIt fails by throwing [{thrown}], whose error Rust takes; any other exception aborts." )); } } if param.ty == Type::Jni(Jni::Object) { text.push_str(&format!( "\n\nRust holds `{name}` only during the call, on this thread, as JNI lends it." )); } if param.ty == Type::Ref(Mutability::Mut, Box::new(Type::Reader)) { text.push_str(&format!( "\n\nRust reads and seeks `{name}` only during the call, from any thread, one call at a time. An `IOException` it throws is Rust's `io::Error` of its message; any other exception aborts." )); } } let suspend = match export.future { Some(_) => "suspend ", None => "", }; let ret = match ok { Type::Unit if single.is_none() => String::new(), _ => format!(": {ret_kt}"), }; let property = matches!( (function.access, place, receiver), (Access::Field { .. }, Place::Member, _) | (Access::Const, _, None) ) && function.params.is_empty(); let member = match function.access { Access::Const if property => member.to_uppercase(), _ => member, }; let top = owner.is_none(); let kind = match property { true => "val", false => "fun", }; let mut member = match top { true => self.claim(&member, format!("fn `{}`", function.path.join("::"))), false => member, }; // A member its type declares already takes a trailing `_`. while taken.contains(&format!("{kind} {member}")) { member = format!("{}_", member.trim_matches('`')); } crate::lock::function(&mut self.locked, function, &member); let (head, getter) = match property { true => (format!("val {member}{ret}\n\tget()"), true), false => (format!("{suspend}fun {member}({}){ret}", kt_params.join(", ")), false), }; let indent_level = match top { true => 0, false => 1, }; let code = match ok { Type::Unit => format!("{head} {{\n{}\n}}", indent_by(&code, 1)), // A getter's body continues a line below its property's. _ if getter => format!("{head} = {}", code.replace('\n', "\n\t")), _ => format!("{head} = {code}"), }; let code = format!("{}{code}\n", docs(text.trim(), "")); Some(indent_by(&code, indent_level)) } /// The Kotlin statement closing each handle the value `e` of type `ty` holds, once a /// call moved their values out. fn close(&mut self, ty: &Type, e: &str) -> String { match ty { Type::Option(inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); format!("{e}?.let {{ {v} -> {close} }}") } Type::Box(inner) => self.close(inner, e), Type::Tuple(elements) => { let t = self.fresh("t"); let closes: Vec = (elements.iter().enumerate()) .filter(|(_, ty)| moved(self.abi, ty)) .map(|(k, ty)| self.close(ty, &format!("{t}.{}", ordinal(k)))) .collect(); format!("{e}.let {{ {t} -> {} }}", closes.join("; ")) } Type::List(_, inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); format!("{e}.forEach {{ {v} -> {close} }}") } _ => format!("{e}.handle.abandon()"), } } /// The glue's out values for `outs`, of a function returning `ok` or `err`, the /// pointers the C call takes after its parameters, and the statements writing them, /// `ok` saying whether it returned ok. /// The glue's out declarations, their pointers, and its writes of them: first what /// Rust wrote back into each of `written`, then the result. fn glue_outs( &mut self, outs: &[(String, Ty)], written: &[&Type], ok: &Type, err_ty: Option<&Type>, ) -> (String, Vec, String) { let mut decl = Vec::new(); let mut ptrs = Vec::new(); let mut back = Vec::new(); let mut oks = Vec::new(); let mut err = String::new(); // Each out's type, in the order the C ABI lists them. let types: Vec<&Type> = match ok { Type::Unit => Vec::new(), Type::Tuple(elements) => elements.iter().collect(), ok => vec![ok], }; let results = types.into_iter().chain(err_ty); for (k, ((name, _), ty)) in outs.iter().zip(written.iter().copied().chain(results)).enumerate() { decl.push(format!("let mut o_{name} = std::mem::MaybeUninit::zeroed();")); ptrs.push(format!("o_{name}.as_mut_ptr()")); let put = format!("{};", put(ty, &format!("o_{name}.assume_init()"))); match name.as_str() { _ if k < written.len() => back.push(put), "err" => err = put, _ => oks.push(put), } } let write = match err_ty.is_some() { true => format!( "w.put(ok);\n\t\tif ok {{\n\t\t\t{}\n\t\t}} else {{\n\t\t\t{err}\n\t\t}}", oks.join("\n\t\t\t") ), false => oks.join("\n\t\t"), }; back.push(write); (decl.join("\n\t\t"), ptrs, back.join("\n\t\t")) } /// Kotlin statements reading a result from the reader `r`: throwing its error, then /// reading its value. fn lift_result(&mut self, ok: &Type, err: Option<&Type>, exception: Option<&str>, r: &str) -> Vec { let mut lines = Vec::new(); if let (Some(err), Some(exception)) = (err, exception) { let e = self.read_value(err, r); lines.push(format!("if (!{r}.bool()) throw {exception}({e})")); } if *ok != Type::Unit { lines.push(self.read_value(ok, r)); } lines } /// The glue's C value of the record `i` Kotlin passes as `e`: each scalar, nested /// 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, e: &str, (arg, n): (&mut Arg, &mut usize), (w, writes): (&str, &mut Vec), 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) => 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; let (jni, native, kt, rust) = match ty { Type::Bool => ("jboolean", "Boolean", e, p), Type::Int(int) => { let (jni, native) = jni_type(abi, &Ty::Int(*int), ty); (jni, native, to_signed(*int, &e), from_jni(*int, &p)) } Type::NonZero(int) => { let (jni, native) = jni_type(abi, &Ty::Int(*int), ty); (jni, native, non_zero(&to_signed(*int, &e)), from_jni(*int, &p)) } Type::F32 => ("jfloat", "Float", e, p), Type::F64 => ("jdouble", "Double", e, p), Type::Char => ("jint", "Int", scalar_value(&e), format!("{p} as u32")), _ => ("jint", "Int", format!("{e}.value"), p), }; arg.jni.push(jni); arg.native.push(native.to_string()); arg.exprs.push(kt); rust } ty => { writes.push(self.write_value(ty, w, &e)); format!("{r}.get()") } }; fields.push(format!("f{k}: {value}")); } format!("crate::{} {{ {} }}", abi.record(i), fields.join(", ")) } /// The Kotlin value of the record `i` Rust returned as the C value `v`: each scalar, /// 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, i: usize, v: &str, (a, slots): (&str, &mut Vec), (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 self.made(&class, &opaque, &words); } 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) => 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 { Type::Bool => (format!("{v} as i64"), format!("({slot} != 0L)")), Type::Int(int) | Type::NonZero(int) => { let narrow = match jni_int(*int) { "jbyte" => format!("{slot}.toByte()"), "jshort" => format!("{slot}.toShort()"), "jint" => format!("{slot}.toInt()"), _ => slot, }; (format!("{v} as i64"), from_signed(*int, &narrow)) } Type::F32 => ( format!("{v}.to_bits() as i64"), format!("_Float.fromBits({slot}.toInt())"), ), Type::F64 => (format!("{v}.to_bits() as i64"), format!("_Double.fromBits({slot})")), Type::Char => (format!("{v} as i64"), format!("{slot}.toInt()")), Type::Enum(e) => { let class = self.qualified(&abi.enumeration(*e)); (format!("{v} as i64"), format!("{class}.of({slot}.toInt())")) } _ => unreachable!("{ty:?} is no scalar"), }; slots.push(rust); kt } ty => { puts.push(put(ty, &v)); self.read_value(ty, r) } }); } format!("{class}({})", fields.join(", ")) } } /// Whether a record's field of type `ty` crosses as a JNI scalar of its own. fn scalar(abi: &Abi<'_>, ty: &Type) -> bool { match ty { Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64 | Type::Char => true, Type::Enum(i) => abi.api.enums[*i].plain(), _ => false, } } /// 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) => 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. 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) => 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, _ => 0, }); fields.sum::() + 2 * usize::from(rest(abi, i)) } /// The JVM slots of the 255 a method takes left past the `unflattened` its C parameters /// take, a future's waker, and the array a written-back argument returns through: what /// flattening records, then the slots a returned record crosses in, may spend. 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, 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::Int(int) if jni_int(*int) == "jlong" => 2, Ty::F64 | Ty::Handle { .. } | Ty::Future(_) => 2, Ty::Buf => 5, Ty::U128 | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) | Ty::In(_) => 2, _ => 1, } } /// The record a function returns or takes directly, and whether in an `Option`. fn direct_record(ok: &Type) -> Option<(usize, bool)> { match ok.base() { Type::Record(i) => Some((*i, false)), Type::Option(inner) => match inner.base() { Type::Record(i) => Some((*i, true)), _ => None, }, _ => None, } } /// Kotlin's zero of the native parameter type `native`, which a `None` passes for each of /// its value's scalars. fn zero(native: &str) -> &'static str { match native { "Boolean" => "false", "Byte" => "(0).toByte()", "Short" => "(0).toShort()", "Int" => "0", "Long" => "0L", "Float" => "0f", "Double" => "0.0", native => unreachable!("{native} is no JNI scalar"), } } /// How a block of numbers crosses: as Kotlin's primitive array of its element. struct Block { /// The JNI array type. jni: &'static str, /// The Kotlin array type. kt: &'static str, /// The signed array of the same width, which JNI and the codec take. signed: &'static str, /// The Rust element. rust: &'static str, /// The codec reader's method. reader: &'static str, } impl Block { /// The Kotlin array `e` as its signed array, a view of the same memory. fn signed(&self, e: &str) -> String { match self.kt == self.signed { true => e.to_string(), false => format!("{e}.as{}()", self.signed), } } /// The signed array `e` as the Kotlin array, a view of the same memory. fn unsigned(&self, e: &str) -> String { match self.kt == self.signed { true => e.to_string(), false => format!("{e}.as{}()", self.kt), } } /// Reading the block of `n` numbers from the reader `r`. fn read(&self, r: &str, n: &str) -> String { self.unsigned(&format!("{r}.{}({n})", self.reader)) } } /// How a block of `elem`s crosses. fn block(elem: &Type) -> Block { let (jni, kt, signed, rust, reader) = match elem { Type::Int(Int::I8) => ("jbyteArray", "ByteArray", "ByteArray", "i8", "i8s"), Type::Int(Int::U16) => ("jshortArray", "UShortArray", "ShortArray", "u16", "i16s"), Type::Int(Int::I16) => ("jshortArray", "ShortArray", "ShortArray", "i16", "i16s"), Type::Int(Int::U32) => ("jintArray", "UIntArray", "IntArray", "u32", "i32s"), Type::Int(Int::I32) => ("jintArray", "IntArray", "IntArray", "i32", "i32s"), Type::Int(Int::U64) => ("jlongArray", "ULongArray", "LongArray", "u64", "i64s"), Type::Int(Int::I64) => ("jlongArray", "LongArray", "LongArray", "i64", "i64s"), Type::F32 => ("jfloatArray", "FloatArray", "FloatArray", "f32", "f32s"), Type::F64 => ("jdoubleArray", "DoubleArray", "DoubleArray", "f64", "f64s"), other => unreachable!("{other:?} is no block's element"), }; Block { jni, kt, signed, rust, reader, } } /// The glue's statement writing the C value `e` of IR type `ty`, which Rust returns: its /// bytes cross as their owner. fn put(ty: &Type, e: &str) -> String { match bytes(ty) { true => format!("w.put(rt::Owned({e}))"), false => format!("w.put({e})"), } } /// Whether `ty` is bytes, alone or in an `Option` or a list. fn bytes(ty: &Type) -> bool { match ty { Type::Slice | Type::Vec | Type::Bytes => true, Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => bytes(inner), _ => false, } } /// Whether passing `ty` moves an object's value out: by value, boxed, or in an `Option`, /// a list, or a tuple, unless `Copy`, and never through a reference. 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, } } /// Whether `ty` crosses as text, `Some(true)`, or a path, `Some(false)`, each a buffer /// copied whole, or as neither. fn copied(ty: &Type) -> Option { match ty.base() { Type::Option(inner) => copied(inner), Type::Str | Type::String => Some(true), Type::Path | Type::PathBuf => Some(false), _ => None, } } /// The suffix of the runtime's type, and of its codec's method, for an address of `family`. fn family_suffix(family: Family) -> &'static str { match family { Family::Any => "", Family::V4 => "V4", Family::V6 => "V6", } } /// The Kotlin `Int` `e` as a `char` crosses, throwing `IllegalArgumentException` unless it is /// a Unicode scalar value, as no Rust `char` holds any other. fn scalar_value(e: &str) -> String { format!("_Native.__char({e})") } /// The signed JNI integer `e` of a `NonZero`, throwing if it is zero, which no `NonZero` is. fn non_zero(e: &str) -> String { format!("_Native.__nonZero({e})") } /// The bound struct of `int`'s pairs of bounds. fn abi_bound(abi: &Abi<'_>, int: Int) -> String { abi.range(&Type::Bound(int)) } /// 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 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) { "jbyte" => ("jbyte", "Byte"), "jshort" => ("jshort", "Short"), "jint" => ("jint", "Int"), _ => ("jlong", "Long"), }, Ty::F32 => ("jfloat", "Float"), Ty::F64 => ("jdouble", "Double"), Ty::Char | Ty::Enum(_) => ("jint", "Int"), Ty::Handle { .. } | Ty::Future(_) => ("jlong", "Long"), Ty::Buf => ("jbyteArray", "ByteArray?"), Ty::Struct(_) if matches!(ty.base(), Type::Callback(..)) => ("jobject", "Any"), Ty::U128 | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) | Ty::In(_) => { ("jbyteArray", "ByteArray") } Ty::Fn(..) => ("jobject", "Any"), Ty::Waker => ("jobject", "Waker"), Ty::ForeignReader => ("jobject", "java.nio.channels.SeekableByteChannel"), Ty::ForeignFuture => ("jobject", "Any"), Ty::Jni(Jni::Object) => ("jobject", "Any?"), Ty::Jni(Jni::Env) => unreachable!("the glue passes its own env"), Ty::Poll | Ty::Status | Ty::Out(_) | Ty::InOut(_) | Ty::Data => unreachable!("{c:?} never crosses JNI"), } } /// The opaque value the C type `c` is, by value or as a receiver. fn opaque_of(abi: &Abi<'_>, c: &Ty) -> Option { let name = match c { Ty::Struct(name) => name, Ty::In(inner) => match &**inner { Ty::Struct(name) => name, _ => return None, }, _ => return None, }; (0..abi.api.records.len()) .find(|&i| &abi.record(i) == name) .and_then(|i| abi.api.records[i].opaque) } /// 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 => vec!["bits".to_string()], false => (0..opaque.words()).map(|k| format!("w{k}")).collect(), } } /// 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() } /// Whether `opaque` crosses JNI as one `long` wherever it crosses alone. fn one_word(opaque: &Opaque) -> bool { opaque.words() == 1 } /// 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) && 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(), Ty::Handle { .. } => "ret as usize as jlong".to_string(), Ty::Waker => "rt::returned(ret)".to_string(), Ty::Buf if copied(ok).is_some() => "rt::owned(env, ret)".to_string(), Ty::Buf => "rt::hand(env, ret)".to_string(), _ => format!( "{{ let mut w = rt::Writer::default(); {}; w.array(env) }}", put(ok, "ret") ), } } /// 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 { if err.is_none() || !written.is_empty() { return None; } match outs { [_] => Some(Ty::Void), [(_, Ty::Out(c)), _] if !matches!(ok, Type::Tuple(e) if e.len() > 1) => match &**c { 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, } } /// The JVM descriptor of a JNI type. fn descriptor(jni: &str) -> &'static str { match jni { "()" => "V", "jboolean" => "Z", "jbyte" => "B", "jshort" => "S", "jint" => "I", "jlong" => "J", "jfloat" => "F", "jdouble" => "D", "jbyteArray" => "[B", "jlongArray" => "[J", _ => "Ljava/lang/Object;", } } /// The `CallStaticMethodA` returning a JNI type. fn call_method(jni: &str) -> &'static str { match jni { "()" => "Void", "jboolean" => "Boolean", "jbyte" => "Byte", "jshort" => "Short", "jint" => "Int", "jlong" => "Long", "jfloat" => "Float", "jdouble" => "Double", _ => "Object", } } /// The `jvalue` field of a JNI integer type. fn jvalue_field(jni: &str) -> &'static str { match jni { "jbyte" => "b", "jshort" => "s", "jint" => "i", _ => "j", } } /// The JNI type of an integer. fn jni_int(int: Int) -> &'static str { match int { Int::U8 | Int::I8 => "jbyte", Int::U16 | Int::I16 => "jshort", Int::U32 | Int::I32 => "jint", _ => "jlong", } } /// The Rust type the C ABI's Rust side spells the C type `c` as, for a trampoline. pub(crate) fn rust_c(abi: &Abi<'_>, c: &Ty) -> String { match c { Ty::Void => "()".to_string(), Ty::Bool => "bool".to_string(), Ty::Int(int) => int.rust().to_string(), Ty::F32 => "f32".to_string(), Ty::F64 => "f64".to_string(), Ty::Char => "u32".to_string(), Ty::Enum(_) => "i32".to_string(), Ty::Buf => "crate::rt::Buf".to_string(), Ty::U128 => "crate::rt::U128".to_string(), Ty::Duration => "crate::rt::Duration".to_string(), Ty::SocketAddr(_) | Ty::IpAddr(_) => format!("crate::{}", crate::glue::rs(c)), Ty::Struct(name) => format!("crate::{name}"), Ty::Handle { .. } => "*const std::ffi::c_void".to_string(), Ty::Out(inner) => format!("*mut {}", rust_c(abi, inner)), other => { let _ = abi; unreachable!("{other:?} is never lent to a trampoline") } } } /// The Kotlin type of an integer. fn kt_int(int: Int) -> &'static str { match int { Int::U8 => "UByte", Int::U16 => "UShort", Int::U32 => "UInt", Int::U64 | Int::Usize => "ULong", Int::I8 => "Byte", Int::I16 => "Short", Int::I32 => "Int", Int::I64 | Int::Isize => "Long", } } /// The Rust integer of type `int` the JNI integer `e` holds: of the same width, or checked /// to fit a 32-bit target's `usize` and `isize`. fn from_jni(int: Int, e: &str) -> String { match int { // A `long` holds a `usize`'s bits. Int::Usize => format!("rt::narrow::({e} as u64)"), Int::Isize => format!("rt::narrow::({e})"), _ => format!("{e} as {}", int.rust()), } } /// The codec's method for an integer, and its width. fn wire_int(int: Int) -> (&'static str, usize) { match int { Int::U8 | Int::I8 => ("i8", 1), Int::U16 | Int::I16 => ("i16", 2), Int::U32 | Int::I32 => ("i32", 4), _ => ("i64", 8), } } /// The Kotlin integer `e` as the signed type JNI passes. fn to_signed(int: Int, e: &str) -> String { match int { Int::U8 => format!("{e}.toByte()"), Int::U16 => format!("{e}.toShort()"), Int::U32 => format!("{e}.toInt()"), Int::U64 => format!("{e}.toLong()"), // Checked against the library's target, which may be 32-bit. Int::Usize => format!("_Native.__usize({e})"), Int::Isize => format!("_Native.__isize({e})"), _ => e.to_string(), } } /// The signed JNI integer `e` as its Kotlin type. fn from_signed(int: Int, e: &str) -> String { match int { Int::U8 => format!("{e}.toUByte()"), Int::U16 => format!("{e}.toUShort()"), Int::U32 => format!("{e}.toUInt()"), Int::U64 | Int::Usize => format!("{e}.toULong()"), _ => e.to_string(), } } /// A Kotlin literal of an integer constant. fn int_literal(int: Int, v: i128) -> String { match int { Int::U8 | Int::U16 | Int::U32 => format!("{v}u"), Int::U64 | Int::Usize => format!("{v}uL"), Int::I64 | Int::Isize if v == i64::MIN as i128 => "Long.MIN_VALUE".to_string(), Int::I64 | Int::Isize => format!("{v}L"), Int::I8 if v == i8::MIN as i128 => "Byte.MIN_VALUE".to_string(), Int::I16 if v == i16::MIN as i128 => "Short.MIN_VALUE".to_string(), Int::I32 if v == i32::MIN as i128 => "Int.MIN_VALUE".to_string(), _ => v.to_string(), } } /// The contract as a Kotlin `ULong` literal. fn contract_literal(contract: u64) -> String { format!("0x{contract:016x}uL") } /// `ty` returned: a borrow is returned as a clone, so owned. pub(crate) fn strip_refs(ty: &Type) -> Type { match ty { Type::Ref(_, inner) => strip_refs(inner), Type::Option(inner) => Type::Option(Box::new(strip_refs(inner))), Type::Box(inner) => Type::Box(Box::new(strip_refs(inner))), ty => ty.clone(), } } /// 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 camel case: `into_label` is `intoLabel`, and `0` is `_0`. fn camel(name: &str) -> String { if name.starts_with(|c: char| c.is_ascii_digit()) { return format!("_{name}"); } let pascal = pascal(name); let mut chars = pascal.chars(); match chars.next() { Some(first) => first.to_lowercase().chain(chars).collect(), None => name.to_string(), } } /// The Kotlin names of parameters, in camel case, [`abi::distinct`], and quoted if a /// keyword. fn locals(params: &[Param]) -> Vec { (abi::distinct(params.iter().map(|p| camel(&p.name))).iter()) .map(|name| kw(name)) .collect() } /// A field's Kotlin name. fn field_name(name: &str) -> String { kw(&camel(name)) } /// A member's Kotlin name: in camel case, quoted if a keyword, or with `_` appended if /// Kotlin gives every such class a member of that name. fn member(snake: &str, reserved: &[&str]) -> String { let name = camel(snake); match reserved.contains(&name.as_str()) { true => format!("{name}_"), false => kw(&name), } } /// A name Kotlin reads as a hard keyword, in backticks. fn kw(name: &str) -> String { const KEYWORDS: &[&str] = &[ "as", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", "interface", "is", "null", "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "typeof", "val", "var", "when", "while", ]; match KEYWORDS.contains(&name) { true => format!("`{name}`"), false => name.to_string(), } } /// A native method's name mangled as JNI's symbols spell it. fn mangle(name: &str) -> String { let mut out = String::new(); for c in name.chars() { match c { '_' => out.push_str("_1"), '/' => out.push('_'), c if c.is_ascii_alphanumeric() => out.push(c), c => { let _ = write!(out, "_0{:04x}", c as u32); } } } out } /// The kind and name a member's code declares, for [`Gen::distinct`]. fn member_name(code: &str) -> Option { let line = code.lines().find(|l| { let l = l.trim_start(); !l.starts_with("/**") && !l.starts_with('*') && !l.starts_with("@") })?; let line = line .trim_start() .trim_start_matches("final ") .trim_start_matches("override ") .trim_start_matches("suspend "); let (kind, rest) = line.split_once(' ')?; if !matches!(kind, "fun" | "val") { return None; } let name: String = rest .chars() .take_while(|c| *c != '(' && *c != ':' && *c != ' ') .collect(); Some(format!("{kind} {name}")) } /// Kotlin's KDoc holding `docs`, each line indented by `indent`, or nothing for none. /// A Kotlin block comment nests, so a `/*` or `*/` in the docs is escaped. fn docs(docs: &str, indent: &str) -> String { if docs.trim().is_empty() { return String::new(); } let escaped = docs.replace("/*", "/*").replace("*/", "*/"); let mut out = format!("{indent}/**\n"); for line in escaped.lines() { match line.is_empty() { true => { let _ = writeln!(out, "{indent} *"); } false => { let _ = writeln!(out, "{indent} * {line}"); } } } let _ = writeln!(out, "{indent} */"); out } /// A field's docs, before it in a constructor's parameters. fn docs_inline(text: &str, indent: &str) -> String { docs(text, indent) } /// Code indented by one tab more. fn indent(code: &str) -> String { indent_by(code, 1) } /// Code indented by `n` tabs more, but for blank lines. pub(crate) fn indent_by(code: &str, n: usize) -> String { let tabs = "\t".repeat(n); let mut out: String = code .lines() .map(|l| match l.is_empty() { true => "\n".to_string(), false => format!("{tabs}{l}\n"), }) .collect(); if !code.ends_with('\n') { out.pop(); } out } #[cfg(test)] mod tests { /// The writeback array is a parameter of its own, which an out pointer's zero slots /// leave out. #[test] fn room_reserves_writeback() { assert_eq!(super::room(3, false, false), 252); assert_eq!(super::room(3, false, true), 251); assert_eq!(super::room(3, true, true), 250); } /// 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_prefixed() { for line in super::RUNTIME.lines() { let words: Vec<&str> = line.split_whitespace().collect(); let Some(at) = words .iter() .position(|w| matches!(*w, "class" | "interface" | "object")) else { continue; }; if line.starts_with(['\t', ' ']) { continue; } let name: String = words[at + 1] .chars() .take_while(|c| c.is_alphanumeric() || *c == '_') .collect(); if words[..at].iter().all(|w| { matches!( *w, "abstract" | "private" | "internal" | "open" | "data" | "sealed" | "fun" ) }) && !name.is_empty() { assert!( name.starts_with("__"), "the runtime's class {name} takes no leading `__`" ); } } } }