//! Swift over the C ABI: `swift/.swift`, which imports the C header as the clang //! module `swift/module.modulemap` declares, beside the atomics its runtime needs. //! //! Each name is its C name without the prefix, as Swift spells it: `moq_track_producer` //! is `TrackProducer`, and its method `moq_track_producer_append_group` is //! `TrackProducer.appendGroup`. A keyword is quoted in backticks, and a member named as one //! Swift gives its type takes a trailing `_`. An object is a noncopyable struct owning its //! handle, freed in `deinit`, so Swift's compiler checks each move and borrow Rust makes: //! `self` is `consuming`, `&mut self` `mutating`, a parameter `consuming`, `borrowing`, or //! `inout`, a tuple holding one a struct of its own, and an array of them swift-collections' //! `UniqueArray`. An object that is `Copy`, which only one C may change is, or thrown as an //! error is a final class instead, since `Swift.Error` requires a copyable type, whose //! handle a call holds at run time. A record is a struct, and any other `Copy` type with //! private fields a struct over the bytes of its C struct, which only Rust makes or reads; //! an enum a Swift enum, with its data as associated values; a trait a protocol; a closure a function type; a future //! an `async` function; an error a thrown `Swift.Error`. The runtime they share, //! [`runtime/rt.swift`](../runtime/rt.swift), holds the classes' handles, the arena a call //! lowers nested values into, and the signal a future parks on. //! //! Bytes are the runtime's `Bytes`: those Rust returned lend its buffer, and pass back to //! Rust as a second owner of it, so neither way copies them. Swift's own bytes and text //! pass as views of Swift's memory at a call's top level, which Rust copies once where it //! keeps them; nested in another value, they are copied once into a buffer Rust takes. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use crate::abi::{self, Abi, Ty, pascal}; use crate::ir::{Access, Closure, Family, Function, Int, Literal, Mutability, On, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.swift"); /// What the generator writes: the Swift file, the clang module map it imports the C /// header through, and the header of atomics that module adds. pub(crate) struct Output { pub(crate) names: BTreeMap, pub(crate) swift: String, pub(crate) modulemap: String, pub(crate) atomics: String, } /// The name of the clang module of the C header: `api` is `ApiFFI`. fn module(prefix: &str) -> String { format!("{}FFI", pascal(prefix)) } /// The Swift for `abi`, whose header's contract is `contract`, or the names two items /// claim alike. 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), |name| TAKEN.contains(&name)), types: String::new(), top: String::new(), natives: String::new(), names: BTreeMap::new(), errors: Vec::new(), thrown: BTreeMap::new(), conforms: BTreeSet::new(), unsent_errors: BTreeSet::new(), structs: structs(abi), fresh: 0, on: On::ALL, }; 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 upper = p.to_uppercase(); let module = module(p); let mut swift = format!( "// Generated by rust2-ffi: Swift over the C ABI of the pub API of {packages}. Do not edit.\n\n\ import BasicContainers\n#if canImport(FoundationEssentials)\nimport FoundationEssentials\n#else\nimport Foundation\n#endif\nimport {module}\n\n" ); let _ = write!( swift, "/// The runtime, and its names for the export's C types and functions.\nenum Native {{\n\ \tstatic let file = \"{p}.swift\"\n\n\ \ttypealias Buf = {p}_buf\n\ \ttypealias CWaker = {p}_waker\n\ \ttypealias CForeignFuture = {p}_foreign_future\n\ \ttypealias CForeignReader = {p}_foreign_reader\n\ \ttypealias CU128 = {p}_u128\n\ \ttypealias CDuration = {p}_duration\n\ \ttypealias CIpv4Addr = {p}_ipv4_addr\n\ \ttypealias CIpv6Addr = {p}_ipv6_addr\n\ \ttypealias CIpAddr = {p}_ip_addr\n\ \ttypealias CSocketAddrV4 = {p}_socket_addr_v4\n\ \ttypealias CSocketAddrV6 = {p}_socket_addr_v6\n\ \ttypealias CSocketAddr = {p}_socket_addr\n\n\ \tstatic func contract() -> Swift.Bool {{\n\t\t{p}_contract() == 0x{contract:016x} && {upper}_CONTRACT == 0x{contract:016x}\n\t}}\n\n\ \t/// The index of the library's target among those this file serves.\n\ \tstatic let target = Swift.UInt64({p}_target())\n\n\ \t/// Throws unless the library's target is among those of `on`, as the item `what` is.\n\ \tstatic func on(_ on: Swift.UInt64, _ what: Swift.String) throws {{\n\t\tif (on >> target) & 1 == 0 {{\n\t\t\tthrow CheckError(function: what, message: \"it is not on this library's target\")\n\t\t}}\n\t}}\n\n\ \t/// Traps unless the library's target is among those of `on`, where nothing can throw.\n\ \tstatic func onOrTrap(_ on: Swift.UInt64, _ what: Swift.String) {{\n\t\tif (on >> target) & 1 == 0 {{\n\t\t\tfatalError(\"\\(what): it is not on this library's target\")\n\t\t}}\n\t}}\n\n\ \t/// Throws what `status`, written by a call of `what`, says it failed, if anything.\n\ \t@inline(__always)\n\tstatic func status(_ status: Swift.Int32, _ what: Swift.StaticString) throws {{\n\t\tif status != 0 {{\n\t\t\tthrow failure(status, what)\n\t\t}}\n\t}}\n\n\ \t/// The error `status` says a call of `what` failed with: out of line, so each call that\n\ \t/// checks one stays small enough for its caller to inline.\n\ \t@inline(never)\n\tstatic func failure(_ status: Swift.Int32, _ what: Swift.StaticString) -> CheckError {{\n\t\tCheckError(function: \"\\(what)\", message: Swift.String(cString: {p}_status_message(status)))\n\t}}\n\n\ \tstatic func free(_ buf: Buf) {{\n\t\t{p}_buf_free(buf)\n\t}}\n\n\ \t/// A buffer Rust owns, holding a copy of what `view` lends.\n\ \tstatic func copy(_ view: Buf) -> Buf {{\n\t\t{p}_buf_copy(view)\n\t}}\n\n\ \t/// A second owner of `buf`, which Rust returned, sharing its bytes.\n\ \tstatic func clone(_ buf: Buf) -> Buf {{\n\t\t{p}_buf_clone(buf)\n\t}}\n\n\ \tstatic func load(_ state: UnsafeMutablePointer) -> Swift.Int {{\n\t\t{p}_atomic_load(state)\n\t}}\n\n\ \tstatic func store(_ state: UnsafeMutablePointer, _ value: Swift.Int) {{\n\t\t{p}_atomic_store(state, value)\n\t}}\n\n\ \tstatic func add(_ state: UnsafeMutablePointer, _ value: Swift.Int) -> Swift.Int {{\n\t\t{p}_atomic_add(state, value)\n\t}}\n\n\ \tstatic func exchange(_ state: UnsafeMutablePointer, _ value: Swift.Int) -> Swift.Int {{\n\t\t{p}_atomic_exchange(state, value)\n\t}}\n\n\ \t/// Set `state` to `new` if it is `old`, returning what it was.\n\ \tstatic func swap(_ state: UnsafeMutablePointer, _ old: Swift.Int, _ new: Swift.Int) -> Swift.Int {{\n\t\t{p}_atomic_cas(state, old, new)\n\t}}\n\n\ \t/// `load`, `store`, and `swap`, sequentially consistent: a store and a later load of\n\ \t/// another word on two threads each meet the other's.\n\ \tstatic func loadSC(_ state: UnsafeMutablePointer) -> Swift.Int {{\n\t\t{p}_atomic_load_sc(state)\n\t}}\n\n\ \tstatic func storeSC(_ state: UnsafeMutablePointer, _ value: Swift.Int) {{\n\t\t{p}_atomic_store_sc(state, value)\n\t}}\n\n\ \tstatic func swapSC(_ state: UnsafeMutablePointer, _ old: Swift.Int, _ new: Swift.Int) -> Swift.Int {{\n\t\t{p}_atomic_cas_sc(state, old, new)\n\t}}\n}}\n\n" ); swift.push_str(RUNTIME); swift.push('\n'); swift.push_str(&g.types); swift.push_str(&g.top); if !g.natives.is_empty() { let _ = write!(swift, "extension Native {{\n{}}}\n", g.natives); } while swift.ends_with("\n\n") { swift.pop(); } let swift = inlinable(&swift); let modulemap = format!( "// Generated by rust2-ffi: the C ABI of {packages} as a clang module, which {p}.swift imports. Do not edit.\n\n\ module {module} {{\n\theader \"../include/{p}.h\"\n\theader \"{p}_atomics.h\"\n\texport *\n}}\n" ); let atomics = format!( "/* Generated by rust2-ffi: the atomics {p}.swift's runtime uses, which Swift's standard\n * library lacks before macOS 15 and iOS 18. Do not edit. */\n\n\ #ifndef {upper}_ATOMICS_H\n#define {upper}_ATOMICS_H\n\n#include \n\n\ static inline intptr_t {p}_atomic_load(const intptr_t *p) {{\n\treturn __atomic_load_n(p, __ATOMIC_ACQUIRE);\n}}\n\n\ static inline void {p}_atomic_store(intptr_t *p, intptr_t v) {{\n\t__atomic_store_n(p, v, __ATOMIC_RELEASE);\n}}\n\n\ static inline intptr_t {p}_atomic_add(intptr_t *p, intptr_t v) {{\n\treturn __atomic_add_fetch(p, v, __ATOMIC_ACQ_REL);\n}}\n\n\ static inline intptr_t {p}_atomic_exchange(intptr_t *p, intptr_t v) {{\n\treturn __atomic_exchange_n(p, v, __ATOMIC_ACQ_REL);\n}}\n\n\ static inline intptr_t {p}_atomic_cas(intptr_t *p, intptr_t old, intptr_t new_) {{\n\t__atomic_compare_exchange_n(p, &old, new_, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);\n\treturn old;\n}}\n\n\ static inline intptr_t {p}_atomic_load_sc(const intptr_t *p) {{\n\treturn __atomic_load_n(p, __ATOMIC_SEQ_CST);\n}}\n\n\ static inline void {p}_atomic_store_sc(intptr_t *p, intptr_t v) {{\n\t__atomic_store_n(p, v, __ATOMIC_SEQ_CST);\n}}\n\n\ static inline intptr_t {p}_atomic_cas_sc(intptr_t *p, intptr_t old, intptr_t new_) {{\n\t__atomic_compare_exchange_n(p, &old, new_, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);\n\treturn old;\n}}\n\n\ #endif\n" ); Ok(Output { names: g.locked, swift: swift + "\n", modulemap, atomics, }) } /// The standard library's names the runtime and the generated code use unqualified, which /// an exported type or function would shadow, and `Swift`, which qualifies the rest. The /// runtime's own are the C ABI's: `Native`, `Bytes`, and each address type are claimed as /// `_native`, `_bytes`, `_socket_addr`, and so on. const TAKEN: &[&str] = &[ "Array", "Bool", "Bytes", "CancellationError", "CheckError", "Comparable", "CustomDebugStringConvertible", "CustomStringConvertible", "Data", "Equatable", "Hashable", "Int", "Int64", "IpAddr", "Ipv4Addr", "Ipv6Addr", "Never", "NonZero", "OpaquePointer", "Optional", "PathBuf", "RandomAccessCollection", "RustDuration", "Sendable", "SeekOrigin", "SeekableReader", "SocketAddr", "SocketAddrV4", "SocketAddrV6", "StaticString", "Swift", "Task", "U128", "UInt", "UInt16", "UInt32", "UInt64", "UInt8", "UTF8", "Unicode", "Unmanaged", "UnsafeBufferPointer", "UnsafeContinuation", "UnsafeMutableBufferPointer", "UnsafeMutablePointer", "UnsafeMutableRawPointer", "UnsafePointer", "UnsafeRawBufferPointer", "UnsafeRawPointer", "UniqueArray", "Void", "fatalError", "withTaskCancellationHandler", "withUnsafeBytes", "withUnsafeContinuation", "withUnsafeMutableBytes", "withUnsafeMutablePointer", "withoutActuallyEscaping", ]; /// One parameter, as the call passes it: the closure it runs inside, holding what it /// passes until it returns, the C arguments, and what closes once the call returns. #[derive(Default)] struct Arg { open: Option<(String, String)>, exprs: Vec, after: Vec, /// Whether an expression gives Rust a retained box, which only the call takes. gives: bool, /// Whether its lowering, its one expression, throws. throws: bool, /// Whether it opens a buffer Rust takes, a second owner of Rust's own, which only the /// call frees: so it opens inside every open that throws. takes: bool, } struct Gen<'a> { locked: BTreeMap, abi: &'a Abi<'a>, /// Each exported type's name, by its C name. classes: HashMap, /// The types, then the top-level functions and constants, then `Native`'s additions. types: String, top: String, natives: String, /// Each top-level Swift name, with what claimed it. names: BTreeMap, errors: Vec, /// The struct each error type that is no exported type throws as, by name. thrown: BTreeMap, /// The exported types thrown as errors, which conform to `Swift.Error`. conforms: BTreeSet, /// Those of them that are not `Sendable`, which `Swift.Error` requires: each conforms /// unchecked, as its run-time checks keep it on its thread. unsent_errors: BTreeSet, /// The objects that are noncopyable structs: each but those `Copy` or thrown. structs: BTreeSet, fresh: usize, /// The targets of the item being written, whose calls check theirs. on: On, } impl<'a> Gen<'a> { /// The statement that throws, if the body around it can, or else traps, unless the /// library's target is among those of `on`, as the item `what` is, then `then`; or `then` /// alone if it is on every target. fn on(&self, on: On, what: &str, then: &str, throws: bool) -> String { let api = self.abi.api; let check = match throws { true => "try Native.on", false => "Native.onOrTrap", }; match api.everywhere(on) { true => then.to_string(), false => format!("{check}({}, \"{what}\"){then}", on.0 & api.all().0), } } fn fresh(&mut self, base: &str) -> String { self.fresh += 1; format!("{base}{}_", self.fresh) } /// A C name without the prefix. fn bare<'n>(&self, c: &'n str) -> &'n str { &c[self.abi.prefix.len() + 1..] } /// The Swift name of the C type `c`. fn class(&self, c: &str) -> String { self.classes.get(c).cloned().unwrap_or_else(|| pascal(self.bare(c))) } /// The top-level Swift name `what` takes with `labels`: `name`, with a trailing `_` /// until neither the runtime nor an earlier item takes its [`full`] name. fn claim(&mut self, name: &str, labels: &[String], what: String) -> String { let mut name = name.to_string(); while TAKEN.contains(&unquote(&name).as_str()) || self.names.contains_key(&full(false, &name, labels.iter().cloned())) { name = format!("{}_", unquote(&name)); } self.names.insert(full(false, &name, labels.iter().cloned()), what); name } /// Check that no two members of the type `rust` share a full Swift name, as [`full`] /// spells it. fn distinct(&mut self, rust: &str, members: &[String]) { let mut seen = BTreeSet::new(); for member in members { if !seen.insert(member) { self.errors.push(format!( "two members of `{rust}` are both `{member}` in Swift, which rust2-ffi should keep apart" )); } } } /// Whether Swift's value of `ty` is noncopyable: it holds an object's struct. fn unique(&self, ty: &Type) -> bool { unique(&self.structs, ty) } /// The ownership a parameter of type `ty` declares, which Swift requires of a /// noncopyable one: `&T` borrows it, `&mut T` is `inout`, and a value moves in. fn ownership(&self, ty: &Type) -> &'static str { match ty { _ if !self.unique(ty) => "", Type::Ref(Mutability::Not, _) => "borrowing ", Type::Ref(Mutability::Mut, _) => "inout ", Type::Option(inner) if matches!(**inner, Type::Ref(Mutability::Mut, _)) => "inout ", _ => "consuming ", } } /// The Swift value of the `n`th element of the tuple `e` of `elements`: a struct's /// field `_n` if it is noncopyable, else the tuple's element. fn element(&self, elements: &[Type], e: &str, n: usize) -> String { match elements.iter().any(|e| self.unique(e)) { true => format!("{e}._{n}"), false => format!("{e}.{n}"), } } /// Whether passing `ty` moves the value of a class's handle out, so the call closes it: /// by value, boxed, or in an `Option`, a list, or a tuple, unless `Copy`, and never /// through a reference. A struct needs no close: Swift's compiler ends it. fn moved(&self, ty: &Type) -> bool { match ty { Type::Object(i) => !self.abi.api.objects[*i].copy && !self.structs.contains(i), Type::Option(inner) | Type::Box(inner) | Type::List(_, inner) => self.moved(inner), Type::Tuple(elements) => elements.iter().any(|ty| self.moved(ty)), _ => false, } } /// The Swift type of `ty`, as a value, a parameter, or a result. fn sw(&self, ty: &Type) -> String { let abi = self.abi; match ty { Type::Const(_) => unreachable!("a const argument is no value"), Type::Jni(_) => unreachable!("only Kotlin exports what takes a JNI value"), Type::Array(n) => Abi::array_class(*n), Type::Unit => "Void".to_string(), Type::Bool => "Swift.Bool".to_string(), Type::Int(int) => sw_int(*int).to_string(), Type::NonZero(int) => format!("NonZero<{}>", sw_int(*int)), Type::F32 => "Swift.Float".to_string(), Type::F64 => "Swift.Double".to_string(), Type::Char => "Swift.Unicode.Scalar".to_string(), Type::Str | Type::String => "Swift.String".to_string(), Type::Path | Type::PathBuf => "PathBuf".to_string(), Type::Slice | Type::Vec | Type::Bytes => "Bytes".to_string(), Type::U128 => "U128".to_string(), Type::Duration => "RustDuration".to_string(), Type::SocketAddr(Family::Any) => "SocketAddr".to_string(), Type::SocketAddr(Family::V4) => "SocketAddrV4".to_string(), Type::SocketAddr(Family::V6) => "SocketAddrV6".to_string(), Type::IpAddr(Family::Any) => "IpAddr".to_string(), Type::IpAddr(Family::V4) => "Ipv4Addr".to_string(), Type::IpAddr(Family::V6) => "Ipv6Addr".to_string(), Type::List(_, inner) if self.unique(inner) => format!("UniqueArray<{}>", self.sw(inner)), Type::List(_, inner) => format!("[{}]", self.sw(inner)), Type::Waker => "@Sendable () -> Void".to_string(), Type::Reader => "some SeekableReader".to_string(), Type::Future => "@Sendable () async -> Void".to_string(), Type::Option(inner) => format!("{}?", self.sw(inner)), Type::Box(inner) | Type::Ref(_, inner) => self.sw(inner), Type::Record(i) => self.class(&abi.record(*i)), Type::Enum(i) => self.class(&abi.enumeration(*i)), Type::Object(i) => self.class(&abi.object(*i)), Type::Callback(i, _) => format!("any {}", self.class(&abi.callback(*i))), Type::Closure(closure_) => { let (params, ret) = (&closure_.params, &closure_.ok); let params: Vec = (params.iter()) .map(|p| format!("{}{}", self.ownership(p), self.sw(p))) .collect(); let throws = match closure_.err { Some(_) => " throws", None => "", }; format!("@Sendable ({}){throws} -> {}", params.join(", "), self.sw(ret)) } Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => self.class(&abi.range(ty)), Type::Tuple(elements) => match &elements[..] { // Swift has no tuple of one: it is its element, which loses nothing. [element] => self.sw(element), elements if self.unique(ty) => self.class(&abi.tuple(elements)), elements => { let elements: Vec = elements.iter().map(|e| self.sw(e)).collect(); format!("({})", elements.join(", ")) } }, } } /// The Swift spelling of a C type, for a local the call writes. fn c_sw(&self, ty: &Ty) -> String { let abi = self.abi; match ty { Ty::Bool => "Swift.Bool".to_string(), Ty::Int(int) => c_int(*int).to_string(), Ty::F32 => "Swift.Float".to_string(), Ty::F64 => "Swift.Double".to_string(), Ty::Char => "Swift.UInt32".to_string(), Ty::Buf => abi.rt("buf"), Ty::U128 => abi.rt("u128"), Ty::Duration => abi.rt("duration"), Ty::SocketAddr(family) => abi.rt(abi::addr(true, *family)), Ty::IpAddr(family) => abi.rt(abi::addr(false, *family)), Ty::Struct(n) | Ty::Enum(n) => n.clone(), Ty::Handle { .. } | Ty::Future(_) => "OpaquePointer?".to_string(), Ty::Waker => abi.rt("waker"), other => unreachable!("no local is {other:?}"), } } /// The zero a local of C type `ty` starts as. fn zero(&self, ty: &Ty) -> String { match ty { Ty::Bool => "false".to_string(), Ty::Int(_) | Ty::F32 | Ty::F64 | Ty::Char => "0".to_string(), Ty::Handle { .. } | Ty::Future(_) => "nil".to_string(), Ty::Enum(n) => format!("{n}(rawValue: 0)"), other => format!("{}()", self.c_sw(other)), } } /// Whether lowering a `ty` nested in another value needs the call's arena: to copy /// bytes, build an array, or hold a handle. fn arena(&self, ty: &Type) -> bool { let api = self.abi.api; match ty { ty if Abi::is_buf(ty) => true, Type::List(..) | Type::Object(_) => true, Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) => self.arena(inner), Type::Tuple(elements) => elements.iter().any(|e| self.arena(e)), Type::Record(i) => api.records[*i].fields.iter().any(|f| self.arena(&f.ty)), Type::Enum(i) => (api.enums[*i].variants.iter()).any(|v| v.fields.iter().any(|f| self.arena(&f.ty))), _ => false, } } /// Whether lowering a `ty` nested in another value can throw: it holds a class whose /// value a move takes, closing its handle. fn throwing(&self, ty: &Type) -> bool { let mut handles = Vec::new(); self.abi.api.handles(ty, &mut handles, &mut Vec::new()); handles.into_iter().any(|i| self.held(i)) } /// Whether object `i` is a class a move may close, whose hold for a call can fail. fn held(&self, i: usize) -> bool { self.abi.traits_status(i) && !self.unique(&Type::Object(i)) } /// `lowered`, a lowering in a function that cannot throw, trapping instead. fn trapping(lowered: String) -> String { match lowered.contains("try ") { true => format!("try! {lowered}"), false => lowered, } } /// The arena argument a value's `_lower` takes, if it needs one. fn arena_arg(&self, ty: &Type) -> &'static str { match self.arena(ty) { true => "a_", false => "", } } /// The C value of the Swift value `e` of type `ty`, nested in a value the call passes: /// bytes copied into the arena `a_`, and a class's handle held by it. A struct's handle /// needs no hold, since the call borrows or consumes the struct until it returns. fn lower(&mut self, ty: &Type, e: &str) -> String { let abi = self.abi; if Abi::is_buf(ty) { return format!("a_.buf({e})"); } match ty { Type::Unit => unreachable!("no value is unit"), Type::Bool | Type::F32 | Type::F64 => e.to_string(), Type::Int(int) => lower_int(*int, e), Type::NonZero(int) => lower_int(*int, &format!("{e}.value")), Type::Char => format!("{e}.value"), Type::U128 => format!("Native.u128({e})"), Type::Array(_) => format!("{e}._c"), Type::Duration => format!("Native.duration({e})"), Type::SocketAddr(_) | Type::IpAddr(_) => format!("Native.addr({e})"), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("{e}._lower()"), Type::Waker => format!("Native.waker({e})"), Type::Future => format!("Native.future({e})"), // A block is copied whole into the arena. Type::List(_, inner) if ty.block().is_some() => { format!("Native.vec(a_.block({e}), {}.init(ptr:len:owner:))", abi.list(inner)) } Type::List(_, inner) => { let x = self.fresh("x"); let item = self.lower(inner, &x); let list = match self.unique(inner) { true => "unique", false => "list", }; // A hold that throws makes the list's lowering throw. let t = match item.contains("try ") { true => "try ", false => "", }; format!( "Native.vec({t}a_.{list}({e}) {{ {x} in {item} }}, {}.init(ptr:len:owner:))", abi.list(inner) ) } // `Optional.map` takes only a copyable value: `Native.option` borrows it. Type::Option(inner) if self.unique(inner) => { let v = self.fresh("v"); let (some, none) = match inner.base() { Type::Object(_) => (format!("{v}.handle"), "nil".to_string()), Type::List(_, elem) => (self.lower(inner, &v), format!("{}()", abi.list(elem))), _ => { let c = abi.option(inner); ( format!("{c}(some: true, value: {})", self.lower(inner, &v)), format!("{c}()"), ) } }; let t = match some.contains("try ") { true => "try ", false => "", }; format!("{t}Native.option({e}, {{ {v} in {some} }}, {none})") } Type::Option(inner) => match inner.base() { Type::Object(i) if self.held(*i) => format!("try a_.held({e}?.handle)"), Type::Object(_) => format!("a_.hold({e}?.handle)"), _ if Abi::is_buf(inner) => format!("a_.buf({e})"), Type::List(_, elem) => { let v = self.fresh("v"); let some = self.lower(inner, &v); let t = if some.contains("try ") { "try " } else { "" }; format!("({t}{e}.map {{ {v} in {some} }} ?? {}())", abi.list(elem)) } _ => { let c = abi.option(inner); let v = self.fresh("v"); let some = self.lower(inner, &v); let t = if some.contains("try ") { "try " } else { "" }; format!("({t}{e}.map {{ {v} in {c}(some: true, value: {some}) }} ?? {c}())") } }, Type::Box(inner) | Type::Ref(_, inner) => self.lower(inner, e), Type::Record(_) | Type::Enum(_) => { let t = match self.throwing(ty) { true => "try ", false => "", }; format!("{t}{e}._lower({})", self.arena_arg(ty)) } Type::Object(_) if self.unique(ty) => format!("{e}.handle"), Type::Object(i) if self.held(*i) => format!("try a_.held({e}.handle)"), Type::Object(_) => format!("a_.hold({e}.handle)"), Type::Callback(i, _) => format!("Native.lower_{}({e})", abi.callback(*i)), Type::Tuple(elements) => { let c = abi.tuple(elements); let fields: Vec = match &elements[..] { [element] => vec![format!("_0: {}", self.lower(element, e))], elements => (elements.iter().enumerate()) .map(|(n, ty)| format!("_{n}: {}", self.lower(ty, &self.element(elements, e, n)))) .collect(), }; format!("{c}({})", fields.join(", ")) } Type::Closure(..) => unreachable!("a closure lowers to its trampoline"), _ => unreachable!("a buffer is above"), } } /// The Swift value of the C value `e` of type `ty`, which it takes ownership of. `e` /// is named, so it may be read more than once. fn lift(&mut self, ty: &Type, e: &str) -> String { let abi = self.abi; match ty { Type::Str | Type::String => format!("Native.string({e})"), Type::Path | Type::PathBuf => format!("Native.path({e})"), Type::Slice | Type::Vec | Type::Bytes => format!("Native.bytes({e})"), Type::Bool | Type::F32 | Type::F64 => e.to_string(), Type::Int(int) => lift_int(*int, e), Type::NonZero(int) => format!("NonZero(_unchecked: {})", lift_int(*int, e)), Type::Char => format!("Native.scalar({e})"), Type::U128 => format!("Native.u128({e})"), Type::Array(n) => format!("{}(_c: {e})", Abi::array_class(*n)), Type::Duration => format!("Native.duration({e})"), Type::SocketAddr(_) | Type::IpAddr(_) => format!("Native.addr({e})"), Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("{}._lift({e})", self.sw(ty)), // A block is copied out whole, then freed. Type::List(_, inner) if ty.block().is_some() => { let v = self.fresh("v"); format!( "{{ () -> {} in let {v} = {e}; defer {{ {}_free({v}) }}; return Native.block({v}.ptr, {v}.len) }}()", self.sw(ty), abi.list(inner) ) } Type::List(_, inner) => { let (v, c) = (self.fresh("v"), self.fresh("c")); let item = self.lift(inner, &c); let list = match self.unique(inner) { true => "unique", false => "list", }; format!( "{{ () -> {} in var {v} = {e}; defer {{ {v}.len = 0; {}_free({v}) }}; return Native.{list}({v}.ptr, {v}.len) {{ {c} in {item} }} }}()", self.sw(ty), abi.list(inner) ) } Type::Option(inner) => match inner.base() { Type::Object(_) => format!("{e}.map {{ {}(raw: $0) }}", self.sw(inner)), Type::Str | Type::String => format!("Native.string(option: {e})"), Type::Path | Type::PathBuf => format!("Native.path(option: {e})"), Type::Slice | Type::Vec | Type::Bytes => format!("Native.bytes(option: {e})"), Type::List(..) => format!( "({e}.ptr == nil ? nil : {} as {}?)", self.lift(inner, e), self.sw(inner) ), _ => format!( "({e}.some ? {} as {}? : nil)", self.lift(inner, &format!("{e}.value")), self.sw(inner) ), }, Type::Box(inner) | Type::Ref(_, inner) => self.lift(inner, e), Type::Record(_) | Type::Enum(_) => format!("{}._lift({e})", self.sw(ty)), Type::Object(_) => format!("{}(raw: {e})", self.sw(ty)), Type::Waker => format!("Native.returned({e})"), Type::Tuple(elements) => match &elements[..] { [element] => self.lift(element, &format!("{e}._0")), elements => { let lifted: Vec = (elements.iter().enumerate()) .map(|(n, ty)| self.lift(ty, &format!("{e}._{n}"))) .collect(); match self.unique(ty) { true => format!("{}({})", self.sw(ty), lifted.join(", ")), false => format!("({})", lifted.join(", ")), } } }, other => unreachable!("{other:?} is never returned"), } } /// The Swift value of the C value `e` of type `ty`, which C lends a callback or closure /// for its call: bytes and text copied, and a scalar as it is. fn lift_lent(&mut self, ty: &Type, e: &str) -> String { match ty { Type::Str | Type::String => format!("Native.string(lent: {e})"), Type::Path | Type::PathBuf => format!("Native.path(lent: {e})"), Type::Slice | Type::Vec | Type::Bytes => format!("Native.bytes(lent: {e})"), Type::Option(inner) => match inner.base() { Type::Str | Type::String => format!("Native.string(lentOption: {e})"), Type::Path | Type::PathBuf => format!("Native.path(lentOption: {e})"), Type::Slice | Type::Vec | Type::Bytes => format!("Native.bytes(lentOption: {e})"), _ => self.lift(ty, e), }, Type::Ref(_, inner) => self.lift_lent(inner, e), ty => self.lift(ty, e), } } fn write(&mut self) { let abi = self.abi; let api = abi.api; for (c, ty) in &abi.ranges.clone() { self.range(c, ty); } // Every tuple holding a struct, wherever it is, a whole return's included, which C // returns through an out pointer per element rather than a struct. let methods = (api.records.iter().flat_map(|r| &r.methods)) .chain(api.enums.iter().flat_map(|e| &e.methods)) .chain(api.objects.iter().flat_map(|o| &o.methods)); let mut tuples = BTreeMap::new(); for function in api.functions.iter().chain(methods) { let types = (function.params.iter().map(|p| &p.ty)) .chain([&function.ok]) .chain(&function.err); for ty in types { crate::ir::each(&strip_refs(ty), &mut |ty| { if let Type::Tuple(elements) = ty && elements.len() > 1 && self.unique(ty) { tuples.insert(abi.tuple(elements), elements.clone()); } }); } } // Each named before any is written, since one tuple's fields may name another. for c in tuples.keys() { let name = self.claim(&self.class(c), &[], format!("the tuple `{c}`")); self.locked.insert( format!("tuple {}", abi.spell(&Type::Tuple(tuples[c].clone()))), name.clone(), ); self.classes.insert(c.clone(), name); } for (c, elements) in &tuples { self.tuple(c, elements); } for (c, n) in &abi.arrays { // Its bytes inline, in C's struct, as `InlineArray` would hold them from macOS 26. let name = Abi::array_class(*n); let _ = write!( self.types, "/// A Rust `[u8; {n}]`: exactly {n} bytes, held inline.\npublic struct {name}: Swift.Hashable, Swift.Sendable, Swift.MutableCollection, Swift.RandomAccessCollection {{\n\tvar _c: {c}\n\n\tinit(_c: {c}) {{\n\t\tself._c = _c\n\t}}\n\n\t/// The bytes of `bytes`, or nil unless it holds exactly {n}.\n\tpublic init?(_ bytes: some Swift.Collection) {{\n\t\tguard bytes.count == {n} else {{\n\t\t\treturn nil\n\t\t}}\n\t\t_c = {c}()\n\t\tSwift.withUnsafeMutableBytes(of: &_c.items) {{ $0.copyBytes(from: bytes) }}\n\t}}\n\n\tpublic var startIndex: Swift.Int {{ 0 }}\n\tpublic var endIndex: Swift.Int {{ {n} }}\n\n\tpublic subscript(i: Swift.Int) -> Swift.UInt8 {{\n\t\tget {{\n\t\t\tSwift.precondition(indices.contains(i), \"index out of range\")\n\t\t\treturn Swift.withUnsafeBytes(of: _c.items) {{ $0[i] }}\n\t\t}}\n\t\tset {{\n\t\t\tSwift.precondition(indices.contains(i), \"index out of range\")\n\t\t\tSwift.withUnsafeMutableBytes(of: &_c.items) {{ $0[i] = newValue }}\n\t\t}}\n\t}}\n\n\tpublic static func == (a: {name}, b: {name}) -> Swift.Bool {{\n\t\ta.elementsEqual(b)\n\t}}\n\n\tpublic func hash(into hasher: inout Swift.Hasher) {{\n\t\tSwift.withUnsafeBytes(of: _c.items) {{ hasher.combine(bytes: $0) }}\n\t}}\n}}\n\n" ); } for constant in &api.constants { let name = self.bare(&abi.name(&constant.path)).to_uppercase(); let name = self.claim(&name, &[], format!("const `{}`", constant.path.join("::"))); self.locked .insert(format!("const {}", constant.path.join("::")), name.clone()); let (ty, value) = match constant.value { Literal::Bool(b) => ("Swift.Bool".to_string(), b.to_string()), Literal::Int(int, v) => (sw_int(int).to_string(), v.to_string()), }; let _ = write!( self.top, "{}public let {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); } for function in &api.functions { for (code, _) in self.function(function, None, None, &[]) { self.top.push_str(&code); self.top.push('\n'); } } // `Swift.Error` is `Sendable`, so an error holding a value Swift keeps on one thread // is so unchecked: its value's run-time checks still keep it there. for (name, ty) in &self.thrown.clone() { let sw = self.sw(ty); let unchecked = match self.sendable(ty).is_empty() { true => ", @unchecked Sendable", false => "", }; let _ = write!( self.types, "/// A `{}` Rust returned as an error, or a closure throws for Rust to return.\npublic struct {name}: Swift.Error{unchecked}, CustomStringConvertible {{\n\tpublic let error: {sw}\n\n\tpublic init(error: {sw}) {{\n\t\tself.error = error\n\t}}\n\n\tpublic var description: Swift.String {{\n\t\t\"\\(error)\"\n\t}}\n}}\n\n", sw.trim_start_matches("Swift.") ); } for name in &self.conforms.clone() { let unchecked = match self.unsent_errors.contains(name) { true => ", @unchecked Sendable", false => "", }; let _ = write!(self.types, "extension {name}: Swift.Error{unchecked} {{}}\n\n"); } } /// The struct of a tuple holding an object's struct, which a Swift tuple cannot hold: /// its fields `_0`, `_1`, ... are the tuple's elements. fn tuple(&mut self, c: &str, elements: &[Type]) { let name = self.class(c); let types: Vec = elements.iter().map(|e| self.sw(e)).collect(); let fields: String = (types.iter().enumerate()) .map(|(n, sw)| format!("\tpublic var _{n}: {sw}\n")) .collect(); let params: Vec = (elements.iter().zip(&types).enumerate()) .map(|(n, (e, sw))| format!("_ _{n}: {}{sw}", self.ownership(e))) .collect(); let assigns: String = (0..elements.len()).map(|n| format!("\t\tself._{n} = _{n}\n")).collect(); let shown: Vec<&str> = types.iter().map(|t| t.trim_start_matches("Swift.")).collect(); let sendable = match self.sendable(&Type::Tuple(elements.to_vec())).is_empty() { true => "", false => ", Sendable", }; let _ = write!( self.types, "/// The tuple `({})`, as a struct, since it holds a value Swift cannot copy. Frozen, so\n/// another module may move each element out.\n@frozen public struct {name}: ~Copyable{sendable} {{\n{fields}\n\tpublic init({}) {{\n{assigns}\t}}\n}}\n\n", shown.join(", "), params.join(", ") ); } /// A struct for a range or pair of bounds, or an enum for a bound, and its conversions. fn range(&mut self, c: &str, ty: &Type) { let name = self.class(c); let p = &self.abi.prefix; let upper = format!("{}_BOUND", p.to_uppercase()); let code = match ty { Type::Range(int) => { let sw = sw_int(*int); let lower = |e: &str| lower_int(*int, e); let lift = |e: &str| lift_int(*int, e); format!( "/// Rust's `Range`: from `start`, up to but not including `end`.\npublic struct {name}: Hashable, Sendable {{\n\tpublic var start: {sw}\n\tpublic var end: {sw}\n\n\tpublic init(start: {sw}, end: {sw}) {{\n\t\tself.start = start\n\t\tself.end = end\n\t}}\n\n\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\t{name}(start: {}, end: {})\n\t}}\n\n\tfunc _lower() -> {c} {{\n\t\t{c}(start: {}, end: {})\n\t}}\n}}\n\n", lift("c.start"), lift("c.end"), lower("start"), lower("end"), ) } Type::Bound(int) => { let sw = sw_int(*int); format!( "/// Rust's `Bound`: what a range's start or end bound does.\npublic enum {name}: Hashable, Sendable {{\n\tcase unbounded\n\tcase included({sw})\n\tcase excluded({sw})\n\n\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\tswitch c.kind {{\n\t\tcase {upper}_UNBOUNDED: return .unbounded\n\t\tcase {upper}_INCLUDED: return .included({})\n\t\tcase {upper}_EXCLUDED: return .excluded({})\n\t\tdefault: fatalError(\"{c}: a bound's kind is invalid\")\n\t\t}}\n\t}}\n\n\tfunc _lower() -> {c} {{\n\t\tswitch self {{\n\t\tcase .unbounded: return {c}(kind: {upper}_UNBOUNDED, value: 0)\n\t\tcase .included(let value): return {c}(kind: {upper}_INCLUDED, value: {})\n\t\tcase .excluded(let value): return {c}(kind: {upper}_EXCLUDED, value: {})\n\t\t}}\n\t}}\n}}\n\n", lift_int(*int, "c.value"), lift_int(*int, "c.value"), lower_int(*int, "value"), lower_int(*int, "value"), ) } Type::Bounds(int) => { let bound = self.class(&self.abi.range(&Type::Bound(*int))); format!( "/// A range's start and end bounds, as Rust's `RangeBounds` gives them.\npublic struct {name}: Hashable, Sendable {{\n\tpublic var start: {bound}\n\tpublic var end: {bound}\n\n\tpublic init(start: {bound}, end: {bound}) {{\n\t\tself.start = start\n\t\tself.end = end\n\t}}\n\n\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\t{name}(start: {bound}._lift(c.start), end: {bound}._lift(c.end))\n\t}}\n\n\tfunc _lower() -> {c} {{\n\t\t{c}(start: start._lower(), end: end._lower())\n\t}}\n}}\n\n" ) } other => unreachable!("{other:?} is no range"), }; self.types.push_str(&code); } /// The members a type's std traits export, with the protocols they conform it to: /// `Display` is `description`, `Debug` `debugDescription`, `PartialEq` `==`, `Hash` /// `hash(into:)`, `Default` a static `default()`, and `Clone` an object's `clone()`. fn traits( &mut self, ty: &Type, c: &str, t: crate::ir::Traits, body: &mut Vec, members: &mut Vec, protocols: &mut Vec<&'static str>, ) { let name = self.sw(ty); let object = matches!(ty, Type::Object(_)); let unique = self.unique(ty); // One whose checks can fail throws, so conforms to no protocol of these, whose // requirements cannot throw; any other's checks never fail. let status = self.abi.traits_status_of(ty); // The statements lowering a value receiver for the function `what`, which on a target // the type is not on throws where it can. let value = |what: &str| { let arena = match self.arena(ty) { true => format!("let a_ = Native.Arena(\"{what}\")\n\t\tdefer {{ a_.finish() }}\n\t\t"), false => String::new(), }; format!( "{}Native.check()\n\t\t{arena}", self.on(self.on, what, "\n\t\t", status) ) }; let lower = match self.throwing(ty) { true => format!("try self._lower({})", self.arena_arg(ty)), false => format!("self._lower({})", self.arena_arg(ty)), }; // The statements calling `call`, the C call with its arguments, unclosed, of the // function `what`, returning `lift` of its result. let call = |call: &str, what: &str, lift: &dyn Fn(&str) -> String| match status { true => format!( "var s_: Swift.Int32 = 0\n\t\tlet r_ = {call}, &s_)\n\t\ttry Native.status(s_, \"{what}\")\n\t\treturn {}", lift("r_") ), false => format!("return {}", lift(&format!("{call})"))), }; // The body calling `{c}_` of the receiver, returning `lift` of its result. let unary = |suffix: &str, lift: &dyn Fn(&str) -> String| { let what = format!("{c}_{suffix}"); match (object, unique) { (true, true) => call(&format!("{what}(self.handle"), &what, lift), (true, false) => { let with = match status { true => format!("try self.handle.with(\"{what}\")"), false => "self.handle.with".to_string(), }; format!( "return {with} {{ h_ in\n\t\t\t{}\n\t\t}}", call(&format!("{what}(h_"), &what, lift).replace("\n\t\t", "\n\t\t\t") ) } (false, _) => format!( "{}var c_ = {lower}\n\t\t{}", value(&what), call(&format!("{what}(&c_"), &what, lift) ), } }; let throws = match status { true => " throws", false => "", }; // A property's body, in a getter that throws if the call can. let getter = |body: String| match status { true => format!("get throws {{\n\t\t\t{}\n\t\t}}", body.replace("\n\t\t", "\n\t\t\t")), false => body, }; let text = |r: &str| format!("Native.string({r})"); if t.display { if !status { protocols.push("CustomStringConvertible"); } members.push("description".to_string()); body.push(format!( "\tpublic var description: Swift.String {{\n\t\t{}\n\t}}\n", getter(unary("to_string", &text)) )); } if t.debug { if !status { protocols.push("CustomDebugStringConvertible"); } members.push("debugDescription".to_string()); body.push(format!( "\t/// Rust's `Debug` form.\n\tpublic var debugDescription: Swift.String {{\n\t\t{}\n\t}}\n", getter(unary("debug", &text)) )); } if object && t.clone { members.push("clone".to_string()); let lift = |r: &str| format!("{name}(raw: {r})"); body.push(format!( "\t/// A new handle to a clone.\n\tpublic func clone(){throws} -> {name} {{\n\t\t{}\n\t}}\n", unary("clone", &lift) )); } if t.eq { // `Hash` agrees with `PartialEq`, so a type with both hashes as Rust does. if !status { protocols.push(match t.hash { true => "Hashable", false => "Equatable", }); } let what = format!("{c}_eq"); let same = |r: &str| r.to_string(); let compare = match (object, unique) { (true, true) => call(&format!("{what}(a.handle, b.handle"), &what, &same), (true, false) => { let with = |h: &str| match status { true => format!("try {h}.handle.with(\"{what}\")"), false => format!("{h}.handle.with"), }; format!( "return {} {{ a_ in {} {{ b_ in\n\t\t\t{}\n\t\t}} }}", with("a"), with("b"), call(&format!("{what}(a_, b_"), &what, &same).replace("\n\t\t", "\n\t\t\t") ) } (false, _) => format!( "{}var ca_ = {}\n\t\tvar cb_ = {}\n\t\t{}", value(&what), lower.replacen("self.", "a.", 1), lower.replacen("self.", "b.", 1), call(&format!("{what}(&ca_, &cb_"), &what, &same) ), }; let borrowing = match unique { true => "borrowing ", false => "", }; body.push(format!( "\tpublic static func == (a: {borrowing}{name}, b: {borrowing}{name}){throws} -> Swift.Bool {{\n\t\t{compare}\n\t}}\n" )); } if t.hash { members.push("hash(into:)".to_string()); let combine = |r: &str| format!("hasher.combine({r})"); body.push(format!( "\t/// Rust's `Hash`, agreeing with `==`.\n\tpublic func hash(into hasher: inout Swift.Hasher){throws} {{\n\t\t{}\n\t}}\n", unary("hash", &combine) )); } if t.default { members.push("static default".to_string()); let lift = match ty { Type::Object(_) => format!("{name}(raw: {c}_default())"), _ => format!("{name}._lift({c}_default())"), }; // A constructor the target lacks throws, as a function's call does. let limited = !self.abi.api.everywhere(self.on); let throws = match limited { true => " throws", false => "", }; body.push(format!( "\t/// Rust's `Default`.\n\tpublic static func `default`(){throws} -> {name} {{\n\t\t{}Native.check()\n\t\treturn {lift}\n\t}}\n", self.on(self.on, &format!("{c}_default"), "\n\t\t", limited) )); } } /// Each method of a type, as members of its Swift type. fn methods( &mut self, methods: &[Function], owner: &Ty, ty: &Type, body: &mut Vec, members: &mut Vec, ) { for method in methods { for (code, member) in self.function(method, Some(owner), Some(ty), members) { members.push(member); body.push(indent(&code)); } } } 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); if record.opaque.is_some() { return self.opaque(i); } let fields: Vec<(String, String)> = (record.fields.iter()) .map(|f| (field_name(&f.name), self.sw(&f.ty))) .collect(); let mut members: Vec = fields.iter().map(|(f, _)| unquote(f)).collect(); let mut body: Vec = (record.fields.iter().zip(&fields)) .map(|(f, (name, sw))| format!("{}\tpublic var {name}: {sw}\n", docs(&f.docs, "\t"))) .collect(); let params: Vec = fields .iter() .map(|(f, sw)| match record.tuple { true => format!("_ {f}: {sw}"), false => format!("{f}: {sw}"), }) .collect(); let assigns: String = fields.iter().map(|(f, _)| format!("\t\tself.{f} = {f}\n")).collect(); body.push(format!("\tpublic init({}) {{\n{assigns}\t}}\n", params.join(", "))); let mut protocols = self.sendable(&ty); self.traits(&ty, &c, record.traits, &mut body, &mut members, &mut protocols); self.methods(&record.methods, &Ty::Struct(c.clone()), &ty, &mut body, &mut members); self.distinct(&rust, &members); // Its conversions. let lifted: Vec = (record.fields.iter().zip(&fields)) .map(|(f, (name, _))| { let e = format!("c.{}", kw(&abi::escape(&f.name))); let value = self.lift(&f.ty, &e); match record.tuple { true => value, false => format!("{}: {value}", unquote(name)), } }) .collect(); let lowered: Vec = (record.fields.iter().zip(&fields)) .map(|(f, (name, _))| { let value = self.lower(&f.ty, &format!("self.{name}")); format!("{}: {value}", abi::escape(&f.name)) }) .collect(); let arena = match self.arena(&ty) { true => "_ a_: Native.Arena", false => "", }; body.push(format!( "\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\t{name}({})\n\t}}\n", lifted.join(", ") )); let throws = match self.throwing(&ty) { true => " throws", false => "", }; body.push(format!( "\tfunc _lower({arena}){throws} -> {c} {{\n\t\t{c}({})\n\t}}\n", lowered.join(", ") )); let text = format!("{rust}\n\n{}", record.docs); let _ = write!( self.types, "{}public struct {name}{} {{\n{}}}\n\n", docs(text.trim(), ""), conform(&protocols), body.join("\n") ); } /// A `Copy` type with private fields: a struct over the bytes of its C struct, which /// only Rust makes or reads. Swift copies it as it copies the bytes. fn opaque(&mut self, i: usize) { let abi = self.abi; let record = &abi.api.records[i]; 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 mut members = Vec::new(); let mut body = vec![format!( "\t/// Its bytes, which only Rust reads.\n\tlet c_: {c}\n\n\tprivate init(c_: {c}) {{\n\t\tself.c_ = c_\n\t}}\n" )]; let mut protocols = self.sendable(&ty); self.traits(&ty, &c, record.traits, &mut body, &mut members, &mut protocols); self.methods(&record.methods, &Ty::Struct(c.clone()), &ty, &mut body, &mut members); self.distinct(&rust, &members); body.push(format!( "\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\t{name}(c_: c)\n\t}}\n" )); body.push(format!("\tfunc _lower() -> {c} {{\n\t\tc_\n\t}}\n")); let text = format!("{rust}\n\n{}", record.docs); let _ = write!( self.types, "{}public struct {name}{} {{\n{}}}\n\n", docs(text.trim(), ""), conform(&protocols), body.join("\n") ); } 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 upper = c.to_uppercase(); let mut members = Vec::new(); let mut cases = Vec::new(); let mut lifts = Vec::new(); let mut lowers = Vec::new(); for variant in &e.variants { let snake = abi::snake(&variant.name); let case = member(&snake, &["init"]); let labels = variant.fields.iter().map(|f| match variant.tuple { true => "_".to_string(), false => unquote(&field_name(&f.name)), }); members.push(full(true, &case, labels)); let tag = format!("{upper}_{}", snake.to_uppercase()); let member = kw(&abi::escape(&snake)); let fields: Vec = (variant.fields.iter()) .map(|f| match variant.tuple { true => self.sw(&f.ty), false => format!("{}: {}", field_name(&f.name), self.sw(&f.ty)), }) .collect(); match fields.is_empty() { true => cases.push(format!("\tcase {case}\n")), false => cases.push(format!("\tcase {case}({})\n", fields.join(", "))), } // A value of a variant the library's target lacks is refused as it crosses. let refused = self.on(variant.on, &format!("{c}.{}", variant.name), "\n\t\t\t", false); if e.plain() { lifts.push(format!("\t\tcase {tag}: return .{case}")); lowers.push(format!("\t\tcase .{case}:\n\t\t\t{refused}return {tag}")); continue; } let lifted: Vec = (variant.fields.iter()) .map(|f| { let value = self.lift(&f.ty, &format!("c.{member}.{}", kw(&abi::escape(&f.name)))); match variant.tuple { true => value, false => format!("{}: {value}", unquote(&field_name(&f.name))), } }) .collect(); let binds: Vec = (0..variant.fields.len()).map(|k| format!("let p{k}_")).collect(); let payload = abi::payload(&c, &variant.name); let lowered: Vec = (variant.fields.iter().enumerate()) .map(|(k, f)| format!("{}: {}", abi::escape(&f.name), self.lower(&f.ty, &format!("p{k}_")))) .collect(); match variant.fields.is_empty() { true => { lifts.push(format!("\t\tcase {tag}: return .{case}")); lowers.push(format!("\t\tcase .{case}:\n\t\t\t{refused}c.tag = {tag}")); } false => { lifts.push(format!("\t\tcase {tag}: return .{case}({})", lifted.join(", "))); lowers.push(format!( "\t\tcase .{case}({}):\n\t\t\t{refused}c.tag = {tag}\n\t\t\tc.{member} = {payload}({})", binds.join(", "), lowered.join(", ") )); } } } let mut body = cases; let mut protocols = self.sendable(&ty); self.traits(&ty, &c, e.traits, &mut body, &mut members, &mut protocols); let owner = abi.ty(&ty); self.methods(&e.methods, &owner, &ty, &mut body, &mut members); self.distinct(&rust, &members); let (matched, invalid) = match e.plain() { true => ("c", "an invalid value"), false => ("c.tag", "an invalid tag"), }; body.push(format!( "\tstatic func _lift(_ c: {c}) -> {name} {{\n\t\tswitch {matched} {{\n{}\n\t\tdefault: fatalError(\"{c}: {invalid}\")\n\t\t}}\n\t}}\n", lifts.join("\n") )); let arena = match self.arena(&ty) { true => "_ a_: Native.Arena", false => "", }; body.push(match e.plain() { true => format!( "\tfunc _lower() -> {c} {{\n\t\tswitch self {{\n{}\n\t\t}}\n\t}}\n", lowers.join("\n") ), false => format!( "\tfunc _lower({arena}){} -> {c} {{\n\t\tvar c = {c}()\n\t\tswitch self {{\n{}\n\t\t}}\n\t\treturn c\n\t}}\n", match self.throwing(&ty) { true => " throws", false => "", }, lowers.join("\n") ), }); let text = format!("{rust}\n\n{}", e.docs); let _ = write!( self.types, "{}public enum {name}{} {{\n{}}}\n\n", docs(text.trim(), ""), conform(&protocols), body.join("\n") ); } /// `Sendable`, for a value whose every handle Rust lets cross threads: see /// [`Self::sends`]. fn sendable(&self, ty: &Type) -> Vec<&'static str> { let mut handles = Vec::new(); self.abi.api.handles(ty, &mut handles, &mut Vec::new()); match handles.iter().all(|&i| self.sends(i)) { true => vec!["Sendable"], false => Vec::new(), } } /// Whether object `i` is `Sendable`: a class shares its value between the threads that /// hold it, so only one Rust shares, `Send` and `Sync`; a noncopyable struct only moves /// to another, so one that is `Send`. Swift's compiler then keeps any other on one /// thread at a time, as its run-time checks do. fn sends(&self, i: usize) -> bool { let object = &self.abi.api.objects[i]; object.send && (object.sync || self.unique(&Type::Object(i))) } 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 rust = abi.api.rust(&object.path, &object.args); let ty = Type::Object(i); let unique = self.unique(&ty); let mut members = vec!["handle".to_string()]; let mut body = vec![match unique { // A lend ends with `_end`, which leaves Rust the handle it lent to free. true => format!( "\tlet handle: OpaquePointer?\n\n\tinit(raw: OpaquePointer?) {{\n\t\thandle = raw\n\t}}\n\n\tdeinit {{\n\t\t{c}_free(handle)\n\t}}\n\n\t@usableFromInline consuming func _end() {{\n\t\tdiscard self\n\t}}\n" ), false => format!( "\tlet handle: Native.Handle\n\n\tinit(raw: OpaquePointer?) {{\n\t\thandle = Native.Handle(raw, {c}_free, \"{name}\")\n\t}}\n\n\tinit(lent raw: OpaquePointer?) {{\n\t\thandle = Native.Handle(raw, nil, \"{name}\")\n\t}}\n\n\tdeinit {{\n\t\thandle.drop()\n\t}}\n" ), }]; // Rust checks each borrow at run time, so it is `Sendable` unless its value stays on // one thread, or is shared on one at a time, which Swift's compiler then enforces. let mut protocols = match self.sends(i) { true => vec!["@unchecked Sendable"], false => Vec::new(), }; self.traits(&ty, &c, object.traits, &mut body, &mut members, &mut protocols); let owner = Ty::Handle { name: c.clone(), constant: false, }; self.methods(&object.methods, &owner, &ty, &mut body, &mut members); self.distinct(&rust, &members); let text = format!("{rust}\n\n{}", object.docs); let docs = docs(text.trim(), ""); let body = body.join("\n"); if !unique { let _ = write!( self.types, "{docs}public final class {name}{} {{\n{body}}}\n\n", conform(&protocols) ); return; } let sendable = match self.sends(i) { true => ", @unchecked Sendable", false => "", }; let _ = write!( self.types, "{docs}public struct {name}: ~Copyable{sendable} {{\n{body}}}\n\n" ); // Swift 6.4 takes a noncopyable type's `Equatable` and `Hashable`, but not yet its // `CustomStringConvertible` or `CustomDebugStringConvertible`, whose members it keeps. if let Some(equal) = protocols.iter().find(|p| ["Equatable", "Hashable"].contains(p)) { let _ = write!( self.types, "#if compiler(>=6.4)\nextension {name}: {equal} {{}}\n#endif\n\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 rust = callback.path.join("::"); let mut body = Vec::new(); let mut members = Vec::new(); let mut table = vec![format!("free: {{ data in Box.release(data) }}")]; for method in &callback.methods { let member = member(&abi::snake(method.name()), &[]); crate::lock::function(&mut self.locked, method, &member); members.push(full(false, &member, method.params.iter().map(|_| "_".to_string()))); let params: Vec = (method.params.iter().zip(locals(&method.params))) .map(|(p, name)| format!("_ {name}: {}", self.sw(&p.ty))) .collect(); let ret = match method.ok { Type::Unit => String::new(), _ => format!(" -> {}", self.sw(&method.ok)), }; body.push(format!( "{}\tfunc {member}({}){ret}", docs(&method.docs, "\t"), params.join(", ") )); let ps: Vec = (0..method.params.len()).map(|k| format!("p{k}_")).collect(); let args: Vec = (method.params.iter().zip(&ps)) .map(|(p, e)| self.lift_lent(&p.ty, e)) .collect(); let call = format!("Box.unbox(data).{member}({})", args.join(", ")); let call = match method.ok { Type::Unit => call, _ => Self::trapping(self.lower(&method.ok, &call)), }; let mut closure_params = vec!["data".to_string()]; closure_params.extend(ps); table.push(format!( "{}: {{ {} in {call} }}", method.name(), closure_params.join(", ") )); } self.distinct(&rust, &members); let text = format!( "{rust}: implemented in Swift. Rust calls its methods from any thread, and releases\nthe implementation once it drops it.\n\n{}", callback.docs ); let _ = write!( self.types, "{}public protocol {name}: Sendable {{\n{}\n}}\n\n", docs(text.trim(), ""), body.join("\n\n") ); let _ = write!( self.natives, "\tnonisolated(unsafe) static let vtable_{c}: UnsafeMutablePointer<{c}_vtable> = {{\n\t\tlet vtable = UnsafeMutablePointer<{c}_vtable>.allocate(capacity: 1)\n\t\tvtable.initialize(to: {c}_vtable(\n\t\t\t{}))\n\t\treturn vtable\n\t}}()\n\n\tstatic func lower_{c}(_ implementation: any {name}) -> {c} {{\n\t\t{c}(vtable: vtable_{c}, data: Box.give(implementation))\n\t}}\n\n", table.join(",\n\t\t\t") ); } /// The Swift statement closing each object the value `e` of type `ty` holds, once a /// call moved them out. fn close(&mut self, ty: &Type, e: &str) -> String { match ty { // A struct's container is borrowed, since `if let` and `for in` would consume it. Type::Option(inner) if self.unique(inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); format!("Native.option({e}, {{ {v} in {close} }}, ())") } Type::List(_, inner) if self.unique(inner) => { let i = self.fresh("i"); let close = self.close(inner, &format!("{e}[{i}]")); format!("for {i} in {e}.indices {{ {close} }}") } Type::Option(inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); format!("if let {v} = {e} {{ {close} }}") } Type::Box(inner) => self.close(inner, e), Type::Tuple(elements) if elements.len() == 1 => self.close(&elements[0], e), Type::Tuple(elements) => { let mut closes = Vec::new(); for (k, ty) in elements.iter().enumerate() { if self.moved(ty) { let element = self.element(elements, e, k); closes.push(self.close(ty, &element)); } } closes.join("; ") } Type::List(_, inner) => { let v = self.fresh("v"); let close = self.close(inner, &v); format!("for {v} in {e} {{ {close} }}") } _ => format!("{e}.handle.close()"), } } /// How the call passes `param`, the C parameter `c`, whose Swift value is `e`, the /// `k`th, which `function` takes. fn arg(&mut self, ty: &Type, c: &Ty, e: &str, k: usize, tr: &str, what: &str) -> (Arg, bool) { let abi = self.abi; let mut arg = Arg::default(); let mut arena = false; if self.moved(ty) { arg.after.push(self.close(ty, e)); } match (ty, c) { // Rust keeps the closure, boxed, until it calls `free`. (Type::Closure(closure_), Ty::Fn(..)) if closure_.kept => { let sw = self.sw(ty); arg.exprs.push(self.trampoline(ty, closure_)); arg.exprs.push(format!("Native.Box<{sw}>.give({e})")); arg.gives = true; arg.exprs .push(format!("{{ data_ in Native.Box<{sw}>.release(data_) }}")); } (Type::Closure(closure_), Ty::Fn(..)) => { let (f, g, d) = (format!("f{k}_"), format!("g{k}_"), format!("d{k}_")); arg.open = Some(( format!( "{tr}withoutActuallyEscaping({e}) {{ {f} in\n\tvar {g} = {f}\n\treturn {tr}withUnsafeMutablePointer(to: &{g}) {{ {d} in" ), "}\n}".to_string(), )); arg.exprs.push(self.trampoline(ty, closure_)); arg.exprs.push(d); } (Type::Ref(_, inner), Ty::ForeignReader) if **inner == Type::Reader => { let r = format!("r{k}_"); arg.open = Some((format!("{tr}Native.reader(&{e}) {{ {r} in"), "}".to_string())); arg.exprs.push(r); } (Type::Callback(i, _), _) => { arg.exprs.push(format!("Native.lower_{}({e})", abi.callback(*i))); arg.gives = true; } (Type::Waker, _) => { arg.exprs.push(format!("Native.waker({e})")); arg.gives = true; } (Type::Future, _) => { arg.exprs.push(format!("Native.future({e})")); arg.gives = true; } (ty, Ty::Buf) if Abi::is_buf(ty) || matches!(ty.base(), Type::Option(inner) if Abi::is_buf(inner)) => { let b = format!("b{k}_"); arg.open = Some((format!("{tr}Native.take({e}) {{ {b} in"), "}".to_string())); arg.exprs.push(b); arg.takes = true; } // A struct the call borrows or consumes, so it lives until the call returns. (ty, Ty::Handle { .. }) if self.unique(ty) => arg.exprs.push(match ty.base() { Type::Option(_) => format!("Native.option({e}, {{ $0.handle }}, nil)"), _ => format!("{e}.handle"), }), (ty, Ty::Handle { .. }) => { let h = format!("h{k}_"); let open = match ty.base() { Type::Option(_) => format!("{tr}Native.with({what}{e}?.handle, {{ {h} in"), _ => format!("{tr}{e}.handle.with({what}{{ {h} in"), }; arg.open = Some((open, "})".to_string())); arg.exprs.push(h); } (ty, _) => { arena = self.arena(ty); let lowered = self.lower(ty, e); arg.throws = lowered.contains("try "); arg.exprs.push(lowered); } } (arg, arena) } /// The C function C calls for `closure`, of type `ty`, lent for a call or kept boxed: /// it lends each object as its type, ended once it returns, and copies one taken by /// value. A struct lent `&mut` is `inout`, which Swift may assign another value; Rust's /// stays its own, so that traps. What it returns or throws is Rust's to own. fn trampoline(&mut self, ty: &Type, closure: &Closure) -> String { let (lent, ret) = (&closure.params, &closure.ok); let ps: Vec = (0..lent.len()).map(|k| format!("p{k}_")).collect(); let mut body = vec![match closure.kept { true => format!("let f_ = Native.Box<{}>.unbox(data_)", self.sw(ty)), false => format!( "let f_ = data_!.assumingMemoryBound(to: ({}).self).pointee", self.sw(ty) ), }]; let mut args = Vec::new(); let mut ends = Vec::new(); for (k, (ty, p)) in lent.iter().zip(&ps).enumerate() { match ty { Type::Ref(m, object) if self.unique(object) => { let l = format!("l{k}_"); let name = self.sw(object); match m { Mutability::Not => { body.push(format!("let {l} = {name}(raw: {p})")); args.push(l.clone()); } Mutability::Mut => { body.push(format!("var {l} = {name}(raw: {p})")); args.push(format!("&{l}")); ends.push(format!( "if {l}.handle != {p} {{ fatalError(\"{name}: a lent handle was replaced\") }}" )); } } ends.push(format!("{l}._end()")); } Type::Ref(_, object) if matches!(**object, Type::Object(_)) => { let l = format!("l{k}_"); body.push(format!("let {l} = {}(lent: {p})", self.sw(object))); body.push(format!("defer {{ {l}.handle.end() }}")); args.push(l); } ty => args.push(self.lift_lent(ty, p)), } } let mut params = vec!["data_".to_string()]; params.extend(ps); let call = format!("f_({})", args.join(", ")); match (&closure.err, ret, ends.is_empty()) { (Some(_), ret, _) => { // A `Void` binding is a warning, which the build makes an error. let mut done = vec![if *ret == Type::Unit { format!("try {call}") } else { format!("let r_ = try {call}") }]; done.extend(ends.iter().cloned()); if *ret != Type::Unit { done.push(format!("ok_!.pointee = {}", self.returned(ret, "r_"))); params.push("ok_".to_string()); } done.push("return true".to_string()); let mut failed = ends; // A `StringError`'s description is its string, so Rust's error returns as it was. failed.push("err_!.pointee = Native.owned(\"\\(error)\")".to_string()); failed.push("return false".to_string()); params.push("err_".to_string()); body.push(format!( "do {{\n\t\t{}\n\t}} catch {{\n\t\t{}\n\t}}", done.join("\n\t\t"), failed.join("\n\t\t") )); } (None, Type::Unit, _) => { body.push(call); body.extend(ends); } (None, ret, true) => body.push(format!("return {}", self.returned(ret, &call))), (None, ret, false) => { body.push(format!("let r_ = {call}")); body.extend(ends); body.push(format!("return {}", self.returned(ret, "r_"))); } } format!("{{ {} in\n\t{}\n}}", params.join(", "), body.join("\n\t")) } /// The C value of `e`, of type `ty`, which a closure returns for Rust to own: a value /// as it lowers, and text in a buffer `buf_copy` made. fn returned(&mut self, ty: &Type, e: &str) -> String { match ty { Type::Str | Type::String | Type::PathBuf => format!("Native.owned({e})"), Type::Option(inner) if matches!(**inner, Type::Str | Type::String | Type::PathBuf) => { format!("({e}.map {{ Native.owned($0) }} ?? Native.none)") } ty => Self::trapping(self.lower(ty, e)), } } /// `function`'s Swift forms and their member names, members of `owner` (whose IR type /// is `owner_ty`) if it has one, apart from the members `taken` names: an overload for /// each choice of passing or leaving out each `Option<&T>` of a struct, since an optional /// holds a struct only by consuming it. fn function( &mut self, function: &Function, owner: Option<&Ty>, owner_ty: Option<&Type>, taken: &[String], ) -> Vec<(String, String)> { let optional: Vec = (function.params.iter().enumerate()) .filter(|(_, p)| self.lent_option(&p.ty)) .map(|(k, _)| k) .collect(); assert!( optional.len() <= MAX_OPTIONAL, "the driver refuses past the bound first" ); (0..1usize << optional.len()) .map(|mask| { let left: BTreeSet = (optional.iter().enumerate()) .filter(|(bit, _)| mask & (1 << bit) == 0) .map(|(_, k)| *k) .collect(); self.overload(function, owner, owner_ty, taken, &left) }) .collect() } /// Whether `ty` is an `Option<&T>` of a struct. fn lent_option(&self, ty: &Type) -> bool { lent_option(&self.structs, ty) } /// One of `function`'s Swift forms, apart from the members `taken` names, leaving out /// the optional borrowed parameters in `left`, which pass `None`. fn overload( &mut self, function: &Function, owner: Option<&Ty>, owner_ty: Option<&Type>, taken: &[String], left: &BTreeSet, ) -> (String, String) { let abi = self.abi; let export = abi.export(function, owner); let c_name = export.call.name.clone(); 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(_)) => &["handle", "init", "deinit"], Some(_) => &["init"], 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 mut member = member(snake, reserved); let receiver = function.receiver.filter(|_| owner.is_some()); let object = matches!(owner, Some(Ty::Handle { .. })) && receiver.is_some(); // A struct's method takes `self` as Rust does: by value, it consumes it, and Swift // then frees the handle Rust moved the value out of. let unique = owner_ty.is_some_and(|ty| self.unique(ty)); // A value's `&mut self` is too, as Rust writes back the value it changed. let value = matches!(export.call.params.first(), Some((_, Ty::InOut(_)))); let mutation = match receiver { Some(Receiver::Owned) if unique => "consuming ", Some(Receiver::Mut) if unique || value => "mutating ", _ => "", }; // A call that can fail a check throws, as do a future and a `Result`. let status = export.call.status().is_some(); let everywhere = abi.api.everywhere(function.on); let throws = function.future || function.err.is_some() || status || !everywhere; // A future's error throws from the call that starts it, as from its polls. let tr = match function.err.is_some() || status { true => "try ", false => "", }; // A class's handle closed throws where the call can. let what = match status { true => format!("\"{c_name}\", "), false => String::new(), }; let mut prelude = Vec::new(); if !object { prelude.push("Native.check()".to_string()); } if !everywhere { prelude.push(format!( "try Native.on({}, \"{c_name}\")", function.on.0 & abi.api.all().0 )); } let mut arena = false; let mut args: Vec = Vec::new(); let mut c_params = export.call.params.iter(); 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 mut arg = Arg::default(); match c { Ty::Handle { .. } if unique => arg.exprs.push("self.handle".to_string()), Ty::Handle { .. } => { arg.open = Some((format!("{tr}self.handle.with({what}{{ h_ in"), "})".to_string())); arg.exprs.push("h_".to_string()); let copy = matches!(ty, Type::Object(i) if abi.api.objects[i].copy); if receiver == Receiver::Owned && !copy { arg.after.push("self.handle.close()".to_string()); } } _ => { arena |= self.arena(&ty); let t = match self.throwing(&ty) { true => "try ", false => "", }; prelude.push(format!("var c_self_ = {t}self._lower({})", self.arena_arg(&ty))); if value { prelude.push(format!("defer {{ self = {} }}", self.lift(&ty, "c_self_"))); } arg.exprs.push("&c_self_".to_string()); } } args.push(arg); } let mut params = Vec::new(); let names = locals(&function.params); for (k, (param, name)) in function.params.iter().zip(&names).enumerate() { let (_, c) = c_params.next().expect("each parameter has its C one"); if let Type::Closure(closure_) = ¶m.ty { c_params.next().expect("a closure has its data"); if closure_.kept { c_params.next().expect("a kept closure has its free"); } } if left.contains(&k) { args.push(Arg { exprs: vec!["nil".to_string()], ..Arg::default() }); continue; } if let Type::Option(lent) = ¶m.ty && self.lent_option(¶m.ty) { // Labelled, as a defaulted argument is, so that overloads leaving out // different ones differ in name. params.push(format!("{name}: borrowing {}", self.sw(lent))); args.push(Arg { exprs: vec![format!("{name}.handle")], ..Arg::default() }); continue; } // A value Rust writes back is `inout`, as is an object it borrows mutably. let ownership = match (param.ty.written(), ¶m.ty) { (true, _) => "inout ", // Rust keeps the waker past the call. (false, Type::Waker | Type::Future) => "@escaping ", (false, Type::Closure(closure_)) if closure_.kept => "@escaping ", // Rust reads and seeks the reader in place. (false, Type::Ref(_, inner)) if **inner == Type::Reader => "inout ", (false, _) => self.ownership(¶m.ty), }; params.push(format!("_ {name}: {ownership}{}", self.sw(¶m.ty))); let (arg, needs) = self.arg(¶m.ty, c, name, k, tr, &what); arena |= needs; args.push(arg); } let outs: Vec<(String, Ty)> = c_params.filter(|(_, ty)| !abi::is_status(ty)).cloned().collect(); // What runs once the call returns, gated on its checks passing when it can fail one: // a failed check, or an argument whose lowering throws, leaves every argument as it // was, as Rust ran nothing. let ran = status && (function.params.iter().any(|p| p.ty.written()) || args.iter().any(|a| !a.after.is_empty())); if ran { prelude.push("var c_ran_ = false".to_string()); } let gate = |stmts: &str| match ran { true => format!("defer {{ if c_ran_ {{ {stmts} }} }}"), false => format!("defer {{ {stmts} }}"), }; // Each value passed for `&mut` takes what Rust wrote back, once the call's own // access to it ends, on every path the call ran, a throw included. let mut written = Vec::new(); for (param, name) in function.params.iter().zip(&names).filter(|(p, _)| p.ty.written()) { let out = Abi::written(function, &abi::escape(¶m.name)); let (_, ty) = outs .iter() .find(|(n, _)| *n == out) .expect("a written parameter has its out"); prelude.push(self.out_decl(&out, ty)); let lifted = self.lift(param.ty.base(), &format!("c_{out}_")); prelude.push(gate(&format!("{name} = {lifted}"))); written.push(out); } if arena { prelude.insert( 1.min(prelude.len()), format!("let a_ = Native.Arena(\"{c_name}\")\ndefer {{ a_.finish() }}"), ); // Past the receiver, which Rust only reads, Rust takes each value passed. prelude.push("a_.take = true".to_string()); } let after: Vec = args.iter().flat_map(|a| a.after.clone()).collect(); if !after.is_empty() { prelude.push(gate(&after.join("; "))); } // A lowering that throws runs before any box or buffer is given, which the call // alone would take: a throw between them would leak it. if args.iter().any(|a| a.gives || a.takes) { for (k, arg) in args.iter_mut().enumerate().filter(|(_, a)| a.throws) { prelude.push(format!("let c_arg{k}_ = {}", arg.exprs[0])); arg.exprs[0] = format!("c_arg{k}_"); } } let exprs: Vec = args.iter().flat_map(|a| a.exprs.clone()).collect(); // A tuple of one returned whole is its element, written through its one out pointer. let ok = match &function.ok { Type::Tuple(elements) if elements.len() == 1 => strip_refs(&elements[0]), ok => strip_refs(ok), }; let err = function.err.as_ref().map(strip_refs); let thrown = err.as_ref().map(|e| self.thrown(e)); let mut inner = Vec::new(); // A failed check writes its status, which throws once the call returns. let (status_arg, check) = match status { true => { inner.push("var c_status_: Swift.Int32 = 0".to_string()); ( vec!["&c_status_".to_string()], Some(match ran { true => format!("try Native.status(c_status_, \"{c_name}\")\nc_ran_ = true"), false => format!("try Native.status(c_status_, \"{c_name}\")"), }), ) } false => (Vec::new(), None), }; let tail; // The call that makes the future unpolled, as `f_`, its status checked: what an eager // call starts with, and, freed, what a cancelled task runs instead of the start, as // Rust drops a future it never awaits. // The arena frees what it gave Rust unless the call reached C, which then owns it. let reached = |call: String| match arena { true => format!("a_.ran({call})"), false => call, }; // A future that is not `Send` made from none is made on a home, where it stays, so // a poll from any thread of the task's executor runs there. let make = export.homed_call().map_or_else(|| c_name.clone(), |homed| homed.name); let call = reached(format!( "{make}({})", exprs.iter().chain(&status_arg).cloned().collect::>().join(", ") )); let made = check .as_ref() .map(|check| format!("var c_status_: Swift.Int32 = 0\nlet f_ = {call}\n{check}")); let mut cancelled = None; if let Some(abi::Future { start, poll, free, .. }) = &export.future { cancelled = Some(match &made { Some(made) => format!("{made}\n{}(f_)", free.name), None => format!("{}({call})", free.name), }); // A poll that can fail, of a future that is not `Send`, throws. let poll_status = poll.status().is_some(); let poll_outs: Vec<(String, Ty)> = poll.params[2..poll.params.len() - usize::from(poll_status)].to_vec(); let decls: Vec = poll_outs.iter().map(|(n, ty)| self.out_decl(n, ty)).collect(); let ptrs: Vec = poll_outs.iter().map(|(n, _)| format!("&c_{n}_")).collect(); let ready = match ok { Type::Unit => "()".to_string(), _ => self.lift_outs(&function.ok, &ok), }; let upper = abi.prefix.to_uppercase(); // `.some` explicitly, since a `nil` output would read as the poll's pending. let mut cases = vec![format!("case {upper}_POLL_READY: return .some({ready})")]; if let (Some(err), Some(thrown)) = (&err, &thrown) { let lifted = self.lift(err, "c_err_"); cases.push(format!( "case {upper}_POLL_ERROR: throw {}", thrown_value(thrown, &lifted) )); } cases.push("default: return nil".to_string()); let cases = cases.join("\n"); inner.extend(decls.iter().cloned()); let start_args: Vec = (exprs.iter().cloned()) .chain(ptrs.iter().cloned()) .chain(["&f_".to_string()]) .chain(status_arg.iter().cloned()) .collect(); let start = export .homed_start() .map_or_else(|| start.name.clone(), |homed| homed.name); let started = reached(format!("{start}({})", start_args.join(", "))); match &check { Some(check) => { inner.push(format!("let c_poll_ = {started}")); inner.push(check.clone()); inner.push(format!("switch c_poll_ {{\n{cases}\n}}")); } None => inner.push(format!("switch {started} {{\n{cases}\n}}")), } let mut body = decls; let mut call_args: Vec = ["f_".to_string(), "w_".to_string()].into_iter().chain(ptrs).collect(); match poll_status { true => { body.push("var c_ps_: Swift.Int32 = 0".to_string()); call_args.push("&c_ps_".to_string()); body.push(format!("let c_poll_ = {}({})", poll.name, call_args.join(", "))); body.push(format!("try Native.status(c_ps_, \"{}\")", poll.name)); body.push(format!("switch c_poll_ {{\n{cases}\n}}")); } false => body.push(format!( "switch {}({}) {{\n{cases}\n}}", poll.name, call_args.join(", ") )), } tail = Some(format!( "return try await Native.run(f_, {}) {{ f_, w_ in\n{}\n}}", free.name, indent(&body.join("\n")) )); } else { tail = None; for (n, ty) in outs.iter().filter(|(n, _)| !written.contains(n)) { inner.push(self.out_decl(n, ty)); } let mut call_args = exprs.clone(); call_args.extend(outs.iter().map(|(n, _)| format!("&c_{n}_"))); call_args.extend(status_arg); let call = reached(format!("{c_name}({})", call_args.join(", "))); match (&err, &ok) { (Some(err), ok) => { let ready = match ok { Type::Unit => "return".to_string(), _ => format!("return {}", self.lift_outs(&function.ok, ok)), }; match &check { Some(check) => { inner.push(format!("let c_ok_ = {call}")); inner.push(check.clone()); inner.push(format!("if c_ok_ {{\n\t{ready}\n}}")); } None => inner.push(format!("if {call} {{\n\t{ready}\n}}")), } let lifted = self.lift(err, "c_err_"); inner.push(format!( "throw {}", thrown_value(thrown.as_ref().expect("an error throws"), &lifted) )); } (None, Type::Unit) => { inner.push(call); inner.extend(check); } // A value C returns beside what Rust wrote back is its return, as with none. (None, ok) if outs.iter().any(|(n, _)| !written.contains(n)) => { inner.push(call); inner.extend(check); inner.push(format!("return {}", self.lift_outs(&function.ok, ok))); } (None, ok) => { inner.push(format!("let c_ret_ = {call}")); inner.extend(check); inner.push(format!("return {}", self.lift(ok, "c_ret_"))); } } } // Wrap the call in each argument's closure, innermost last, each opened with `try` // only where the call throws. A buffer Rust takes opens innermost, so nothing throws // between its take and the call. let wrap = |inner: String, throws: bool| { let mut code = inner; let (takes, rest): (Vec<&Arg>, Vec<&Arg>) = args.iter().partition(|a| a.takes); for arg in takes.into_iter().rev().chain(rest.into_iter().rev()) { if let Some((open, close)) = &arg.open { // An opener may hold several `try`s, as a lent closure's two do. let open = match throws { true => open.clone(), false => open.replace("try ", ""), }; let lines = code.lines().count(); // A closure of one line returns its value; of more, its own `return` does. let body = match lines > 1 || code.starts_with("return ") || code.starts_with("throw ") { true => code.clone(), false => format!("return {code}"), }; code = format!("return {open}\n{}\n{close}", indent(&body)); } } code }; let code = wrap(inner.join("\n"), true); let mut body = prelude; match tail { // An eager call runs Rust, and any callback it makes, before its future exists, // and a callback may cancel the task: so it is made, then `Native.made` checks the // task before its first poll, never started. Some(tail) if function.eager => { match &made { // Made by a call of several lines, which binds `f_` itself unwrapped. Some(made) => { let wrapped = wrap(format!("{made}\nreturn f_"), true); match wrapped.strip_prefix("return ") { Some(wrapped) => body.push(format!("let f_ = {wrapped}")), None => body.push(made.clone()), } } None => { let made = wrap(call.clone(), false); body.push(format!("let f_ = {}", made.strip_prefix("return ").unwrap_or(&made))); } } body.push(tail.replacen("Native.run(", "Native.made(", 1)); } Some(tail) => { let made = wrap(cancelled.expect("a future has its cancel"), status); let made = made.strip_prefix("return ").unwrap_or(&made); body.push(format!( "// A task cancelled already takes nothing, even what is ready.\nif Task.isCancelled {{\n{}\n\tthrow CancellationError()\n}}", indent(made) )); // The call and its first poll in one: the output if ready, else the future. let output = match ok { Type::Unit => "Void".to_string(), _ => self.sw(&ok), }; let tr = match err.is_some() || status { true => "try ", false => "", }; let code = match code.lines().count() > 1 || code.starts_with("return ") { true => code, false => format!("return {code}"), }; body.push("var f_: OpaquePointer? = nil".to_string()); body.push(format!( "if let r_ = {tr}Native.start(({output}).self, {{\n{}\n}}) {{\n\treturn r_\n}}", indent(&code) )); body.push(tail); } None => body.push(code), } let mut text = function.docs.clone(); for k in left { text.push_str(&format!("\n\nWithout `{}`, as Rust's `None`.", unquote(&names[*k]))); } 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 `{}` past the call, calls it from any thread, one call at a time, and releases it once it drops it.", unquote(name) ), false => format!( "\n\nRust calls `{}` only during the call, from any thread.", unquote(name) ), }); if lent.iter().any(|p| matches!(p.base(), Type::Object(_))) { text.push_str(&format!( "\nAn object it lends lives only for that call of `{}`: keep none past it.", unquote(name) )); } } } if function.future { text.push_str("\n\nA cancelled task cancels it in Rust, losing nothing, and throws `CancellationError`."); } let effects = match (function.future, throws) { (true, _) => " async throws", (false, true) => " throws", (false, false) => "", }; let ret = match ok { Type::Unit => String::new(), _ => format!(" -> {}", self.sw(&ok)), }; let is_static = receiver.is_none() && owner.is_some(); let stat = match is_static { true => "static ", false => "", }; let body = body.join("\n"); let var = function.params.is_empty() && !throws; // A field read stays a property though a check of its handle may fail, which throws // from its getter, unless Swift cannot copy its value, whose getter cannot throw. let getter = throws && !function.future && function.err.is_none() && everywhere && !self.unique(&function.ok); let var = match (function.access, receiver) { (Access::Field { set: false, .. }, Some(_)) => { function.params.is_empty() && (!throws || getter) && mutation.is_empty() } (Access::Const, None) => { if var { member = member.trim_matches('`').to_uppercase(); } var } _ => false, }; let labels: Vec = match var { true => Vec::new(), false => (params.iter()) .map(|p| unquote(p.split([' ', ':']).next().expect("a parameter has its label"))) .collect(), }; // A member its type declares already, as a field of its name, takes a trailing `_`. match owner { None => member = self.claim(&member, &labels, format!("fn `{}`", function.path.join("::"))), Some(_) => { while taken.contains(&full(is_static, &member, labels.iter().cloned())) { member = format!("{}_", unquote(&member)); } } } let omitted = left.iter().map(usize::to_string).collect::>().join(","); self.locked.insert( format!("{} / omitted {omitted}", crate::lock::function_key(function)), member.clone(), ); // A future runs on its caller's executor, as Swift 6.2's `nonisolated(nonsending)` // says, so a call ready at its first poll never hops off an actor and back. let isolation = match function.future { true => "nonisolated(nonsending) ", false => "", }; let head = match var { true => format!("public {stat}var {member}{}", ret.replacen(" -> ", ": ", 1)), false => format!( "{isolation}public {stat}{mutation}func {member}({}){effects}{ret}", params.join(", ") ), }; let body = match var && throws { true => format!("get throws {{\n{}\n}}", indent(&body)), false => body, }; let code = format!("{}{head} {{\n{}\n}}\n", docs(text.trim(), ""), indent(&body)); (code, full(is_static, &member, labels)) } /// The declaration of the local the call writes the out value `name` of C type `ty` to. fn out_decl(&self, name: &str, ty: &Ty) -> String { let Ty::Out(inner) = ty else { unreachable!("an out parameter is a pointer") }; format!("var c_{name}_: {} = {}", self.c_sw(inner), self.zero(inner)) } /// The Swift value of a call's outs, which return `ok`, or each element of a tuple. fn lift_outs(&mut self, declared: &Type, ok: &Type) -> String { match declared { Type::Tuple(elements) if elements.len() == 1 => self.lift(ok, "c_out0_"), Type::Tuple(elements) => { let lifted: Vec = (elements.iter().enumerate()) .map(|(n, e)| self.lift(&strip_refs(e), &format!("c_out{n}_"))) .collect(); match self.unique(ok) { true => format!("{}({})", self.sw(ok), lifted.join(", ")), false => format!("({})", lifted.join(", ")), } } _ => self.lift(ok, "c_out_"), } } /// How an error of type `err` is thrown: as itself if an exported type, which then /// conforms to `Swift.Error`, or else in a struct of its own. fn thrown(&mut self, err: &Type) -> Thrown { match err.base() { Type::Record(_) | Type::Enum(_) | Type::Object(_) => { self.conforms.insert(self.sw(err)); if self.sendable(err.base()).is_empty() { self.unsent_errors.insert(self.sw(err)); } Thrown::Itself } _ => { // Named by its key, as its C structs are, so two types never share one. let key = self.abi.key(err); let seen = self.thrown.iter().find(|(_, seen)| self.abi.key(seen) == key); let name = match seen { Some((name, _)) => name.clone(), None => { let name = format!("{}Error", pascal(&key)); let name = self.claim(&name, &[], format!("the error type `{}`", self.sw(err))); self.thrown.insert(name.clone(), err.clone()); name } }; self.locked.insert(crate::lock::error_key(self.abi, err), name.clone()); Thrown::Wrapped(name) } } } } /// How a function throws its error. enum Thrown { Itself, Wrapped(String), } /// The error value thrown for the lifted error `lifted`. fn thrown_value(thrown: &Thrown, lifted: &str) -> String { match thrown { Thrown::Itself => lifted.to_string(), Thrown::Wrapped(name) => format!("{name}(error: {lifted})"), } } /// The most `Option<&T>` parameters of a struct a function takes, each doubling its /// overloads. const MAX_OPTIONAL: usize = 2; /// Each function or method Swift cannot export, and why, which the driver /// refuses before any language is generated: one taking more optional borrowed structs /// than [`MAX_OPTIONAL`], or returning an error that holds one, which `Swift.Error` /// requires be copyable. pub(crate) fn refusals<'a>(abi: &Abi<'a>) -> Vec<(&'a Function, String)> { let structs = structs(abi); let api = abi.api; let methods = (api.records.iter().flat_map(|r| &r.methods)) .chain(api.enums.iter().flat_map(|e| &e.methods)) .chain(api.objects.iter().flat_map(|o| &o.methods)); let mut refusals = Vec::new(); for (kind, function) in (api.functions.iter().map(|f| ("fn", f))).chain(methods.map(|f| ("method", f))) { let what = format!("cannot export {kind} `{}`", function.shown[1..].join("::")); let optional = (function.params.iter()) .filter(|p| lent_option(&structs, &p.ty)) .count(); if optional > MAX_OPTIONAL { refusals.push(( function, format!( "{what}: {optional} optional borrowed objects, past the {MAX_OPTIONAL} Swift takes, which overloads each with and without it since its optional holds an object only by consuming it" ), )); } if function.err.as_ref().is_some_and(|err| unique(&structs, err)) { refusals.push(( function, format!("{what}: error holding an object Swift cannot copy, as `Swift.Error` requires"), )); } } refusals } /// Whether Swift's value of `ty` is noncopyable: it holds one of `structs`. fn unique(structs: &BTreeSet, ty: &Type) -> bool { match ty { Type::Object(i) => structs.contains(i), Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => unique(structs, inner), Type::Tuple(elements) => elements.iter().any(|e| unique(structs, e)), _ => false, } } /// Whether `ty` is an `Option<&T>` of one of `structs`. fn lent_option(structs: &BTreeSet, ty: &Type) -> bool { matches!(ty, Type::Option(inner) if matches!(&**inner, Type::Ref(Mutability::Not, object) if unique(structs, object))) } /// The objects Swift holds as noncopyable structs: each but those `Copy`, and those thrown /// as errors, which `Swift.Error` requires be copyable. fn structs(abi: &Abi<'_>) -> BTreeSet { let api = abi.api; let methods = (api.records.iter().flat_map(|r| &r.methods)) .chain(api.enums.iter().flat_map(|e| &e.methods)) .chain(api.objects.iter().flat_map(|o| &o.methods)); let thrown: BTreeSet = (api.functions.iter().chain(methods)) .filter_map(|f| match f.err.as_ref().map(Type::base) { Some(Type::Object(i)) => Some(*i), _ => None, }) .collect(); (0..api.objects.len()) .filter(|i| !api.objects[*i].copy && !thrown.contains(i)) .collect() } /// `ty` returned: a borrow is returned as a clone, so owned. 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))), Type::List(c, inner) => Type::List(*c, Box::new(strip_refs(inner))), Type::Tuple(elements) => Type::Tuple(elements.iter().map(strip_refs).collect()), ty => ty.clone(), } } /// The Swift type of an integer. fn sw_int(int: Int) -> &'static str { match int { Int::U8 => "Swift.UInt8", Int::U16 => "Swift.UInt16", Int::U32 => "Swift.UInt32", Int::U64 => "Swift.UInt64", Int::Usize => "Swift.UInt", Int::I8 => "Swift.Int8", Int::I16 => "Swift.Int16", Int::I32 => "Swift.Int32", Int::I64 => "Swift.Int64", Int::Isize => "Swift.Int", } } /// The Swift type Swift imports a C integer as: `size_t` is `Int`. fn c_int(int: Int) -> &'static str { match int { Int::Usize => "Swift.Int", int => sw_int(int), } } /// The C integer of the Swift integer `e`. fn lower_int(int: Int, e: &str) -> String { match int { Int::Usize => format!("Swift.Int(bitPattern: {e})"), _ => e.to_string(), } } /// The Swift integer of the C integer `e`. fn lift_int(int: Int, e: &str) -> String { match int { Int::Usize => format!("Swift.UInt(bitPattern: {e})"), _ => e.to_string(), } } /// The Swift 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 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(), } } /// A field's Swift name: `init` would name the initializer. fn field_name(name: &str) -> String { member(name, &["init"]) } /// A member's Swift name: in camel case, quoted if a keyword, or with `_` appended if /// Swift gives every such type 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 member's full Swift name, which two members of a type may share only if one is static /// and the other not: its name, then its argument labels, so a property and a method of no /// arguments are alike. fn full(is_static: bool, name: &str, labels: impl IntoIterator) -> String { let labels: String = labels.into_iter().map(|l| l + ":").collect(); let stat = match is_static { true => "static ", false => "", }; match labels.is_empty() { true => format!("{stat}{}", unquote(name)), false => format!("{stat}{}({labels})", unquote(name)), } } /// A name without the backticks quoting a keyword. fn unquote(name: &str) -> String { name.trim_matches('`').to_string() } /// A name Swift reads as a keyword, in backticks. fn kw(name: &str) -> String { const KEYWORDS: &[&str] = &[ "Any", "Protocol", "Self", "Type", "as", "associatedtype", "await", "break", "case", "catch", "class", "continue", "default", "defer", "deinit", "do", "else", "enum", "extension", "fallthrough", "false", "fileprivate", "for", "func", "guard", "if", "import", "in", "init", "inout", "internal", "is", "let", "nil", "open", "operator", "precedencegroup", "private", "protocol", "public", "repeat", "rethrows", "return", "self", "static", "struct", "subscript", "super", "switch", "throw", "throws", "true", "try", "typealias", "var", "where", "while", ]; match KEYWORDS.contains(&name) { true => format!("`{name}`"), false => name.to_string(), } } /// `swift` with every body another module may inline: each function, initializer, /// subscript, and computed property of a type or the file `@inlinable`, and each other /// declaration they could name `@usableFromInline` unless public, `private` ones made /// internal. So a consumer's call of a wrapper compiles to a direct call of its C function, /// not a call into this module, whose cost would follow where the linker places its code. /// /// It reads the generated file a line at a time, as the generator writes it: one /// declaration a line, each brace that opens a body ending its line. fn inlinable(swift: &str) -> String { /// What a brace opened: a type's members, or code. #[derive(PartialEq)] enum Scope { Members, Protocol, Code, } const ACCESS: &[&str] = &["public ", "private ", "fileprivate "]; const MODIFIERS: &[&str] = &[ "static ", "mutating ", "consuming ", "final ", "nonisolated ", "nonisolated(unsafe) ", "nonisolated(nonsending) ", ]; let mut scopes: Vec = Vec::new(); let mut out = String::with_capacity(swift.len() * 11 / 10); for line in swift.lines() { let code = line.trim_start_matches('\t'); let tabs = &line[..line.len() - code.len()]; let mut opened = Scope::Code; let mut written = None; if !code.starts_with("//") && scopes.iter().all(|s| *s == Scope::Members) { // Attributes on the line, then its access and modifiers, then its keyword. let mut rest = code; let mut attributes = String::new(); while rest.starts_with('@') { let end = rest.find(' ').unwrap_or(rest.len()); attributes.push_str(&rest[..end]); attributes.push(' '); rest = rest[end..].trim_start(); } // Access and modifiers come in either order, as `nonisolated(nonsending) public`, // and keep it, but for a `private` or `fileprivate`, which an inlined body could // not name. let mut public = false; let mut modifiers = String::new(); loop { if let Some(a) = ACCESS.iter().find(|a| rest.starts_with(**a)) { if *a == "public " { public = true; modifiers.push_str(a); } rest = &rest[a.len()..]; } else if let Some(m) = MODIFIERS.iter().find(|m| rest.starts_with(**m)) { modifiers.push_str(m); rest = &rest[m.len()..]; } else { break; } } let keyword = rest.split([' ', '(', '<', '?']).next().unwrap_or(""); // A property is computed when its line opens a body before any `=`. let computed = match (rest.find('{'), rest.find('=')) { (Some(brace), Some(assign)) => brace < assign, (brace, _) => brace.is_some(), }; let attribute = match keyword { "func" | "init" | "subscript" => Some("@inlinable "), "var" | "let" if computed => Some("@inlinable "), "var" | "let" | "struct" | "class" | "enum" | "typealias" if !public => Some("@usableFromInline "), _ => None, }; opened = match keyword { "struct" | "class" | "enum" | "extension" => Scope::Members, "protocol" => Scope::Protocol, _ => Scope::Code, }; // A declaration the generator marks itself keeps its mark. let marked = attributes.contains("@inlinable") || attributes.contains("@usableFromInline"); if let Some(attribute) = attribute.filter(|_| !marked) { written = Some(format!("{tabs}{attributes}{attribute}{modifiers}{rest}")); } } let opens = line.matches('{').count(); let closes = line.matches('}').count(); if !code.starts_with("//") { match opens.cmp(&closes) { std::cmp::Ordering::Greater => { scopes.push(opened); scopes.extend((1..opens - closes).map(|_| Scope::Code)); } std::cmp::Ordering::Less => { for _ in 0..closes - opens { scopes.pop().expect("the generated Swift's braces balance"); } } std::cmp::Ordering::Equal => {} } } out.push_str(written.as_deref().unwrap_or(line)); out.push('\n'); } assert!(scopes.is_empty(), "the generated Swift's braces balance"); out } /// Swift doc comments holding `docs`, each line indented by `indent`, or nothing for none. fn docs(docs: &str, indent: &str) -> String { docs.lines() .map(|line| match line.is_empty() { true => format!("{indent}///\n"), false => format!("{indent}/// {line}\n"), }) .collect() } /// Code indented by one tab more, but for blank lines. fn indent(code: &str) -> String { let mut out: String = code .lines() .map(|l| match l.is_empty() { true => "\n".to_string(), false => format!("\t{l}\n"), }) .collect(); if !code.ends_with('\n') { out.pop(); } out } /// The conformances a type declares, as `: A, B`, or nothing for none. fn conform(protocols: &[&str]) -> String { match protocols.is_empty() { true => String::new(), false => format!(": {}", protocols.join(", ")), } } #[cfg(test)] mod tests { use super::{RUNTIME, TAKEN, inlinable}; /// Each member a body may name crosses: functions and computed properties inline, /// internal storage and types are usable from them, and code, protocols, public /// storage, and what the generator marks itself stay as written. #[test] fn inlinable_marks_members() { let swift = "\ public struct A: ~Copyable { let handle: OpaquePointer? public let name: Swift.String private var count = 0 var size: Swift.Int { 1 } public var bytes: Swift.Int { let n = size return n } init(raw: OpaquePointer?) { handle = raw } deinit { free(handle) } @usableFromInline consuming func _end() { discard self } /// A call {in braces. nonisolated(nonsending) public func get() async throws -> Swift.Int { let x = { () -> Int in 1 }() return x } } public protocol P: Sendable { func call() -> Swift.Int } enum Native { struct Handle { static let slots: UnsafeMutablePointer = { let count = 1 return .allocate(capacity: count) }() } } public func top() {} "; let want = "\ public struct A: ~Copyable { @usableFromInline let handle: OpaquePointer? public let name: Swift.String @usableFromInline var count = 0 @inlinable var size: Swift.Int { 1 } @inlinable public var bytes: Swift.Int { let n = size return n } @inlinable init(raw: OpaquePointer?) { handle = raw } deinit { free(handle) } @usableFromInline consuming func _end() { discard self } /// A call {in braces. @inlinable nonisolated(nonsending) public func get() async throws -> Swift.Int { let x = { () -> Int in 1 }() return x } } public protocol P: Sendable { func call() -> Swift.Int } @usableFromInline enum Native { @usableFromInline struct Handle { @usableFromInline static let slots: UnsafeMutablePointer = { let count = 1 return .allocate(capacity: count) }() } } @inlinable public func top() {} "; assert_eq!(inlinable(swift), want); } /// Each type the runtime declares at its top level, and each protocol one conforms to, /// is a name no export may take, as either would clash with or shadow it. #[test] fn runtime_names_taken() { for line in RUNTIME.lines() { let Some(decl) = [ "public struct ", "public final class ", "public enum ", "public protocol ", ] .iter() .find_map(|kind| line.strip_prefix(kind)) else { continue; }; let decl = decl.trim_end_matches('{').trim(); // A generic's parameters, such as `NonZero`, name it // no further; the type is its name before them. let decl = match decl.split_once('<') { Some((name, rest)) => name.to_string() + rest.split_once('>').expect("a generic closes").1, None => decl.to_string(), }; let (name, conforms) = decl.split_once(':').unwrap_or((&decl, "")); let names = std::iter::once(name).chain(conforms.split(',')); // A qualified name, such as `Swift.Error`, cannot clash. for name in (names.map(str::trim)).filter(|n| !n.is_empty() && !n.starts_with('@') && !n.contains('.')) { assert!(TAKEN.contains(&name), "the runtime's `{name}` is not in TAKEN"); } } } }