MEP 49. Mochi-to-Swift transpiler: Apple platforms via SwiftPM, actor + AsyncStream agents, static Linux/Windows binaries
| Field | Value |
|---|---|
| MEP | 49 |
| Title | Mochi-to-Swift transpiler |
| Author | Mochi core |
| Status | Draft |
| Type | Standards Track |
| Created | 2026-05-23 10:30 (GMT+7) |
| Depends | MEP-4 (Type System), MEP-5 (Type Inference), MEP-13 (ADTs and Match), MEP-45 (C transpiler, IR reuse), MEP-46 (BEAM transpiler, IR reuse), MEP-47 (JVM transpiler, IR reuse), MEP-48 (.NET transpiler, IR reuse) |
| Research | ~/notes/Spec/0049/01..12 |
| Tracking | /docs/implementation/0049/ |
Abstract
Mochi today ships vm3 (mochi run), an ahead-of-time C transpiler producing native single-file binaries (MEP-45), an Erlang/BEAM transpiler producing supervised concurrent runtimes (MEP-46), a JVM transpiler reaching Maven Central and Loom (MEP-47), and a .NET transpiler reaching NuGet and NativeAOT (MEP-48). None of these paths produces a first-class iOS, macOS, watchOS, tvOS, or visionOS application. The Apple ecosystem requires Swift, compiled by Apple's toolchain, distributed through App Store Connect or signed Developer ID channels. MEP-49 specifies a fifth transpiler pipeline that targets Apple's Swift 6.0 language, packages output through SwiftPM and xcodebuild, and reaches the same 1.4B-device Apple platform footprint that no other Mochi backend can address.
The pipeline reuses MEP-45's typed-AST and aotir IR, plus the monomorphisation, match-to-decision-tree, and closure-conversion passes shared with MEP-46, MEP-47, and MEP-48. It forks at the emit stage: instead of emitting ISO C23 (MEP-45), Core Erlang via cerl (MEP-46), Java source via JavaPoet (MEP-47), or C# source via Roslyn SyntaxFactory (MEP-48), it emits Swift 6.0 source text via a Mochi-side syntax-tree model, optionally piped through swift-format for canonical layout. Four packaging targets ship together: --target=swift-ios produces a code-signed .ipa via xcodebuild archive (~5-15 MB, ready for TestFlight or App Store Connect); --target=swift-macos produces a signed .app bundle or .dmg via codesign + notarytool (~3-10 MB, distributable via Developer ID); --target=swift-linux-static produces a single statically linked Linux binary via the Static Linux SDK with musl libc (~10-15 MB, ready for systemd or container deployment); --target=swift-windows produces a Windows .exe with MSI installer via WiX (~4-8 MB). Secondary targets --target=swift-watchos, --target=swift-tvos, and --target=swift-visionos ship simultaneously and share the iOS code path.
The master correctness gate is byte-equal stdout from the produced binary (executable Swift target run directly, or iOS app run in the simulator with stdout captured via XCUITest) versus vm3 on the entire fixture corpus, across Swift 6.0 and Swift 6.1, on x86_64-linux-gnu, aarch64-linux-gnu, aarch64-darwin (macOS arm64), and x86_64-windows. vm3 is the recording oracle for expect.txt; the transpiler does not link against or depend on vm3.
Five load-bearing decisions:
-
Swift 6.0 floor with strict concurrency by default. Swift 6.0 (released 2024-09-17 alongside Xcode 16) is the first release with Swift 6 language mode: complete sendable checking, region-based isolation (SE-0414), typed throws (SE-0413), and non-copyable generics (SE-0427) all reach
Active. MEP-49 emits exclusively against Swift 6 language mode. This locks in static guarantees that Mochi's type system already proves at the Mochi level (sendability of message payloads, exhaustive switch, nominal error types) and prevents the codegen pass from emitting code that compiles under Swift 5.x but breaks under Swift 6.x. Floor-ing at 6.0 drops Xcode 15 (last supported 2024-09); by the MEP-49 implementation landing horizon (2026 H2), Xcode 16 is the App Store floor anyway. Swift 5.10 is rejected because typed throws and complete sendability are post-6.0; backporting via flags creates a dual codepath. See 02-design-philosophy §3, 12-risks-and-alternatives §R1, §A2. -
All Swift-supported platforms, not Apple-only. The platform matrix is Apple platforms (iOS 18+, iPadOS 18+, macOS 15+ Sequoia, watchOS 11+, tvOS 18+, visionOS 2+) plus Linux (x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-unknown-linux-musl via Static Linux SDK) plus Windows (x86_64-pc-windows-msvc). Excluding Linux/Windows would force users with a Swift iOS frontend and a Mochi backend to switch Mochi targets (.NET, JVM, BEAM, C) for the backend, breaking the single-language story. Server-side Swift via Vapor and Hummingbird reached production at major employers in 2024-2025; Mochi serves both client and server in one toolchain. The cost is a 5-OS-by-2-arch CI matrix, comparable to MEP-47 (JVM) and MEP-48 (.NET). See 02-design-philosophy §4, 07-swift-target-portability §1-7.
-
Mochi agents as Swift
actor+AsyncStream<Message>mailbox. Swift Concurrency (introduced Swift 5.5, finalised 6.0) provides actor isolation (serial method dispatch with sendable enforcement) and AsyncStream (a buffered, backpressure-aware async sequence with bounded policies). Mochi agents lower one-to-one: an agent declaration becomes apublic actortype; the mailbox is a privateAsyncStream<Message>with.bufferingOldest(N)policy;cast(.msg)is acontinuation.yield(.msg);call(.req) -> Replyuses aCheckedContinuation<Reply, Error>carried as an associated value of the message enum. The actor's mailbox loop is a privatefor await msg in mailboxrunning in a Task launched atinit. No GCD, no Combine, no actor-framework dependency (Akka-Swift, Pekko-Swift do not exist; we do not introduce one). See 02-design-philosophy §5, 09-agent-streams §1-§12. -
Reuse MEP-45's
aotirIR plus all shared passes. The IR is target-agnostic; monomorphisation, match-to-decision-tree, closure-conversion, exhaustiveness checking, and sendability inference all run once and feed five backends. The fork is at the emit pass:transpiler3/swift/lower/lowersaotirto Swift-source structural nodes;transpiler3/c/emit/lowersaotirto C;transpiler3/beam/lower/to Core Erlang;transpiler3/jvm/lower/to Java source;transpiler3/dotnet/lower/to C# source. Sharing the IR keeps the five targets semantically aligned and amortises pass-implementation work across all five. See 05-codegen-design §5. -
Foundation plus apple/swift- packages as fat runtime;
MochiRuntimeas thin runtime.* The runtime libraryMochiRuntime(Apache-2.0, ~6000 LOC) provides only what Foundation and the apple/swift-* package family do not: Mochi-typed function-interface zoo (handled by Swift closures directly), Mochi-shaped collection helpers re-exportingOrderedDictionary/OrderedSet/Deque/Heapfrom apple/swift-collections, a small Datalog engine, AI / FFI dispatch tables, agent supervisor, ZonedDateTime polyfill (Foundation Date is wall-clock only), JSONValue enum for dynamic JSON. Everything else (HTTP, file I/O, regex, locale, dates) goes through Foundation (Apple or swift-corelibs-foundation) directly. Jackson-equivalent: System.Text.Json-equivalent: FoundationJSONEncoder/JSONDecoder. AlamoFire, SwiftyJSON, Moya, RxSwift, Combine are explicitly rejected as runtime deps. See 04-runtime §1-§20, 02-design-philosophy §8 and §13.
The gate for each delivery phase is empirical: every Mochi source file in tests/transpiler3/swift/fixtures/ must compile via the Swift pipeline and produce stdout that diffs clean against the expect.txt recorded by vm3. swiftc-clean (with -strict-concurrency=complete -warnings-as-errors -swift-version 6) on generated code is the secondary gate. swift-format fixed-point (running format twice produces no diff) is the tertiary gate. iOS / macOS app bundle validation via xcrun altool is the quaternary gate. Static Linux SDK single-binary build is the quinary gate. Reproducibility (bit-identical .swiftmodule and .o across two CI hosts) is the senary gate.
Motivation
Mochi today targets vm3 (for mochi run), MEP-45 (C, single-binary AOT), MEP-46 (BEAM, supervision and hot reload), MEP-47 (JVM, Maven Central and Loom), and MEP-48 (.NET, NuGet and NativeAOT). None deliver the Apple platforms:
-
Apple App Store. iOS apps require Swift or Objective-C compiled by Apple's toolchain, signed by an Apple Developer Program account, distributed through App Store Connect. Sideloading exists on EU iOS via the Digital Markets Act (since iOS 17.4, 2024-03) but remains a fringe distribution channel. macOS, watchOS, tvOS, and visionOS apps follow the same rules. The C target (MEP-45) cannot produce a
.ipa. The JVM target (MEP-47) reaches Android via D8/R8 but not iOS. The .NET target (MEP-48) reaches iOS via .NET MAUI but the resulting bundles include the Mono runtime (forbidden for some App Store categories) and have a 30-100 MB footprint that loses on the App Store benchmark. The Swift target produces idiomatic Swift indistinguishable from hand-written code after swift-format, sized at 5-15 MB, free of any embedded runtime evaluator, ready for App Review. -
visionOS. Apple Vision Pro shipped 2024-02-02 and is the only commercially viable AR/VR platform from a major vendor. visionOS apps are Swift-only (Objective-C support is partial; SwiftUI is the canonical UI framework). MEP-49 reaches visionOS as a first-class target, sharing 95% of the iOS codegen path.
-
Server-side Swift. Vapor 4.99 (2024-10) and Hummingbird 2.0 (2024-08) reached production quality. Major employers (Apple internal services, a number of Fortune 500 backend teams) shipped production Swift services in 2024-2025. A Mochi user with a Swift iOS frontend and a Mochi backend can now keep one language across the stack instead of crossing a JSON serialisation boundary at every API call.
-
CLR-style reified generics with value-type performance. Swift generics are reified (the compiler specialises per type, no JVM-style erasure), value types (struct, enum) live on the stack or are copied by value, and ARC removes the need for tracing GC overhead. Numeric Mochi code (matrix math, signal processing) lowers to Swift code that the optimiser compiles to SIMD-vectorised loops competitive with C. The .NET target offers similar reified generics but pays a tracing-GC tax for long-running services; the Swift target's ARC has deterministic deallocation and no stop-the-world pauses.
-
AsyncSequence and structured concurrency. Swift's
for await elem in streamandwithThrowingTaskGroup { group in ... }are first-class control flow, not library calls. The error and cancellation propagation is automatic. Mochi streams and parallel blocks lower one-to-one. Compare .NET's IAsyncEnumerable (similar but more verbose), JVM's Flow.Publisher (lower-level, not control-flow), BEAM's GenStage (different paradigm). Swift's syntax and semantics are the closest to Mochi's own. -
Apple's first-party Swift packages: a curated standard library above the language stdlib. apple/swift-collections, apple/swift-algorithms, apple/swift-async-algorithms, apple/swift-numerics, apple/swift-system, apple/swift-log, apple/swift-metrics, apple/swift-distributed-tracing all ship from Apple under permissive licences (Apache-2.0). The quality bar is high; the API stability is reliable. Mochi runtime re-exports these to give Mochi users a canonical surface above the language.
-
FoundationModels. Apple's on-device LLM framework (iOS 18+, macOS 15+ Apple Silicon only) is the first vendor-provided, privacy-preserving local LLM with a stable Swift API. Mochi
generatelowers to FoundationModels on eligible platforms with swift-openai-async fallback elsewhere. No other Mochi target reaches FoundationModels. -
SwiftUI, SwiftData, Observation. Apple's modern declarative-UI, persistence, and state-observation frameworks are Swift-only. While MEP-49 v1 does not expose these as Mochi language surface (they remain v2 candidates), Mochi-emitted Swift code is consumable from SwiftUI projects: users import the Mochi-generated package and call Mochi functions from their SwiftUI views.
-
Static Linux binary via the Static Linux SDK. Swift 5.9 (2023-09) added the Static Linux SDK, producing single statically linked Linux binaries (musl libc) with
swift build --swift-sdk x86_64-swift-linux-musl. Comparable to Go'sgo buildoutput. Mochi--target=swift-linux-staticships single-binary Linux deployments without container or shared-library dependencies. -
Windows .exe. Swift on Windows reached production quality in Swift 5.9 (2023-09). The toolchain ships as MSI, integrates with MSVC linker, bundles ICU. Mochi
--target=swift-windowsproduces native .exe binaries.
The C target (MEP-45) remains the right choice for embedded targets, single-file distribution, and minimal runtime footprint. The BEAM target (MEP-46) remains the right choice for hot-reload services, distributed pubsub, and OTP supervision. The JVM target (MEP-47) remains the right choice for Maven Central interop, Loom concurrency, JIT performance, and Android. The .NET target (MEP-48) remains the right choice for NuGet, value-type structs without ARC, and Windows-enterprise integration. The Swift target is the right choice for Apple platforms (iOS, macOS, watchOS, tvOS, visionOS), App Store distribution, server-side Swift, and FoundationModels access. All five ship; the user picks per workload.
Specification
This section is normative. Sub-notes under ~/notes/Spec/0049/01..12 are informative.
1. Pipeline and IR reuse
MEP-49 shares the front-end and aotir passes with MEP-45, MEP-46, MEP-47, and MEP-48 and forks at the emit stage:
Mochi source
| parser (MEP-1/2/3, reused)
v
typed AST
| type checker (MEP-4/5, reused)
v
aotir IR
| monomorphisation pass (shared)
| closure conversion pass (shared)
| match decision tree (shared)
| exhaustiveness check (shared)
| sendability inference (shared)
v
Swift source codegen pass (transpiler3/swift/lower/)
| emit Swift 6.0 source via Mochi-side syntax tree
| optional: swift-format format --in-place
v
.swift files under out/Sources/<Module>/
| emit Package.swift at out/
| emit module.modulemap if FFI present
v
swift build (libraries / Linux / Windows executables)
xcodebuild archive (iOS / macOS / watchOS / tvOS / visionOS apps)
| codesign (Apple platforms only)
| notarytool submit (macOS Developer ID)
| stapler staple (macOS Developer ID)
v
.ipa / .app / .dmg / Linux static binary / .exe + .msi
Both mochi run (vm3) and mochi build (transpiler3) share the same parser, type system, and IR.
2. Build driver UX
mochi build --target=<TGT> <input.mochi> [-o <output>]
Targets:
swift-ios: produces a code-signed.ipavia xcodebuild archive plusxcrun altool --validate-app.swift-macos: produces a signed.appbundle (or.dmgwith the--dmgflag) via codesign + notarytool + stapler.swift-watchos,swift-tvos,swift-visionos: produces signed app bundles for the named Apple platform.swift-linux-static: produces a single statically linked Linux binary via the Static Linux SDK (musl).swift-linux-dynamic: produces a dynamically linked Linux binary (libSwift required at runtime).swift-windows: produces a Windows .exe.swift-source: emits Swift source plus Package.swift without building (for downstream Xcode integration).swift-library: emits a SwiftPM library target consumable from another Swift project.
The driver dispatches to platform-specific tools: swift build for SwiftPM, xcodebuild for Apple platforms, codesign/notarytool/stapler for signing.
3. Name mangling
Mochi names → Swift names:
- Module path
mochilang/aiops/Pipeline→ Swift moduleMochiLangAiopsPipeline(PascalCase concatenation withMochiprefix when unique). - Mochi function
process_batch→ SwiftprocessBatch(lowerCamelCase). - Mochi type
User_Record→ SwiftUserRecord(PascalCase). - Mochi sum variant
OK→ Swift caseok(lowerCamelCase; original mangling table emitted alongside for FFI). - Mochi reserved-word collisions:
class,protocol,actor,extension,Any,Type,Self,Sendableare escaped with a_suffix (class_).
4. Type lowering
Per 06-type-lowering:
int→Int64(notInt; fixed 64-bit).float→Double.bool→Bool.string→String(UTF-8 native).bytes→Dataat I/O boundaries,[UInt8]in core.list<T>→[T].map<K, V>→[K: V].set<T>→Set<T>.ordered_map<K, V>→OrderedDictionary<K, V>(apple/swift-collections).record { ... }→@frozen public struct ...: Sendable, Hashable, Codable.union { ... }→public enum ...: Sendable, Hashable, Codablewithindirectcases for recursion.option<T>→T?.result<T, E>→Result<T, E>.fun(T) -> R→(T) -> R.agent→public actor.stream<T>→AsyncStream<T>orAsyncSequencegeneric.
5. Expression lowering
Per 05-codegen-design §13-§22:
- Mochi literals → Swift literals; Swift integer literals are
Intby default, so Mochi codegen emitsInt64(...)explicitly. - Mochi index expressions → Swift subscripts.
- Mochi
match→ Swiftswitchwith case patterns andwhereguards; exhaustiveness verified by Swift compiler. - Mochi
if-let→ Swiftif let. - Mochi closure literal
fn x => x + 1→ Swift closure{ (x: Int64) -> Int64 in x + 1 }. - Mochi method call
obj.method(args)→ Swift method call (extension methods for record types). - Mochi
withexpression → Swiftwithmethod on the struct.
6. Closures
Per 05-codegen-design §12, §17:
- Mochi closures lower to Swift closures with explicit
@Sendablewhen crossing actor boundaries. - Captures are by-value (Swift default for
let); explicit capture lists are emitted only when needed forweak selfor[x = x]. - Escaping closures (stored in struct fields) emit
@escaping.
7. Runtime library
Per 04-runtime:
MochiRuntimeSwiftPM package (Apache-2.0, ~6000 LOC).- Re-exports apple/swift-collections, apple/swift-algorithms, apple/swift-async-algorithms, apple/swift-numerics, apple/swift-system, apple/swift-log.
- Adds Mochi-specific: agent supervisor (
MochiRuntime.Supervisor), datalog evaluator (MochiRuntime.Datalog), ZonedDateTime, JSONValue enum, query DSL extensions. - Targets Swift 6.0 minimum; library evolution enabled for ABI stability across Mochi versions.
8. Concurrency
Per 09-agent-streams:
- Mochi agent → Swift
actor. - Mailbox:
private var mailbox: AsyncStream<Message>+private var continuation: AsyncStream<Message>.Continuation. cast(.msg)→continuation.yield(.msg)(fire-and-forget).call(.req)→await withCheckedThrowingContinuation { cont in continuation.yield(.req(cont)) }.spawn Foo(...)→Foo(...)(the actor's init starts the mailbox loop).- Streams:
AsyncStream<T>andAsyncSequencegeneric. - Parallel blocks:
await withThrowingTaskGroup(of: R.self) { group in ... }. - Cancellation: cooperative via
Task.checkCancellation().
9. Memory model
- ARC (Automatic Reference Counting) for class types; value semantics for struct/enum.
- Mochi closures captured into struct fields use explicit capture lists when needed.
- Mochi
weakandunownedreferences emitted for cyclic graphs (supervisor → child links useunowned; caches useweak). - No tracing GC.
10. Error model
Per 06-type-lowering §7, 02-design-philosophy §11:
- Mochi
Result<T, E>→ SwiftResult<T, E>. - Mochi throwing function
fun parse() -> AST throws ParseError→ Swiftfunc parse() throws(ParseError) -> AST(typed throws, SE-0413). - Mochi
try/catch(planned) → Swiftdo/catch. - Mochi
panic→ SwiftfatalError.
11. Portability
Per 07-swift-target-portability:
- Apple platforms: deployment targets iOS 18, iPadOS 18, macOS 15, watchOS 11, tvOS 18, visionOS 2.
- Linux: Ubuntu 22.04 LTS minimum, x86_64-unknown-linux-gnu and aarch64-unknown-linux-gnu, plus static via musl.
- Windows: Windows 10 1809+ minimum, x86_64-pc-windows-msvc only.
- Embedded Swift: out of v1 scope, reserved for v2.
- SwiftWasm: out of v1 scope, reserved for v2.
12. Build system
Per 10-build-system:
- SwiftPM as canonical build driver:
swift build. - Apple-platform apps: emit SwiftPM library + Xcode project, build via
xcodebuild archive. - Cross-compile to Linux from macOS: Static Linux SDK installed via
swift sdk install. - Windows: native MSVC toolchain on Windows host (no cross-compile from non-Windows).
- Build determinism:
--cache-path+SWIFTPM_DETERMINISTIC_BUILD=1+ pinned toolchain.
13. Reproducibility
Per 11-testing-gates §10:
- Pinned Swift toolchain (
.swift-versionfile checked in). - swift-format applied deterministically.
- No
__DATE__/__TIME__/__FILE__macros in emitted code. - Codesign excluded from byte-equality check (codesign stamps timestamp); unsigned binary is bit-identical.
Package.resolvedchecked in.
14. Hardening
Per 11-testing-gates §14:
- swiftc with
-warnings-as-errors -strict-concurrency=complete -swift-version 6. - No
unsafeBitCast/Unsafe*Pointer.assumingMemoryBoundin user-facing code. - Mac App Store sandbox entitlements emitted with minimal allow-list.
- TLS pinning available via URLSessionDelegate; manifest-driven.
15. Diagnostics
- Mochi emits Swift source with
// swift-format-ignoreonly where absolutely necessary; tracked inSUPPRESSIONS.md. - Source maps:
.mochi.mapsidecar per generated.swiftfor debugger integration. - DWARF debug info available via
swift build -c debug.
16. FFI
Per 01-language-surface §10, 06-type-lowering §16:
- Mochi
extern fun foo(...) -> ...from a C module →@_silgen_name("foo") func foo(...)plus amodule.modulemapdeclaring the C module. - Mochi-side exports:
@_cdecl("mochi_foo") public func mochiFoo(...). - C struct: Swift
structmatching C layout via@_silgen_nameandwithUnsafePointer. - Module maps generated per Mochi
import "c/<library>"declaration.
17. Output style
- 4-space indentation (Swift convention).
- K&R brace style.
- Explicit
publicmodifiers on all public APIs. - Explicit type annotations on public function signatures (Library Evolution requirement).
- Sorted imports, sorted dictionary keys in literals (for determinism).
Rationale
The five load-bearing decisions (§Abstract) flow from a single observation: Apple platforms require Swift, and Swift 6.0 is the version of Swift that catches at compile time the same invariants Mochi already proves at the Mochi level. Lower Mochi to Swift 6.0 and the two type systems align; the Swift compiler becomes a second-line check on Mochi's correctness.
The choice of actor + AsyncStream over GCD or a custom runtime is forced by the same logic: Swift's sendability checker is the second-line check on Mochi's agent-message-sendability rule. A GCD-based lowering would skip sendability entirely.
The choice of all Swift-supported platforms (not Apple-only) follows from the user-facing goal: Mochi should let a single team ship the same backend logic to iOS, macOS, Linux, and Windows. Apple-only would re-introduce the multi-language stack the Mochi target plurality was designed to eliminate.
The choice of SwiftSyntax-shaped emission (Mochi-side syntax tree, not raw strings, not direct dependency on apple/swift-syntax) is forced by codegen reproducibility: hand-rolled string templates drift, swift-format alone cannot fix structural bugs. A Go-side syntax model gives us correctness without the build-time cost of a Swift toolchain dependency.
The thin runtime (MochiRuntime) is the same philosophy that drove MEP-47 (thin dev.mochi.runtime) and MEP-48 (thin Mochi.Runtime): the platform's first-party libraries are the canonical surface; Mochi adds only what is missing.
Backwards Compatibility
MEP-49 is purely additive. mochi run keeps the vm3 path; existing transpiler3 targets (C, BEAM, JVM, .NET) are untouched. No Mochi language surface changes. The Swift target lands as a new transpiler3/swift/ subtree and new tests/transpiler3/swift/ fixture corpus. Phase gates ensure no cross-target regression.
Reference Implementation
Implementation lives under:
transpiler3/swift/aotir/: MochiaotirIR consumer (target-agnostic).transpiler3/swift/lower/:aotir→ Swift source codegen pass.transpiler3/swift/emit/: file writer, Package.swift emitter, swift-format invocation.transpiler3/swift/build/: driver forswift build,xcodebuild, codesign, notarytool.runtime/swift/MochiRuntime/: SwiftPM package source.tests/transpiler3/swift/: fixture corpus and gate tests.
The transpiler3/swift codegen pass is approximately 4000 LOC of Go (a Mochi-side syntax tree model plus a pretty-printer). The runtime library MochiRuntime is approximately 6000 LOC of Swift across ~30 files. The fixture corpus targets ~400 fixtures by Phase 18 completion.
Phase plan
Eighteen phases mirroring MEP-45/46/47/48:
| Phase | Name | Surface |
|---|---|---|
| 1 | Hello world | Basic print, let, int |
| 2 | Scalars | int/float/bool/string ops, comparisons |
| 3.1 | Lists | list literal, index, len, for-each |
| 3.2 | Maps | map literal, index, len, keys, values, has |
| 3.3 | Sets | set literal, add, has, len |
| 3.4 | Lists of records | list[record], comprehensions over records |
| 4 | Records | records, methods, equality, with |
| 5 | Sum types | sum types, pattern matching, exhaustiveness |
| 6 | Closures and higher-order | closures, higher-order, @Sendable |
| 7 | Query DSL | from/where/select, group_by, order_by, joins |
| 8 | Datalog | facts, rules, recursion |
| 9 | Agents | actor definitions, spawn, call, cast |
| 10 | Streams | streams, AsyncSequence, await foreach |
| 11 | Async colouring | async colouring, typed throws |
| 12 | Swift FFI | C interop via module maps |
| 13 | LLM | generate (FoundationModels on Apple, mock elsewhere) |
| 14 | Fetch | fetch (URLSession, against local test server) |
| 15 | iOS app bundle | .ipa bundle, codesign, xcodebuild archive |
| 16 | Reproducible build | byte-identical .swiftmodule and .o |
| 17 | Static Linux single binary | static Linux SDK, single binary |
| 18 | App Store validation | App Store / Mac App Store validation |
Per 11-testing-gates §18, a phase lands only when all gates are green: per-phase fixture corpus, swiftc clean, swift-format fixed-point, cross-target differential where applicable, App Store validation for Phase 15+, Static Linux SDK gate for Phase 17.
Dependencies
- MEP-4 (Type System), MEP-5 (Type Inference), MEP-13 (ADTs and Match): Mochi front-end.
- MEP-45 (C transpiler):
aotirIR plus shared passes. - MEP-46 (BEAM transpiler): shared IR confirmation, cross-target gates.
- MEP-47 (JVM transpiler): shared IR confirmation, prior art for Java-source emission.
- MEP-48 (.NET transpiler): shared IR confirmation, prior art for C#-source emission.
External:
- Swift toolchain 6.0+ (Apple-shipped, swift.org-shipped).
- SwiftPM (bundled with toolchain).
- xcodebuild (Apple platforms only, bundled with Xcode 16+).
- codesign, notarytool, stapler (Apple platforms only, bundled with Xcode).
- WiX Toolset 4.x (Windows MSI packaging).
- apple/swift-collections, apple/swift-algorithms, apple/swift-async-algorithms, apple/swift-numerics, apple/swift-system, apple/swift-log (runtime deps).
Open questions
Per 12-risks-and-alternatives §3:
- Q1: SwiftUI lowering. v2.
- Q2: SwiftData lowering. v2.
- Q3: Embedded Swift target. v2.
- Q4: SwiftWasm target. v2.
- Q5: Windows ARM64 target. v2 when toolchain matures.
- Q6: Distributed actors. v2.
- Q7: App Store automation. v2.
Security considerations
- Codesign and notarization mandatory for distribution outside Mac App Store on macOS.
- Mac App Store sandbox entitlements emitted with deny-by-default policy.
- TLS pinning available via URLSessionDelegate.
- FFI requires manifest entry; reflection-bypass rejected at runtime.
- No
unsafeSwift constructs in user-facing code; runtime libraryMochiRuntime.Unsafenamespace contains pointer manipulations. - Static Linux SDK statically embeds ICU and mbedTLS; supply-chain security depends on Apple's toolchain provenance.
References
- SE-0306: Actors. https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md
- SE-0314: AsyncStream. https://github.com/apple/swift-evolution/blob/main/proposals/0314-async-stream.md
- SE-0335: any types. https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md
- SE-0336: distributed actor. https://github.com/apple/swift-evolution/blob/main/proposals/0336-distributed-actor-isolation.md
- SE-0381: C++ interop. https://github.com/apple/swift-evolution/blob/main/proposals/0381-cxx-interop.md
- SE-0382: Macros. https://github.com/apple/swift-evolution/blob/main/proposals/0382-macros.md
- SE-0390: ~Copyable. https://github.com/apple/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md
- SE-0413: Typed throws. https://github.com/apple/swift-evolution/blob/main/proposals/0413-typed-throws.md
- SE-0414: Region-based isolation. https://github.com/apple/swift-evolution/blob/main/proposals/0414-region-based-isolation.md
- SE-0427: Noncopyable generics. https://github.com/apple/swift-evolution/blob/main/proposals/0427-noncopyable-generics.md
- SE-0446: ~Escapable. https://github.com/apple/swift-evolution/blob/main/proposals/0446-non-escapable.md
- Swift 6.0 release notes. https://swift.org/blog/swift-6/
- swift-corelibs-foundation. https://github.com/swiftlang/swift-corelibs-foundation
- swift-collections. https://github.com/apple/swift-collections
- swift-async-algorithms. https://github.com/apple/swift-async-algorithms
- swift-syntax. https://github.com/swiftlang/swift-syntax
- swift-format. https://github.com/swiftlang/swift-format
- Swift Package Index. https://swiftpackageindex.com/
- Static Linux SDK. https://swift.org/blog/swift-static-linux-sdk/
- FoundationModels framework. (Apple Developer Documentation, iOS 18+, macOS 15+)
- Vapor 4. https://vapor.codes
- Hummingbird 2. https://github.com/hummingbird-project/hummingbird
Research notes
Twelve research notes elaborate the design:
- 01-language-surface: Mochi sub-languages mapped onto Swift 6.0 lowering obligations.
- 02-design-philosophy: Why Swift, why Swift 6.0 floor, why actor + AsyncStream, why all platforms.
- 03-prior-art-transpilers: Skip.tools, J2ObjC, Swiftify, Sourcery, Hylo, Mojo, Embedded Swift, SwiftWasm, IL2CPP analogues.
- 04-runtime: Swift stdlib, Foundation, swift-corelibs-foundation, apple/swift-* packages, MochiRuntime layout.
- 05-codegen-design: Mochi-side syntax tree emission, swift-format integration, aotir IR reuse.
- 06-type-lowering: Type-by-type mapping to Swift 6.0 (Int64, struct, enum, actor, AsyncStream, Codable).
- 07-swift-target-portability: Platform matrix, Static Linux SDK, App Store packaging, Windows MSI.
- 08-dataset-pipeline: Query DSL lowering via Sequence/AsyncSequence + swift-collections + swift-algorithms.
- 09-agent-streams: Mochi agents as Swift
actor+ AsyncStream mailboxes; structured concurrency. - 10-build-system: SwiftPM, Package.swift, xcodebuild, codesign + notarytool, WiX.
- 11-testing-gates: Per-phase Go test gates, Swift version matrix, App Store validation, Static Linux SDK gate.
- 12-risks-and-alternatives: Risk register, Kotlin Multiplatform / Combine / GCD rejected and why.
The 18-phase delivery plan walks from hello-world through scalars, collections, records, sums, closures, queries, datalog, agents, streams, async, Swift FFI, LLM, fetch, then iOS app bundle, reproducibility, static Linux single binary, and App Store validation. Each phase is gated against vm3.