The in-browser compiler#
A plan for a Swift playground that compiles and runs SwiftUI apps entirely in the browser: no server, no container, the real Swift compiler running as WebAssembly next to the renderer. This document is the plan, not a record of what works; History will say what landed.
The first goal is deliberately small and has no browser in it: a CLI that
compiles a Swift hello world through a WebAssembly build of the Swift
compiler and links it into a .wasm that runs. Everything after that
reuses pieces this repository already has.
Why this shape#
SwiftBrowser's invariant is that an app's source imports SwiftUI and
compiles unchanged for iOS and the browser. A playground has to keep that, so
it has to run Apple's compiler: a hand-written Swift interpreter or a subset
compiler (the shape of MiniSwift)
would re-implement Sema, where Swift's complexity lives, and would drift from
the real language the way the shim is forbidden to.
The precedents, and what each one proves:
- clang in the browser. Wasmer runs clang as a WebAssembly module in Chrome, Safari and Firefox (their post), at about 100 MB uncompressed. LLVM-sized C++ runs in a browser.
- Linking in the browser. swiftwasm-pad compiles on a server but links in the browser: a Swift-written linker in a Web Worker joins the user's object file to a prebuilt shared library of the stdlib and its frameworks. Only the compiler stayed on the server.
- This repository. The stdlib, Foundation and the shim are already built
once into a kit (
packages/cli/src/kit.ts): per shim target a.swiftmoduleand an archive, plus the macros, so an app's build compiles only the app. The renderer already runs WASI commands through@bjorn3/browser_wasi_shim(Web/src/wasm.ts) and already restores@Stateacross a rebuild. The CLI already rewrites wasm custom sections in TypeScript (packages/cli/src/wasm.ts) and already works around small default thread stacks for big modules (packages/cli/src/threadStacks.ts).
So the one piece nobody has shipped is swift-frontend built for a
WebAssembly host. That is the critical path; the rest is assembly.
The pipeline, stage by stage#
A swiftbrowser dev build today is six programs. Each becomes one of three
things in the browser: a port to WebAssembly, a rewrite in TypeScript, or a
prebuilt file.
| Stage today | Becomes | Why |
|---|---|---|
swift build and swift-driver (Swift) |
TypeScript, rewritten | They only compute swift-frontend and wasm-ld argument lists. Porting them would drag in Foundation, Dispatch and process spawning for nothing. |
swift-frontend (C++ plus Swift) |
WebAssembly, ported | Parser, Sema, SILGen, the SIL optimizer, IRGen and LLVM. There is no substitute. |
| ClangImporter (inside the frontend) | WebAssembly, with prebuilt module caches | It runs on every compile, for SwiftShims at least. Its precompiled modules (PCMs) are built once and shipped, so it never parses a C header at runtime. |
Macro plugins (-load-plugin-executable, a child process per plugin) |
TypeScript host, macros as WebAssembly | Swift can compile macro plugins for Wasm and the compiler already speaks to plugins over a JSON protocol. The TypeScript host answers that protocol and runs the macro module in the browser's own engine. SwiftDataMacros (@Model, #Predicate, @Entry) is the one plugin apps need. |
wasm-ld |
WebAssembly first, maybe TypeScript later | lld builds for a WebAssembly host today. A TypeScript linker is worth it only once dynamic linking is the goal (see "Later"). |
wasm-opt |
skipped, or binaryen.js | Binaryen ships as a JavaScript and WebAssembly package already. A playground build does not need -Osize and stripping. |
| The kit, Foundation, the WASI sysroot | prebuilt, downloaded once | Exactly the files the CLI's kit holds, plus the Swift SDK's stdlib modules and archives, laid out for a virtual file system. |
Where TypeScript fits#
- Rewrite in TypeScript: the driver (argument lists and the order of
invocations), the WASI host (in-memory and persisted file systems, clocks,
stdout capture, the big-stack worker), the macro plugin host, diagnostics
parsing, and everything in the editor. Two pieces of the CLI already run
without Node-specific dependencies and can run in the page as they are:
the import report behind
swiftbrowser check(packages/cli/src/compat.ts) gives instant "this import is not supported" feedback before the compiler is even loaded, and@swiftbrowser/xcodeprojreads an Xcode project dropped onto the page. - Maybe, later: the linker. The relocatable object format and the
linking conventions are documented and stable,
packages/cli/src/wasm.tsalready parses sections, and a TypeScript linker would make incremental and dynamic linking ours to shape. The hard parts are section garbage collection (without it the output balloons), thread-local storage, and synthesizing the constructor call. Not beforewasm-ldas Wasm has shown the rest working. - Never: the frontend proper. Rewriting Sema in TypeScript is the subset-compiler path in different clothes.
Milestone 1: hello world through a Wasm compiler, from a CLI#
Done when: Sources/HelloWasm/main.swift is compiled by a swift-frontend
that is itself a WebAssembly module, linked by a wasm-ld that is itself a
WebAssembly module, both run from a Node CLI with no native Swift toolchain
on the machine, and the resulting hello.wasm prints its line under
wasmtime. No browser, no shim, no macros, no Foundation.
Status: done. swiftbrowser-wasmc in
packages/wasm-compiler compiles and links HelloWasm with both tools as
WebAssembly under Node's WASI in about 2 s, and the output runs under
wasmtime; the in-memory host the browser will use does the same. The
measurements, sizes and what a 32-bit host needed are in the package's
README. The CI job is the WebAssembly compiler workflow; it fetches the
tools from @swiftbrowser/wasm-tools, whose modules live in Cloudflare R2
and ship to npm with the other packages, and the Swift SDK from swift.org.
The steps, in order; each has its own check so a failure says which assumption broke.
1.1 Record the native invocations#
Build HelloWasm natively with swift build --swift-sdk <wasm sdk> -v and
keep the exact swift-frontend and wasm-ld command lines, with every
path under the Swift SDK's artifact bundle resolved. Then replay both by
hand, with no SwiftPM and no driver, and check the result runs under
wasmtime. This is the specification for the TypeScript driver and the list
of files the virtual SDK has to contain: the target triple
(wasm32-unknown-wasip1, KIT_TRIPLE in kit.ts), the sysroot, the
resource directory under swift_static, swiftrt.o, the stdlib and
concurrency archives, wasi-libc, libc++, the compiler-rt builtins, and the
-z stack-size and --export flags the shim's apps carry.
Measure the native frontend here too: peak memory and wall time for
-typecheck and -c on HelloWasm, and on the Counter and Settings
examples against the kit, with /usr/bin/time -v. These numbers decide
between a 32-bit memory and Memory64 (step 1.3) and set the expectation for
the browser.
1.2 Build LLVM, Clang and lld for a wasm32-wasip1 host#
Before Swift enters the picture, build the C++ toolchain the compiler sits
on for a WebAssembly host, from the same llvm-project fork and tag Swift
6.4.0 builds from, so one source tree serves both. The configuration is
YoWASP's, which builds Clang and LLD for
WASI with one patch to LLVM's Support library; that patch, ported to Swift's
LLVM 21, is in packages/wasm-compiler/toolchain/patches/llvm-project.
LLVM_ENABLE_THREADS=OFF, no exceptions and no RTTI (Swift's LLVM builds
that way already), and only the WebAssembly target in
LLVM_TARGETS_TO_BUILD, which removes most of the binary.
The C++ compiler is the native Swift toolchain's clang, and the sysroot is
the Swift SDK's own WASI sysroot rather than wasi-sdk's, so the compiler's
C++ and its Swift (1.3) share one wasi-libc and one libc++. That libc++ is
built without threads, and LLVM's headers use std::mutex even with
threading off, so toolchain/build-sysroot.sh rebuilds libc++ 21 (ABI
version 2, as the Swift runtime expects) with threads over wasi-libc's
single-threaded pthread stubs, with wasi-sdk's own flags.
Check: clang.wasm compiles a C hello world and wasm-ld.wasm links it,
under wasmtime and under Node, and the result runs. This shakes out the
CMake setup, the host file system assumptions and the stack and memory
settings while the binary is still small enough to iterate on.
1.3 Build swift-frontend for a wasm32-wasip1 host#
Treat it as a new cross-compilation host for the compiler, the way the build already cross-compiles its host tools for Android and other Linux architectures: the compiler's CMake with the toolchain file from 1.2, against the LLVM, Clang and lld built there. The pieces, and the decision each one needs:
- The C++ compiler. Builds with the same flags as 1.2. Everything that
assumes a process exists is compiled out or stubbed on WASI: the crash
reporter and signal handlers,
PrettyStackTrace, the module cache's file locks (one process, so a lock that always succeeds),getrusage, spawning the plugin server and the driver's job execution. - The Swift in the compiler.
SwiftCompilerSources(optimizer passes written in Swift) is mandatory: since Swift 6 the pass manager refuses to build without it (#error "Building the compiler without Swift sources is not supported anymore"). It is cross-compiled towasm32-wasip1by the native toolchain'sswiftcwith C++ interop, against the Swift SDK's stdlib and the sysroot from 1.2 (BOOTSTRAPPING_MODE=BOOTSTRAPPINGwithSWIFT_NATIVE_SWIFT_TOOLS_PATHset becomesCROSSCOMPILE), and linked into the same module with the Swift SDK's static runtime, which is what every SwiftWasm program already is. swift-syntax (the new parser, macros) is off for this milestone (SWIFT_BUILD_SWIFT_SYNTAX=OFF, which also turns off macros and the regex literal parser); macros return in Milestone 2. - Stack. Sema and SIL recurse deeply; the native compiler runs on a
thread with a large stack. The Wasm module gets its stack from the
linker, so link with
-z stack-sizein the tens of megabytes, and run the module on a worker in the browser later.threadStacks.tsis the same problem solved forwasm-opt. - Memory. 32-bit. The native frontend peaks at about 250 MB on the
largest example, an optimized whole-module build (1.1's numbers are in
packages/wasm-compiler/README.md), far below the 4 GB a 32-bit memory allows, and every engine supports 32-bit memories. Memory64 is not needed. - Threads. None.
LLVM_ENABLE_THREADS=OFFand-num-threads 0; whole-module optimization still works single-threaded. - Size.
--gc-sections,--strip-alland awasm-opt -Ospass on the compiler itself; record the compressed size, since it is the playground's first download.
Check: swift-frontend.wasm -frontend -typecheck main.swift succeeds
against the Swift SDK's stdlib module under wasmtime, then
-frontend -c -primary-file main.swift -o main.o produces an object that
the native wasm-ld links and that runs. Mixing the native linker in
here isolates the frontend's bugs from the linker's.
1.4 Link in Wasm#
Replace the native wasm-ld in the 1.3 check with wasm-ld.wasm from 1.2,
with the argument list from 1.1. Compare the output to the native build's:
the same imports and exports, and the same text when run, with any size
difference explained.
1.5 The CLI#
A new package, packages/wasm-compiler (name to settle), with no native
Swift anywhere in it:
- A host abstraction with two backends: Node's own WASI with real
pre-opened directories, which is the simplest thing for a CLI and for
tests, and the in-memory
@bjorn3/browser_wasi_shimtreeWeb/src/wasm.tsalready builds, which is what the browser will use. The compiler and the linker are instantiated through this layer only, so Milestone 3 changes the backend and nothing else. - The driver in TypeScript: given sources, a module name, an
optimization level and the SDK layout, it produces the frontend
invocations (one per primary file, or one whole-module invocation) and
the linker invocation, as 1.1 recorded them. It is a pure function of
its inputs and is unit-tested against the recorded command lines.
swift-autolink-extractbecomes a few lines of TypeScript that read the objects' autolink section and order the libraries the way the tool does. - The SDK layout: a directory (and later a manifest of downloadable
files) holding the sysroot, the stdlib modules and archives,
swiftrt.oand the compiler-rt builtins, taken from the Swift SDK artifact bundle by a script that records which files the frontend and linker actually opened (the WASI shim can log every open). - A command:
swiftbrowser-wasmc hello.swift -o hello.wasm, plus--typecheck. Diagnostics come out as the frontend prints them, so the existingremapDiagnosticsinstage.tsapplies unchanged.
Check: a CI job next to hello-wasm that runs the CLI on HelloWasm and
then runs the output under wasmtime, on a runner with no Swift installed.
The compiler and linker modules and the SDK are fetched from a release
asset, since they are far too big for the repository.
Milestone 2: a SwiftUI app#
Done when: the Counter example (and then every example) compiles through the Wasm compiler against the kit, from the CLI, and runs in the existing dev server exactly as a native build does.
Status: every example builds this way and matches its native snapshot
(stages 2a and 2b). --compiler wasm (or no Swift install) makes the CLI's build and
dev compile and link with the WebAssembly tools
(packages/cli/src/wasmCompiler.ts), package dependencies included, and
macros expand through plugins built as WebAssembly that the host runs for
the compiler (packages/wasm-compiler/src/plugins.ts). Clang's module
cache can be prebuilt and carried into an in-memory session, where it
validates unchanged (stage 2c), cutting a first Foundation compile's
frontend from 2.8 to 1.0 s. The numbers are in
packages/wasm-compiler/README.md. A package's macro targets (TCA's) build
as WebAssembly plugins the same way, from the package's own sources rather
than its copy for the shim, with swift-syntax compiled unoptimized for them
alone: about 3.5 minutes the first time for swift-syntax, then cached by the
plugin's sources (buildPlugin in packages/cli/src/wasmCompiler.ts).
Registry dependencies (.package(id:)) resolve from the registries SwiftPM
is configured with (packages/cli/src/registry.ts). The Composable
Architecture builds and runs this way, its six macro targets as plugins:
about 8 minutes the first time on a 4-core machine, most of it
swift-syntax. The packages' compiled modules are kept between builds
(packages/cli/src/moduleCache.ts), keyed by what goes into each, so a
rebuild compiles only the modules an edit reaches, and another app shares
them: TCA rebuilds in about 25 s after an edit to the app, against about
170 s compiling its 22 package modules again (and 15–17 s with the native
toolchain).
- The kit as the SDK. Extend the SDK layout of 1.5 with the kit: the
shim's modules and archives,
FoundationBridge, and the Swift SDK's Foundation in the lean and full variants the CLI already distinguishes (icu.tstrims the ICU data per locale; the same files go in the manifest). The modules are tied to one compiler version, which is fine: the playground pins a toolchain and the manifest names it. - ClangImporter's caches. The first compile against the kit builds
PCMs for
SwiftShims, the WASI libc module map and Foundation's C modules. Build them once with the Wasm compiler itself, store them in the SDK, and point-module-cache-pathat them. PCMs validate against file paths and timestamps, so the virtual file system gives every SDK file a fixed path and a fixed timestamp, and the compile flags are the same string every time. - Macros. Turn swift-syntax back on in the compiler build, compile
SwiftDataMacrosforwasm32-wasip1the way the Swift compiler's own Wasm macro support expects, and replace the child-process plugin with a host import: the frontend writes a plugin message, the TypeScript host runs the macro module (instantiated once and reused) and hands the reply back. The plugin protocol is JSON over a pipe today, so the TypeScript host is the pipe. Verify with the examples that use@Model,@Queryand@Entry, and with#Preview, which the CLI already strips (compat.ts). - The linker's inputs. The kit's archives are large and mostly
unused by any one app;
--gc-sectionskeeps the output the size of a native build. Record link times here, since they decide whether Milestone 4's dynamic linking is needed. - Parity. The headless snapshot tests (
scripts/snapshot-test.sh) run the Wasm-compiled examples under wasmtime and diff against the same snapshots the native builds produce. Same ops, or a bug in the port.
Milestone 3: the compiler in the browser#
Done when: a page compiles and runs the Counter example with no server request after the initial downloads, in Chrome, Safari and Firefox.
Status: done in Chromium; Safari and Firefox are not tested yet (this
work's environment has only Chromium). The page is Web/playground/
(Web/src/playground/): Counter's sources in an editor, compiled and
linked in a worker on the in-memory host with the CLI's own staging and
flags (its browser entry, packages/cli/src/browser.ts), and run by the
renderer's app page in a frame, which takes the module as a blob: URL
(?module=). The page itself is SwiftUI views from @swiftbrowser/react
(app.tsx), laid out like Xcode: the files in a NavigationSplitView's
sidebar, then the editor beside a simulator, the app page's iPhone
(?embed=1, without its toolbar) scaled to fit; in a compact width (a
phone) the code is a navigation stack's root, the simulator a screen its
bar's iPhone button (or a build that links) pushes, and the files an
inspector (a sheet there). Edits, compile errors and @Observable models work, and
after the first visit a reload compiles with no request for an asset.
Measured in Chromium against a local server (Web/playground/smoke.mjs):
| Time | |
|---|---|
| First visit, downloads to running app | 11–15 s (frontend 3.0 s, wasm-ld 3–4 s) |
| Reload, everything from the Cache API | 7.0–7.2 s |
| An edit | 6.5 s |
| A type error | 2.0 s |
Every file comes from npm. The page fetches the packages the CLI uses, at the release's version, through jsDelivr, which serves an npm package file by file (up to 150 MB a package) with CORS and immutable caching, and compresses what it serves:
| Package | What the page reads |
|---|---|
@swiftbrowser/wasm-tools |
the compiler (27 MB) and linker (9 MB), brotli-compressed, and the toolchain's macro plugins |
@swiftbrowser/wasm-sdk, -foundation, -icu |
the 452 SDK files a compile reads (142 MB) |
@swiftbrowser/kit |
the kit's modules and archives a compile reads (40 files, 43 MB), and its macros |
@swiftbrowser/playground |
playground.json (which files of the others), the ICU data trimmed to English, the module cache |
No browser's DecompressionStream reads brotli, so a WebAssembly decoder
(brotli-dec-wasm, 200 KB) unpacks the tools as they arrive (2.4 s for the
compiler). The Cache API keeps every file unpacked under its versioned URL,
so a reload makes no request and decodes nothing, and a new version drops
the old files.
How it differs from the plan below:
- Files recorded, not resolved. A Node script
(
Web/playground/build-assets.ts) compiles the page's apps with the page's own code over the whole SDK and kit as the packages hold them, records the files the tools open, and writes@swiftbrowser/playground: their list by package, the trimmed ICU data and the module cache those compiles leave. An app that reads a file no recorded compile opened would fail; adding it to the recorded apps (--app) puts its files in. ICU's 34 MB data member is left out of the SDK's archive, and the page links its trimmed data in its place, as the CLI does. - The Cache API, not the origin-private file system: each file is one immutable response.
- No
-typecheckpass: a whole-module compile stops at type errors in about 2 s anyway. - Plugins lazily. The macro plugins load only when a compile expands a macro: it fails with the compiler's "could not be found" error, and the worker then loads them and compiles again. Until then they are only downloaded into the cache, behind the first compile.
- Memory. A phone's browser kills a page well before a desktop's
(Counter crashed an iPhone's Safari during the compile, not an iPad's). A
download goes to the cache and is read back from it, never held twice;
the plugins (three compiled modules of 40 MB) wait for a macro; ICU's
emptied 34 MB member is left out of its archive. Each tool runs in a
worker of its own that loads it and the files it reads from the cache
(the linker the archives and objects, the compiler the rest) and is ended
once it answers, so the compiler's code, memory and modules are gone
before the linker loads; the downloads run in one too, which takes the
brotli decoder's memory with it. The page's worker holds only the small
files. A tool's worker keeps each input once (a WASI file would copy
it), and the linker's drops each archive once the linker has read it
whole (it keeps its own copy), but those the link names twice, which it
reads again. A compile also unloads the last build's app from the
frame, which shows a still copy of it meanwhile: its document without
scripts, inert. The tools and plugins are cached without their custom sections:
the names are a quarter of the compiler and the linker. The app is
linked without DWARF (
--strip-debug), as the CLI's release builds are: 37 MB instead of 48 for the frame to compile. Chromium's renderer peaked at 1.7 GB for Counter's first compile before these, about 0.9 GB after. The status line shows each tool's linear memory: the frontend takes 123 MB and the linker 366 MB, much of it the inputs it reads whole.
Running it: the page is in the site built with SB_PLAYGROUND=1, and
fetches the packages at the repository's version (SB_PLAYGROUND_VERSION
for another) from jsDelivr. Before a release publishes them, point it at
the dev server's copy of the workspaces' packages, filled:
node packages/wasm-tools/fetch.mjs # the tools (R2 credentials)
node packages/wasm-sdk/pack-sdk.mjs --from <the Swift SDK's wasm32-unknown-wasip1 directory>
node packages/kit/pack-kit.mjs --from <a kit, ~/.cache/swiftbrowser/kits/...>
npm run playground:assets --workspace @swiftbrowser/web # fills packages/playground
cd Web && SB_PLAYGROUND=1 SB_PLAYGROUND_NPM=/npm/ npm run dev # then open /playground/
The release fills and publishes @swiftbrowser/playground with the others
(.github/workflows/publish.yml), and CI's examples job runs the page in
Chromium on its packages (.github/workflows/wasm-compiler.yml).
The kit matches the renderer. The kit is the Swift half of the
renderer's protocol, so a page must not run a kit built from other sources
than its own JavaScript. A release's site reads every package at the
release's version, kit included. A site built from main serves the kit
and @swiftbrowser/playground itself, built from the same commit by CI's
playground job, and fetches only the compiler and SDK from npm: they
change with Swift, not with this repository. SB_PLAYGROUND_LOCAL has a site
build do that (Web/plugins/playground.ts): it copies the files the page
reads of those packages to /npm/<package>@site-<hash>/, laid out as
jsDelivr serves them, and any package Web/playground/site-packages.mjs
finds npm lacking at that version (the SDK before the first release that
publishes it). A file over Cloudflare Pages' 25 MiB goes in
brotli-compressed as <file>.brotli (not .br, which a static server may
send as Content-Encoding: br), and the site's playground.json names it.
When the compiler on npm is not the commit's, the site goes without the
page. As a last guard, playground.json records the sources the kit was
built from (sourcesHash, checked against the kit's id), the site build the
sources its renderer was, and the page warns when they differ.
Still to do: Safari and Firefox.
- Loading. The compiler module is fetched compressed, compiled with
WebAssembly.compileStreamingand kept in the Cache API, so the one-time cost is paid once per browser. The SDK's files are fetched by the manifest, lazily where possible (Foundation's full variant only when an app imports what needs it) and persisted in the origin-private file system or IndexedDB. Everything the CLI'skit.tsandstage.tsdecide about what an app needs is reused. - Running. The compiler runs in a Web Worker with the in-memory WASI backend from 1.5. One instance per worker, warm, reused across compiles; a compile that crashes the instance re-instantiates it. Cross-origin isolation headers only if threads are ever turned on, which the plan avoids.
- Memory. A 32-bit memory grows to the limit the engine allows, which is plenty: 1.1 measured a few hundred megabytes for a whole app.
- Output. The linked app is the same WASI command
swiftbrowser devproduces, minuswasm-opt, soWeb/src/wasm.tsand the renderer run it unchanged, and the@Statesnapshot the dev server restores on a rebuild restores here too. - Diagnostics. A
-typecheckpass first, so errors come back before codegen runs, mapped to the editor's lines with the existing remapping.
The CLI's default compiler#
The same compiler makes Swift optional for the CLI. --compiler (or
SWIFTBROWSER_COMPILER) picks (packages/cli/src/compiler.ts): auto, the
default, takes the toolchain when it is installed, as it builds faster, and
the WebAssembly compiler otherwise, saying why; native and wasm take one
or say what is missing.
Done so far, all without a Swift install:
- The SDK.
swiftbrowser doctor --installlays the Swift SDK for WebAssembly out in the CLI's cache when there is no toolchain to install it (src/wasmSdk.ts), from npm packages that carry the files the compiler reads, split by who needs them (src/sdkPackages.ts: the sysroot and standard library, Foundation, ICU's code and its data, testing, C++; 51 MB to download against swift.org's 93 MB bundle, which a CLI whose version has no packages falls back to). ICU's 34 MB data member is left out of its archive and carried as its own file, which the CLI trims per app; the compiler reads the rest from there. - The kit. The released kit (@swiftbrowser/kit) is checked by type-checking an import of every module with the WebAssembly frontend, so it works on any host. Kits are named by the Swift version both compilers report, so the two share one.
- Macros. The kit carries its macros built as WebAssembly
(
wasm-plugins/), from the same sources as its modules: the release builds them (swiftbrowser kit --wasm-macros), and a kit made here gets them on its first WebAssembly build. A native toolchain runs the same files: the CLI writes a script per macro that runs it under Node through @swiftbrowser/wasm-compiler'splugin-executable(the native compiler's stdin/stdout plugin protocol, framed as the WebAssembly host frames it), and names the script as the macro's plugin executable, so no per-host packages are needed. The toolchain's ObservationMacros and SwiftMacros (the standard library's@TaskLocal,@OptionSet...) come from @swiftbrowser/wasm-tools. - Packages. Resolved with git, without SwiftPM (
src/resolve.ts): the highest version every requirement allows,Package.resolvedpins honoured, only the packages the app's products need; it picks the versions SwiftPM picks on the packages tried (TCA, swift-algorithms, SDWebImageSwiftUI: 18 packages). Manifests are compiled and run by the WebAssembly tools against SwiftPM's PackageDescription built for WebAssembly, shipped in @swiftbrowser/wasm-tools (manifest-api/), and read asdump-packagedescribes them (src/manifest.ts); results are cached by the manifest's text. Both packages copied for the shim and plain Swift packages build; a target with resources getsBundle.module, falling back to the app's bundle as with the native build. C targets compile with clang built as WebAssembly, shipped in @swiftbrowser/wasm-tools, with SwiftPM's flags and module maps (src/wasmPackages.ts); package traits and the conditions that name them are followed. The package fixtures (local packages, Nuke, Gifu, WrappingHStack, RevenueCat's SDK) pass CI's native checks this way, and Ice Cubes builds (about 30 packages, swift-cmark and SQLite in C; 20 minutes on a 4-core machine) and runs headless. - Compiler fixes. Two bugs the native compiler does not show, found on
Ice Cubes, are patched in
toolchain/patches/swift: anya !== bbetween class references aborted an optimized build (SimplifyBuiltin's negation of a pointer comparison), and an assertion only an assertions build makes (a local discriminator set twice) stopped a package. checktype-checks against the kit with the WebAssembly frontend.testbuilds what SwiftPM's debug--build-testsdoes: the app as a testable module whose entry point is renamed (<App>_main), each test target against it, and a runner that is the program's entry point (src/testDiscovery.ts). XCTest's tests are listed from the test module's symbol graph (-emit-symbol-graph) where SwiftPM reads its index store; Swift Testing finds its own as it runs. swift-testing's macros (@Test,#expect) come as a WebAssembly plugin in @swiftbrowser/wasm-tools. The init app's test builds in 25 s cold and 13 s warm (SwiftPM: 51 s).- Publishing. @swiftbrowser/wasm-compiler is published with the other packages and is a dependency of the CLI.
- CI (
.github/workflows/wasm-compiler.yml) builds every example from the kit on a runner with Swift removed and compares each with its snapshot, HotProspects and its package included, builds and runs apps with plain and copied packages there, and runs an app's tests.
Still needing the toolchain: building a kit for an edited shim (contributors only). A package target compiles as one job, where SwiftPM splits it across cores: RevenueCat's SDK takes about 6 minutes on a 4-core machine.
dev speed. A rebuild on save, the number that decides whether auto
can be the default, measured on a 4-core machine (a dev session's second
and third builds; native is SwiftPM's release rebuild against the kit):
| App | Native | WebAssembly compiler, before | Now |
|---|---|---|---|
| Counter, 3 files | 5.2 s | 11.4 s | 5.0–5.9 s |
| Settings, 3 files | 6.5 s | 14.2 s | 7.5–8.3 s |
| Todos, SwiftData | 7.1–7.2 s | ||
| HackingWithSwift, 16 files | 8.6 s | 24.4 s | 13.1 s |
| FoodTruck, 57 files | 26–28 s |
Two changes made the difference. The compiled tools are kept for the
process (packages/wasm-compiler/src/node/wasi-host.ts), so a rebuild runs
code V8 has already optimized: in one process a second compile takes about
two thirds of the first, a second link a third. And dev compiles
unoptimized (-Onone, no DEBUG define; build stays -O), about a third
faster; every example's unoptimized module gives the same op stream. What
did not help: one frontend job per file (each re-type-checks the module:
26 s for HackingWithSwift on 4 workers, against 10 s for one job), and
prelinking the kit with wasm-ld -r (2.8 to 2.4 s a link). Left: the
frontend is still about twice native on bigger apps. The published
compiler is built without assertions since release swift-6.4.0-r9: 5-15%
faster than with them (which -sil-verify-none had already narrowed) and
9 MB smaller, with every example's code the same as the assertions build
made (swift-6.4.0-r8, kept in R2 for a compiler crash's diagnostics).
Milestone 4: the playground#
The product on top: an editor, the examples as starting points, an Xcode
project dropped onto the page and read by @swiftbrowser/xcodeproj, the
import report before the first compile, sharing a playground as a URL.
Nothing here is compiler work and it is not planned in this document.
Later#
- Dynamic linking. Prelink the kit and the stdlib once into a shared module, and link only the app's objects per edit, which is the swiftwasm-pad shape. It needs position-independent code for the kit and the WASI dynamic-linking conventions, which SwiftWasm supports only experimentally. Worth it when Milestone 2's link times say so, and the point at which a TypeScript linker pays for itself.
- Incremental compilation. The frontend's own incremental mode needs a persisted build record and per-file dependency graphs, both files the virtual file system can keep between compiles.
- Native platforms through the same path. A compiler running under
Node needs no toolchain install, so
swiftbrowser checkcould use it on a machine with no Swift, at the cost of speed.
Risks and how each is retired#
| Risk | What would make it real | Retired by |
|---|---|---|
| The frontend does not fit in a 32-bit memory on real apps | Peak memory over about 3 GB on the examples | Retired by 1.1: about 250 MB at most natively |
| The compiler's Swift parts cannot be cross-compiled to a Wasm host | Bootstrapping or swift-syntax needs a feature SwiftWasm lacks | Retired by 1.3 for SwiftCompilerSources, cross-compiled with C++ interop; swift-syntax is still off and comes back with Milestone 2's macros |
| Compiles are too slow to feel like a playground | Several times native, on a single thread | 1.1's native numbers set the bound; Milestone 1 measured hello world at about 1.4 s in the frontend and 0.6 s in wasm-ld under Node, mostly V8 compiling the modules; -Onone, the -typecheck first pass, skipping wasm-opt, caching compiled modules, dynamic linking |
| Download size | A compiler over about 60 MB compressed | Milestone 1's tools, stripped and without assertions: 21.5 MB brotli for the frontend, 7.8 MB for wasm-ld; hello world opens 47 MB of the SDK. Then Cache API and lazy SDK files; wasm-opt barely helps once compressed |
| PCMs invalidate on every compile | ClangImporter rebuilding its cache each run | Fixed paths and timestamps in the virtual file system; identical flags |
| Deep recursion overflows the Wasm stack | A crash in Sema on an expression a native build handles | -z stack-size; the compiler on its own worker |
| The port drifts from upstream | A patch set that cannot be rebased on the next Swift release | Keep the port as a CMake host configuration plus small WASI guards in the style LLVM already carries for Emscripten; upstream what is general |
Decisions#
- Versions are pinned together: Swift 6.4.0 (the CLI's
SWIFT_VERSION), its Swift SDK for Wasm by checksum, itsllvm-projecttag, swift-syntax- The compiler module, the SDK manifest and the kit carry the same version string and refuse to mix.
- The frontend is invoked directly. No driver, no SwiftPM in the browser; the TypeScript driver is the only thing that knows the argument lists.
- Static linking first. A full link per compile, with
wasm-ldas Wasm. Dynamic linking only with numbers that ask for it. - One host layer, two backends. Node WASI for the CLI and tests, the in-memory shim for the browser. Nothing above the layer knows which.
- No threads in the compiler. Simpler build, no isolation headers, and the frontend is mostly single-threaded anyway.
- TypeScript owns the edges, Wasm owns the middle. Anything that shuffles arguments, files or messages is TypeScript; anything that understands Swift is the ported compiler.
Open questions#
How the frontend's Wasm macro support expects a plugin to be loaded, and whether its loader can be pointed at a host import.Settled: a plugin built for WASI exportsswift_wasm_macro_v1_pump, and the compiler's executable-plugin pipe becomes four host imports (Milestone 2's status).The compiler's licence and attribution requirements for shipping it as a download.Settled:packages/wasm-tools/LICENSE.txtcarries the licenses of Swift, the LLVM Project, swift-cmark and wasi-libc, which the modules contain.