Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! The Swift side of a Swift unit: a wrapper that redeclares each bridged function with its
//! original labels, defaults and `throws`, calling the Rust library's JSON dispatcher through a C
//! module map; and the driver `record` and `diff` compile with the originals or with the wrapper.
//!
//! Values cross as JSON written and read by a small codec in each file (`fileprivate`, so a
//! wrapper and a driver, or two wrappers, can be compiled into one module).
use std::fmt::Write as _;
use crate::bridge::Manifest;
use crate::lang::swift::{SwiftSig, signature};
/// The module name the driver is compiled under, removed from recorded error type names.
pub const DRIVER_MODULE: &str = "RustAnythingDriver";
/// The port type of a Swift `UInt` or `UInt64`: the dialect calls every Swift integer `int`, which is
/// `i64` in the port and cannot hold the upper half of their range (issue #1045).
pub fn unsigned_port_type(swift_type: &str) -> Option<String> {
// `Swift.UInt64` is spelled with its module, as `swift_to_ts` already strips it.
let name = swift_type.trim();
let name = name.strip_prefix("Swift.").unwrap_or(name).trim();
if matches!(name, "UInt" | "UInt64") {
return Some("u64".to_string());
}
// `UInt64?` crosses as an optional, whose port type is `Option<i64>` unless this says otherwise.
if let Some(inner) = name.strip_suffix('?') {
return unsigned_port_type(inner).map(|t| format!("Option<{t}>"));
}
// `[UInt64]` loses the upper half of the range as `Vec<i64>` too, and so does `[[UInt64]]`.
let inner = name.strip_prefix('[')?.strip_suffix(']')?;
unsigned_port_type(inner).map(|t| format!("Vec<{t}>"))
}
pub fn camel(m: &Manifest) -> String {
crate::codegen_ruby::camel(&m.lib_name())
}
pub fn wrapper_path(m: &Manifest) -> String {
format!("swift/{}.swift", camel(m))
}
/// The Clang module the wrapper imports: the C declarations of the dispatcher, and the library
/// to link.
pub fn native_module(m: &Manifest) -> String {
format!("{}Native", camel(m))
}
/// The error type the wrapper throws for a port's `Err("Type: message")`.
pub fn error_type(m: &Manifest) -> String {
format!("{}Error", camel(m))
}
const HEADER: &str = "// The C entry points of a rust-anything crate, generated by rust-anything.\n\
#ifndef RUST_ANYTHING_H\n#define RUST_ANYTHING_H\n\n\
char *rust_anything_call(const char *name, const char *args);\n\
void rust_anything_free(char *ptr);\n\n#endif\n";
/// `swift/<Native>/module.modulemap` and its header.
pub fn module_files(m: &Manifest) -> Vec<(String, String)> {
let native = native_module(m);
vec![
(
format!("swift/{native}/module.modulemap"),
format!(
"module {native} {{\n header \"rust_anything.h\"\n link \"{}\"\n export *\n}}\n",
m.lib_name()
),
),
(format!("swift/{native}/rust_anything.h"), HEADER.into()),
]
}
const INTS: &[&str] = &[
"Int64", "Int32", "Int16", "Int8", "UInt32", "UInt16", "UInt8",
];
/// The unsigned types whose range does not fit `Int`: their conformance reads `.uint` and, because a small
/// value arrives as `.int`, any non-negative `Int` too (issue #1045).
const WIDE_UNSIGNED: &[&str] = &["UInt64", "UInt"];
/// JSON values, a parser and a writer, and the conversions of the types the bridge carries.
fn codec() -> String {
let mut ints = String::new();
for t in INTS {
let _ = writeln!(
ints,
"extension {t}: RACodable {{\n \
fileprivate init(raJSON v: RAJSON) throws {{\n \
guard case .int(let n) = v, let x = {t}(exactly: n) else {{ throw RAJSONError(\"expected {t}\") }}\n \
self = x\n }}\n \
fileprivate var raJSON: RAJSON {{ .int(Int(self)) }}\n}}"
);
}
let mut wide = String::new();
for t in WIDE_UNSIGNED {
let _ = writeln!(
wide,
"extension {t}: RACodable {{\n \
fileprivate init(raJSON v: RAJSON) throws {{\n \
switch v {{\n \
case .uint(let u): self = {t}(u)\n \
case .int(let n) where n >= 0: self = {t}(n)\n \
default: throw RAJSONError(\"expected {t}\")\n \
}}\n }}\n \
fileprivate var raJSON: RAJSON {{ .uint(UInt64(self)) }}\n}}"
);
}
CODEC.replace("__INTS__\n", &format!("{ints}{wide}"))
}
const CODEC: &str = r#"// `String.range(of:)` for error messages is Foundation's, so the file imports it rather than
// leaving the caller to.
import Foundation
fileprivate indirect enum RAJSON {
case null
case bool(Bool)
case int(Int)
case uint(UInt64)
case double(Double)
case string(String)
case array([RAJSON])
case object([(String, RAJSON)])
}
fileprivate struct RAJSONError: Error, CustomStringConvertible {
let description: String
init(_ description: String) { self.description = description }
}
fileprivate struct RAParser {
let bytes: [UInt8]
var i = 0
init(_ text: String) { bytes = Array(text.utf8) }
mutating func parse() throws -> RAJSON {
skip()
let v = try value()
skip()
guard i == bytes.count else { throw RAJSONError("trailing text in JSON") }
return v
}
mutating func skip() {
while i < bytes.count, bytes[i] == 0x20 || bytes[i] == 0x0a || bytes[i] == 0x0d || bytes[i] == 0x09 {
i += 1
}
}
mutating func word(_ w: String, _ v: RAJSON) throws -> RAJSON {
let w = Array(w.utf8)
guard i + w.count <= bytes.count, Array(bytes[i..<i + w.count]) == w else {
throw RAJSONError("bad JSON literal")
}
i += w.count
return v
}
mutating func value() throws -> RAJSON {
guard i < bytes.count else { throw RAJSONError("unexpected end of JSON") }
switch bytes[i] {
case UInt8(ascii: "n"): return try word("null", .null)
case UInt8(ascii: "t"): return try word("true", .bool(true))
case UInt8(ascii: "f"): return try word("false", .bool(false))
case UInt8(ascii: "\""): return .string(try string())
case UInt8(ascii: "["):
i += 1
var items: [RAJSON] = []
skip()
if i < bytes.count, bytes[i] == UInt8(ascii: "]") { i += 1; return .array(items) }
while true {
skip()
items.append(try value())
skip()
guard i < bytes.count else { throw RAJSONError("unexpected end of JSON") }
i += 1
if bytes[i - 1] == UInt8(ascii: "]") { return .array(items) }
guard bytes[i - 1] == UInt8(ascii: ",") else { throw RAJSONError("expected , or ]") }
}
case UInt8(ascii: "{"):
i += 1
var pairs: [(String, RAJSON)] = []
skip()
if i < bytes.count, bytes[i] == UInt8(ascii: "}") { i += 1; return .object(pairs) }
while true {
skip()
let key = try string()
skip()
guard i < bytes.count, bytes[i] == UInt8(ascii: ":") else { throw RAJSONError("expected :") }
i += 1
skip()
pairs.append((key, try value()))
skip()
guard i < bytes.count else { throw RAJSONError("unexpected end of JSON") }
i += 1
if bytes[i - 1] == UInt8(ascii: "}") { return .object(pairs) }
guard bytes[i - 1] == UInt8(ascii: ",") else { throw RAJSONError("expected , or }") }
}
default:
return try number()
}
}
mutating func hex4() throws -> UInt32 {
guard i + 4 <= bytes.count, let n = UInt32(String(decoding: bytes[i..<i + 4], as: UTF8.self), radix: 16) else {
throw RAJSONError("bad \\u escape")
}
i += 4
return n
}
mutating func string() throws -> String {
guard i < bytes.count, bytes[i] == UInt8(ascii: "\"") else { throw RAJSONError("expected a string") }
i += 1
var out: [UInt8] = []
while i < bytes.count {
let c = bytes[i]
i += 1
if c == UInt8(ascii: "\"") { return String(decoding: out, as: UTF8.self) }
guard c == UInt8(ascii: "\\") else { out.append(c); continue }
guard i < bytes.count else { break }
let e = bytes[i]
i += 1
switch e {
case UInt8(ascii: "n"): out.append(0x0a)
case UInt8(ascii: "t"): out.append(0x09)
case UInt8(ascii: "r"): out.append(0x0d)
case UInt8(ascii: "b"): out.append(0x08)
case UInt8(ascii: "f"): out.append(0x0c)
case UInt8(ascii: "u"):
var code = try hex4()
if (0xD800...0xDBFF).contains(code), i + 1 < bytes.count,
bytes[i] == UInt8(ascii: "\\"), bytes[i + 1] == UInt8(ascii: "u") {
let save = i
i += 2
let low = try hex4()
if (0xDC00...0xDFFF).contains(low) {
code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)
} else {
i = save
}
}
let scalar = Unicode.Scalar(code) ?? "\u{FFFD}"
out.append(contentsOf: Array(String(Character(scalar)).utf8))
default: out.append(e)
}
}
throw RAJSONError("unterminated string")
}
mutating func number() throws -> RAJSON {
let start = i
while i < bytes.count, "+-0123456789.eE".utf8.contains(bytes[i]) { i += 1 }
let text = String(decoding: bytes[start..<i], as: UTF8.self)
if !text.utf8.contains(where: { $0 == UInt8(ascii: ".") || $0 == UInt8(ascii: "e") || $0 == UInt8(ascii: "E") }) {
if let n = Int(text) { return .int(n) }
// Above `Int.max`: Swift `UInt64` and `UInt` cross as JSON numbers like every other integer.
if let u = UInt64(text) { return .uint(u) }
}
guard let d = Double(text) else { throw RAJSONError("bad JSON number `\(text)`") }
return .double(d)
}
}
fileprivate func raQuote(_ s: String) -> String {
var out = ""
raQuote(s, &out)
return out
}
fileprivate func raQuote(_ s: String, _ out: inout String) {
out += "\""
for u in s.unicodeScalars {
switch u {
case "\"": out += "\\\""
case "\\": out += "\\\\"
case "\n": out += "\\n"
case "\r": out += "\\r"
case "\t": out += "\\t"
default:
if u.value < 0x20 {
let hex = String(u.value, radix: 16)
out += "\\u" + String(repeating: "0", count: 4 - hex.count) + hex
} else {
out.unicodeScalars.append(u)
}
}
}
out += "\""
}
fileprivate func raWrite(_ v: RAJSON, _ out: inout String) {
switch v {
case .null: out += "null"
case .bool(let b): out += b ? "true" : "false"
case .int(let n): out += String(n)
case .uint(let u): out += String(u)
case .double(let d):
if d.isNaN {
out += "{\"$num\":\"NaN\"}"
} else if d.isInfinite {
out += d > 0 ? "{\"$num\":\"Infinity\"}" : "{\"$num\":\"-Infinity\"}"
} else if d == 0 && d.sign == .minus {
out += "{\"$num\":\"-0\"}"
} else {
out += "\(d)"
}
case .string(let s): raQuote(s, &out)
case .array(let items):
out += "["
for (k, item) in items.enumerated() {
if k > 0 { out += "," }
raWrite(item, &out)
}
out += "]"
case .object(let pairs):
out += "{"
for (k, (key, item)) in pairs.enumerated() {
if k > 0 { out += "," }
raQuote(key, &out)
out += ":"
raWrite(item, &out)
}
out += "}"
}
}
fileprivate func raText(_ v: RAJSON) -> String {
var out = ""
raWrite(v, &out)
return out
}
fileprivate protocol RACodable {
init(raJSON: RAJSON) throws
var raJSON: RAJSON { get }
}
extension Int: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
guard case .int(let n) = v else { throw RAJSONError("expected an integer") }
self = n
}
fileprivate var raJSON: RAJSON { .int(self) }
}
__INTS__
extension Double: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
switch v {
case .double(let d): self = d
case .int(let n): self = Double(n)
case .uint(let u): self = Double(u)
case .object(let pairs) where pairs.count == 1 && pairs[0].0 == "$num":
switch pairs[0].1 {
case .string("NaN"): self = .nan
case .string("Infinity"): self = .infinity
case .string("-Infinity"): self = -.infinity
case .string("-0"): self = -0.0
default: throw RAJSONError("expected a number")
}
default: throw RAJSONError("expected a number")
}
}
fileprivate var raJSON: RAJSON { .double(self) }
}
extension Float: RACodable {
fileprivate init(raJSON v: RAJSON) throws { self = Float(try Double(raJSON: v)) }
fileprivate var raJSON: RAJSON { .double(Double(self)) }
}
extension Bool: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
guard case .bool(let b) = v else { throw RAJSONError("expected a boolean") }
self = b
}
fileprivate var raJSON: RAJSON { .bool(self) }
}
extension String: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
guard case .string(let s) = v else { throw RAJSONError("expected a string") }
self = s
}
fileprivate var raJSON: RAJSON { .string(self) }
}
extension Optional: RACodable where Wrapped: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
if case .null = v { self = nil } else { self = try Wrapped(raJSON: v) }
}
fileprivate var raJSON: RAJSON { map { $0.raJSON } ?? .null }
}
extension Array: RACodable where Element: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
guard case .array(let items) = v else { throw RAJSONError("expected an array") }
self = try items.map { try Element(raJSON: $0) }
}
fileprivate var raJSON: RAJSON { .array(map { $0.raJSON }) }
}
extension Dictionary: RACodable where Key == String, Value: RACodable {
fileprivate init(raJSON v: RAJSON) throws {
guard case .object(let pairs) = v else { throw RAJSONError("expected an object") }
var out: [String: Value] = [:]
for (k, x) in pairs { out[k] = try Value(raJSON: x) }
self = out
}
fileprivate var raJSON: RAJSON {
.object(keys.sorted().map { ($0, self[$0]!.raJSON) })
}
}
fileprivate func raDecode<T: RACodable>(_ v: RAJSON) throws -> T { try T(raJSON: v) }
"#;
fn is_void(ret: &str) -> bool {
matches!(ret.trim(), "Void" | "()" | "Swift.Void")
}
/// `name(a0, to: a1)`: the call with the original argument labels.
fn call(sig: &SwiftSig, args: &[String]) -> String {
let parts: Vec<String> = sig
.params
.iter()
.zip(args)
.map(|(p, a)| match &p.label {
Some(l) => format!("{l}: {a}"),
None => a.clone(),
})
.collect();
format!("{}({})", sig.name, parts.join(", "))
}
fn signatures(m: &Manifest) -> Vec<(&crate::ts::exports::ExportedFn, SwiftSig)> {
m.exports
.iter()
.filter_map(|f| {
let proto = f.prototype.as_deref()?;
Some((f, signature(proto)?))
})
.collect()
}
pub fn wrapper(m: &Manifest) -> String {
let native = native_module(m);
let error = error_type(m);
// Issue #1198: what stays in Swift is not in this file, which replaces the original.
let kept = crate::bridge::kept_header(&m.js_only, "Swift");
let mut out = format!(
"// The Rust port of `{unit}`, generated by rust-anything: the same functions, with the same\n\
// labels, defaults and `throws`, each calling the Rust library through the C module\n\
// `{native}` (in `swift/{native}/`). Compile it into the target in place of the original\n\
// file. Regenerate with `rust-anything refresh`.\n\
{kept}\n\
import {native}\n\n\
/// An error a Rust port returned: `Err(\"Type: message\")` arrives as `typeName` and\n\
/// `message`.\n\
public struct {error}: Error, CustomStringConvertible {{\n \
public let typeName: String\n \
public let message: String\n \
public var description: String {{ message }}\n}}\n\n\
{codec}\n\
fileprivate func raCall(_ name: String, _ args: [RAJSON]) -> Result<RAJSON, {error}> {{\n \
guard let ptr = rust_anything_call(name, raText(.array(args))) else {{\n \
fatalError(\"rust-anything: no answer from `\\(name)`\")\n }}\n \
let text = String(cString: ptr)\n \
rust_anything_free(ptr)\n \
var parser = RAParser(text)\n \
guard let answer = try? parser.parse(), case .object(let pairs) = answer, let first = pairs.first else {{\n \
fatalError(\"rust-anything: unreadable answer from `\\(name)`: \\(text)\")\n }}\n \
switch (first.0, first.1) {{\n \
case (\"ok\", let value):\n return .success(value)\n \
case (\"error\", .string(let message)):\n \
if let colon = message.range(of: \": \") {{\n \
return .failure({error}(typeName: String(message[..<colon.lowerBound]), message: String(message[colon.upperBound...])))\n }}\n \
return .failure({error}(typeName: \"\", message: message))\n \
case (\"panic\", .string(let message)):\n \
fatalError(\"Rust panic: \\(message)\")\n \
default:\n \
fatalError(\"rust-anything: unreadable answer from `\\(name)`: \\(text)\")\n }}\n}}\n\n\
fileprivate func raTrap<T>(_ body: () throws -> T) -> T {{\n \
do {{ return try body() }} catch {{ fatalError(\"rust-anything: \\(error)\") }}\n}}\n",
unit = m.unit,
codec = codec(),
);
for (f, sig) in signatures(m) {
let args: Vec<String> = sig
.params
.iter()
.map(|p| format!("{}.raJSON", p.name))
.collect();
let invoke = format!("raCall(\"{}\", [{}])", f.name, args.join(", "));
let void = is_void(&sig.ret);
let body = match (sig.throws, void) {
(true, true) => format!(" _ = try {invoke}.get()"),
(true, false) => format!(
" let answer = try {invoke}.get()\n return raTrap {{ try raDecode(answer) }}"
),
(false, true) => format!(" _ = raTrap {{ try {invoke}.get() }}"),
(false, false) => format!(" return raTrap {{ try raDecode({invoke}.get()) }}"),
};
let proto = f.prototype.as_deref().unwrap_or_default();
let _ = write!(out, "\n{proto} {{\n{body}\n}}\n");
}
out
}
/// The bench half of the generated driver: called when a third argument names a minimum time. It repeats
/// the recorded calls until that much time has passed and writes the mean nanoseconds per call, one entry
/// per function, in the shape `harness::bench_rows` reads.
const DRIVER_BENCH: &str = r#"
let minMs = Double(argv[3]) ?? 100
// One timing per function: the same function's recorded calls are repeated until it has had
// `minMs` of them, so a slow case cannot starve a fast one (review of #1052).
var byName: [String: [[RAJSON]]] = [:]
for c in cases {
guard case .object(let fields) = c else { continue }
var name = ""
var args: [RAJSON] = []
for (k, v) in fields {
if k == "fn", case .string(let s) = v { name = s }
if k == "args", case .array(let xs) = v { args = xs }
}
byName[name, default: []].append(args)
}
var entries: [String] = []
for (name, argLists) in byName.sorted(by: { $0.key < $1.key }) {
let deadline = Date().addingTimeInterval(minMs / 1000.0)
var total = 0.0
var count = 0
repeat {
for args in argLists {
let t0 = Date().timeIntervalSince1970
_ = raCase(name, args)
total += (Date().timeIntervalSince1970 - t0) * 1_000_000_000
count += 1
}
} while Date() < deadline
let mean = total / Double(max(count, 1))
entries.append(raQuote(name) + ":{\"ns\":" + String(mean) + ",\"cases\":" + String(argLists.count) + "}")
}
let text = "{" + entries.joined(separator: ",") + "}"
// `createFile` refuses a path that already exists (main created the output above), so the
// timings are written over it.
try? Data(text.utf8).write(to: URL(fileURLWithPath: argv[2]))
return
"#;
/// `main.swift` of the driver: reads a JSON array of cases, runs each, and writes one JSON line
/// per case (`{"i": n, "ok": v}`, `{"i": n, "error": ..., "error_type": ...}`, or
/// `{"i": n, "skip": true}` for arguments that do not convert). `rust` is the build with the
/// wrapper, whose errors carry the port's type name.
pub fn driver(m: &Manifest, rust: bool) -> String {
let bench = DRIVER_BENCH.trim_matches('\n');
let mut arms = String::new();
for (f, sig) in signatures(m) {
let names: Vec<String> = (0..sig.params.len()).map(|i| format!("p{i}")).collect();
let _ = writeln!(
arms,
" case {}:",
serde_json::Value::from(f.name.clone())
);
if !names.is_empty() {
let decls: Vec<String> = sig
.params
.iter()
.zip(&names)
.map(|(p, n)| format!("{n}: {}", p.ty))
.collect();
let _ = writeln!(arms, " let {}", decls.join(", "));
let assigns: Vec<String> = names
.iter()
.enumerate()
.map(|(i, n)| format!("{n} = try raDecode(raArg(a, {i}))"))
.collect();
let _ = writeln!(
arms,
" do {{ {} }} catch {{ return .badInput }}",
assigns.join("; ")
);
}
let invoke = call(&sig, &names);
let line = match (sig.throws, is_void(&sig.ret)) {
(true, true) => {
format!(
"do {{ try {invoke}; return .ok(.null) }} catch {{ return .thrown(error) }}"
)
}
(true, false) => {
format!(
"do {{ return .ok(try {invoke}.raJSON) }} catch {{ return .thrown(error) }}"
)
}
(false, true) => format!("{invoke}; return .ok(.null)"),
(false, false) => format!("return .ok({invoke}.raJSON)"),
};
let _ = writeln!(arms, " {line}");
}
let rust_error = if rust {
format!(
" if let e = e as? {} {{ return (e.message, e.typeName) }}\n",
error_type(m)
)
} else {
String::new()
};
format!(
"// The rust-anything driver for `{unit}`, generated: runs recorded cases.\n\n\
import Foundation\n\n\
{codec}\n\
fileprivate enum RAOutcome {{\n case ok(RAJSON)\n case thrown(Error)\n case badInput\n}}\n\n\
fileprivate func raArg(_ a: [RAJSON], _ i: Int) -> RAJSON {{\n \
guard i < a.count else {{ return .null }}\n \
if case .object(let pairs) = a[i], pairs.count == 1, pairs[0].0 == \"$undefined\" {{ return .null }}\n \
return a[i]\n}}\n\n\
fileprivate func raErrorFields(_ e: Error) -> (String, String) {{\n\
{rust_error} \
var type = String(reflecting: Swift.type(of: e))\n \
if type.hasPrefix(\"{DRIVER_MODULE}.\") {{ type.removeFirst(\"{DRIVER_MODULE}.\".count) }}\n \
return (String(describing: e), type)\n}}\n\n\
fileprivate func raCase(_ name: String, _ a: [RAJSON]) -> RAOutcome {{\n \
switch name {{\n{arms} default:\n return .badInput\n }}\n}}\n\n\
fileprivate func raAppend(_ path: String, _ text: String) {{\n \
guard let handle = FileHandle(forWritingAtPath: path) else {{ return }}\n \
handle.seekToEndOfFile()\n \
handle.write(text.data(using: .utf8)!)\n \
handle.closeFile()\n}}\n\n\
fileprivate func raMain() throws {{\n \
let argv = CommandLine.arguments\n \
let input = String(decoding: FileManager.default.contents(atPath: argv[1]) ?? Data(), as: UTF8.self)\n \
var parser = RAParser(input)\n \
guard case .array(let cases) = try parser.parse() else {{ throw RAJSONError(\"the cases are not a JSON array\") }}\n \
FileManager.default.createFile(atPath: argv[2], contents: nil)\n \
if argv.count > 3 {{\n{bench}\n }}\n \
let progress = ProcessInfo.processInfo.environment[\"RUST_ANYTHING_PROGRESS\"]\n \
for (index, c) in cases.enumerated() {{\n \
if let p = progress {{ raAppend(p, \"\\(index)\\n\") }}\n \
guard case .object(let fields) = c else {{ continue }}\n \
var name = \"\"\n \
var args: [RAJSON] = []\n \
for (k, v) in fields {{\n \
if k == \"fn\", case .string(let s) = v {{ name = s }}\n \
if k == \"args\", case .array(let xs) = v {{ args = xs }}\n }}\n \
var line: [(String, RAJSON)] = [(\"i\", .int(index))]\n \
switch raCase(name, args) {{\n \
case .ok(let v): line.append((\"ok\", v))\n \
case .thrown(let e):\n \
let (message, type) = raErrorFields(e)\n \
line.append((\"error\", .string(message)))\n \
line.append((\"error_type\", .string(type)))\n \
case .badInput: line.append((\"skip\", .bool(true)))\n }}\n \
raAppend(argv[2], raText(.object(line)) + \"\\n\")\n }}\n}}\n\n\
try raMain()\n",
unit = m.unit,
codec = codec(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lang::Lang;
use crate::ts::exports::ExportedFn;
fn manifest(protos: &[(&str, &str)]) -> Manifest {
Manifest {
schema: String::new(),
root: std::path::PathBuf::new(),
root_written: None,
unit: "Sources/Geo/Geo.swift".into(),
language: Lang::Swift,
kind: crate::bridge::Kind::Ffi,
crate_name: "geo-rs".into(),
exports: protos
.iter()
.map(|(name, proto)| ExportedFn {
name: (*name).into(),
prototype: Some((*proto).into()),
..Default::default()
})
.collect(),
classes: Vec::new(),
js_only: Vec::new(),
batches: Vec::new(),
allocator: Default::default(),
float_tolerance: None,
ignore_key_order: false,
messages: false,
end_state: None,
}
}
#[test]
fn the_header_names_what_stays_in_swift() {
// Issue #1198: the wrapper is compiled in place of the original, which also holds these.
let mut m = manifest(&[("add", "add(_ a: Int, _ b: Int) -> Int")]);
let header = |m: &Manifest| -> String {
let w = wrapper(m);
w.split("import ").next().unwrap_or_default().to_string()
};
assert!(!header(&m).contains("Kept in Swift"), "{}", header(&m));
m.js_only = vec![crate::bridge::JsOnly {
name: "total".into(),
file: "Sources/Geo/Geo.swift".into(),
line: 3,
reason: "takes a variadic parameter `xs`".into(),
}];
assert!(
header(&m).contains(
"// Kept in Swift and not defined here: `total`. Move what is kept out of the original \
before this file replaces it.\n"
),
"{}",
header(&m)
);
}
#[test]
fn an_array_of_unsigned_integers_keeps_its_range_too() {
// Review of #1085: `[UInt64]` matched nothing, so the port took `Vec<i64>`.
assert_eq!(unsigned_port_type("[UInt64]").as_deref(), Some("Vec<u64>"));
assert_eq!(
unsigned_port_type("[[UInt]]").as_deref(),
Some("Vec<Vec<u64>>")
);
assert_eq!(unsigned_port_type(" Swift.UInt64 ").as_deref(), Some("u64"));
assert_eq!(
unsigned_port_type("UInt64?").as_deref(),
Some("Option<u64>")
);
assert_eq!(
unsigned_port_type("[UInt64]?").as_deref(),
Some("Option<Vec<u64>>")
);
assert_eq!(unsigned_port_type("[Int64]"), None);
assert_eq!(unsigned_port_type("[String]"), None);
}
#[test]
fn the_generated_file_imports_what_its_error_messages_need() {
// `String.range(of:)` is Foundation's: without the import, the caller's file had to add it.
let codec = codec();
assert!(
codec.lines().any(|l| l.trim() == "import Foundation"),
"the codec imports Foundation: {codec}"
);
// Before the first declaration, so it reads as a file header.
let import = codec.find("import Foundation").unwrap();
let first_item = codec.find("fileprivate indirect enum RAJSON").unwrap();
assert!(import < first_item, "{codec}");
}
#[test]
fn the_codec_carries_an_unsigned_case_and_its_conformances() {
// Issue #1045: without these, a unit taking `UInt64` would get a wrapper that does not compile.
let codec = codec();
for want in [
"case uint(UInt64)",
"if let u = UInt64(text) { return .uint(u) }",
"case .uint(let u): out += String(u)",
"extension UInt64: RACodable",
"extension UInt: RACodable",
"case .uint(let u): self = Double(u)",
] {
assert!(codec.contains(want), "{want} missing");
}
// Exactly one declaration: Swift rejects a duplicate enum case, and the template once had two.
assert_eq!(codec.matches("case uint(UInt64)").count(), 1, "{codec}");
// `.int` stays the first choice: a value that fits `Int` is written as one.
assert!(
codec.contains("if let n = Int(text) { return .int(n) }"),
"{codec}"
);
}
#[test]
fn the_wrapper_keeps_labels_defaults_and_throws() {
let m = manifest(&[
(
"add",
"public func add(_ a: Int, to b: Int = 2) throws -> Int",
),
("log", "func log(_ s: String)"),
]);
assert_eq!(wrapper_path(&m), "swift/GeoRs.swift");
let w = wrapper(&m);
assert!(w.contains("import GeoRsNative\n"), "{w}");
assert!(
w.contains(
"public func add(_ a: Int, to b: Int = 2) throws -> Int {\n \
let answer = try raCall(\"add\", [a.raJSON, b.raJSON]).get()\n \
return raTrap { try raDecode(answer) }\n}"
),
"{w}"
);
assert!(
w.contains("func log(_ s: String) {\n _ = raTrap { try raCall(\"log\", [s.raJSON]).get() }\n}"),
"{w}"
);
let d = driver(&m, true);
assert!(d.contains("let p0: Int, p1: Int"), "{d}");
assert!(d.contains("return .ok(try add(p0, to: p1).raJSON)"), "{d}");
assert!(d.contains("log(p0); return .ok(.null)"), "{d}");
assert!(d.contains("as? GeoRsError"), "{d}");
assert!(!driver(&m, false).contains("GeoRsError"));
let map = &module_files(&m)[0];
assert_eq!(map.0, "swift/GeoRsNative/module.modulemap");
assert!(map.1.contains("link \"geo_rs\""), "{}", map.1);
}
}