Skip to main content

ferrokit_build/
lib.rs

1//! Compiles a Mac app's Swift code from `build.rs` and links it into the
2//! app, so Rust can call Swift (and SwiftUI) through `@_cdecl` functions.
3//!
4//! ```no_run
5//! // build.rs
6//! fn main() {
7//!     ferrokit_build::swift("swift").compile();
8//! }
9//! ```
10//!
11//! ```toml
12//! # Cargo.toml
13//! [build-dependencies]
14//! ferrokit-build = "0.15"
15//! ```
16//!
17//! Every `.swift` file under the folder (here `swift/`, next to
18//! `Cargo.toml`) is compiled by `swiftc` into one static library, which is
19//! linked into the package's binaries. The Swift runtime, SwiftUI and the
20//! rest of Apple's frameworks come with macOS, so nothing is copied into the
21//! app; the frameworks the Swift code imports are linked automatically.
22//! `swiftc` comes with the Command Line Tools (`xcode-select --install`),
23//! which a Rust build on a Mac needs anyway. SwiftUI's macros (`@State`,
24//! `@Entry`, `#Preview`: macros since the macOS 27 SDK) need Xcode, whose
25//! plugin expands them: when the Command Line Tools are selected and an
26//! Xcode is in `/Applications`, it's used for the Swift (with a warning).
27//! Setting `DEVELOPER_DIR` picks the toolchain yourself, and turns that
28//! fallback off.
29//!
30//! On the Swift side, export functions with C names; on the Rust side,
31//! declare them in an `extern "C"` block:
32//!
33//! ```swift
34//! // swift/Greeting.swift
35//! @_cdecl("greeting_length")
36//! public func greetingLength(_ name: UnsafePointer<CChar>) -> Int {
37//!     "Hello, \(String(cString: name))!".count
38//! }
39//! ```
40//!
41//! ```no_run
42//! unsafe extern "C" {
43//!     fn greeting_length(name: *const std::ffi::c_char) -> isize;
44//! }
45//! // SAFETY: a NUL-terminated string.
46//! let n = unsafe { greeting_length(c"Ferrokit".as_ptr()) };
47//! ```
48//!
49//! A SwiftUI view goes into a Ferrokit window through `ferrokit::native`: a
50//! Swift function returns an `NSHostingView` (`Unmanaged.passRetained(view)
51//! .toOpaque()`), and `native(|_| unsafe { Retained::from_raw(ptr.cast()) }
52//! .unwrap())` wraps it. Ferrokit's guide, chapter 14, has the whole recipe.
53//!
54//! The settings follow the build: the target's architecture (so universal
55//! builds work), optimisation and debug info from the Cargo profile, and the
56//! minimum macOS from `MACOSX_DEPLOYMENT_TARGET`, else 15.0.
57//!
58//! Put the Swift code in the package that builds the app (its binary or
59//! example): the link settings Cargo passes from a build script reach that
60//! package's own binaries only.
61
62#![warn(missing_docs)]
63// The examples are build scripts, where `fn main` is the point.
64#![allow(clippy::needless_doctest_main)]
65
66use std::env;
67use std::fmt;
68use std::path::{Path, PathBuf};
69use std::process::Command;
70
71/// Swift code to compile: the `.swift` files under `dir` (relative to the
72/// package's `Cargo.toml`). Set options, then call
73/// [`compile`](Swift::compile).
74pub fn swift(dir: impl AsRef<Path>) -> Swift {
75    Swift { dir: dir.as_ref().to_path_buf(), module: None, min_macos: None, swift_version: None, flags: Vec::new() }
76}
77
78/// Swift code to compile into the package (see [`swift`]).
79#[derive(Debug, Clone)]
80pub struct Swift {
81    dir: PathBuf,
82    module: Option<String>,
83    min_macos: Option<String>,
84    swift_version: Option<String>,
85    flags: Vec<String>,
86}
87
88/// Why the Swift code couldn't be compiled.
89#[derive(Debug)]
90pub enum Error {
91    /// Not building for macOS.
92    NotMacos(String),
93    /// The folder has no `.swift` files (or doesn't exist).
94    NoSources(PathBuf),
95    /// `xcrun` or `swiftc` couldn't be run.
96    NoToolchain(String),
97    /// `swiftc` reported errors (they're above, in the build output).
98    Compile,
99    /// The Swift uses SwiftUI's macros (`@State`, `@Entry`, `#Preview`),
100    /// which need Xcode: the Command Line Tools don't have their plugin.
101    NeedsXcode,
102    /// A Cargo variable a build script gets is missing (not run by Cargo).
103    NotInBuildScript(&'static str),
104}
105
106impl fmt::Display for Error {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Error::NotMacos(os) => write!(f, "ferrokit-build compiles Swift for macOS only (the target's OS is {os})"),
110            Error::NoSources(dir) => write!(f, "no .swift files in {}", dir.display()),
111            Error::NoToolchain(why) => write!(f, "couldn't run swiftc ({why}); install the Command Line Tools with `xcode-select --install`, or Xcode"),
112            Error::Compile => write!(f, "swiftc failed; its errors are above"),
113            Error::NeedsXcode => write!(f, "this Swift uses SwiftUI's macros (@State, @Entry, #Preview), which the Command Line Tools can't expand: install Xcode (it's found in /Applications), or set DEVELOPER_DIR to one"),
114            Error::NotInBuildScript(var) => write!(f, "{var} isn't set: call ferrokit-build from a build script (build.rs)"),
115        }
116    }
117}
118
119impl std::error::Error for Error {}
120
121impl Swift {
122    /// The Swift module's name, which Swift code in other modules would
123    /// `import`. By default the package's name in UpperCamelCase
124    /// (`my-app` → `MyApp`).
125    pub fn module(mut self, name: &str) -> Self {
126        self.module = Some(name.to_string());
127        self
128    }
129
130    /// The oldest macOS the Swift code is compiled for, such as `"15.0"`.
131    /// By default `MACOSX_DEPLOYMENT_TARGET`, else 15.0 (Ferrokit's
132    /// minimum).
133    pub fn min_macos(mut self, version: &str) -> Self {
134        self.min_macos = Some(version.to_string());
135        self
136    }
137
138    /// The Swift language mode (`"5"` or `"6"`); by default `swiftc`'s
139    /// own.
140    pub fn swift_version(mut self, version: &str) -> Self {
141        self.swift_version = Some(version.to_string());
142        self
143    }
144
145    /// Passes `flag` to `swiftc` as it is (`"-warnings-as-errors"`, `"-D"`
146    /// and `"FEATURE"` as two flags…).
147    pub fn flag(mut self, flag: &str) -> Self {
148        self.flags.push(flag.to_string());
149        self
150    }
151
152    /// Compiles the Swift code and links it into the package, or stops the
153    /// build with what went wrong (`swiftc`'s errors are in the build
154    /// output).
155    pub fn compile(self) {
156        if let Err(e) = self.try_compile() {
157            panic!("{e}");
158        }
159    }
160
161    /// [`compile`](Self::compile), returning the error instead of stopping
162    /// the build. On success, the static library's path.
163    pub fn try_compile(self) -> Result<PathBuf, Error> {
164        let var = |name: &'static str| env::var(name).map_err(|_| Error::NotInBuildScript(name));
165        let os = var("CARGO_CFG_TARGET_OS")?;
166        if os != "macos" {
167            return Err(Error::NotMacos(os));
168        }
169        let manifest = PathBuf::from(var("CARGO_MANIFEST_DIR")?);
170        let out = PathBuf::from(var("OUT_DIR")?);
171        let dir = manifest.join(&self.dir);
172        let sources = sources(&dir);
173        // Watched before anything can fail, so adding the first file reruns.
174        println!("cargo:rerun-if-changed={}", dir.display());
175        for s in &sources {
176            println!("cargo:rerun-if-changed={}", s.display());
177        }
178        println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");
179        println!("cargo:rerun-if-env-changed=DEVELOPER_DIR");
180        if sources.is_empty() {
181            return Err(Error::NoSources(dir));
182        }
183
184        let arch = match var("CARGO_CFG_TARGET_ARCH")?.as_str() {
185            "aarch64" => "arm64".to_string(),
186            other => other.to_string(),
187        };
188        let min = self.min_macos.clone().or_else(|| env::var("MACOSX_DEPLOYMENT_TARGET").ok()).unwrap_or_else(|| "15.0".into());
189        let module = self.module.clone().unwrap_or_else(|| module_name(&env::var("CARGO_PKG_NAME").unwrap_or_default()));
190        let lib = out.join("libferrokit_swift.a");
191        let opt = env::var("OPT_LEVEL").unwrap_or_default();
192        let debug_info = !matches!(env::var("DEBUG").as_deref(), Ok("false" | "0" | "none") | Err(_));
193        let compile = |developer: Option<&Path>| -> Result<(String, PathBuf, std::process::Output), Error> {
194            let sdk = xcrun(developer, &["--sdk", "macosx", "--show-sdk-path"])?;
195            let swiftc = PathBuf::from(xcrun(developer, &["--find", "swiftc"])?);
196            let mut cmd = Command::new(&swiftc);
197            if let Some(d) = developer {
198                cmd.env("DEVELOPER_DIR", d);
199            }
200            cmd.args(["-emit-library", "-static", "-parse-as-library"])
201                .args(["-module-name", &module])
202                .args(["-target", &format!("{arch}-apple-macos{min}")])
203                .arg("-sdk")
204                .arg(&sdk)
205                .arg("-module-cache-path")
206                .arg(out.join("swift-module-cache"))
207                .arg(if opt == "0" { "-Onone" } else { "-O" });
208            if debug_info {
209                cmd.arg("-g");
210            }
211            if let Some(v) = &self.swift_version {
212                cmd.args(["-swift-version", v]);
213            }
214            cmd.args(&self.flags).arg("-o").arg(&lib).args(&sources);
215            let output = cmd.output().map_err(|e| Error::NoToolchain(format!("{}: {e}", swiftc.display())))?;
216            Ok((sdk, swiftc, output))
217        };
218
219        let (mut sdk, mut swiftc, mut output) = compile(None)?;
220        // The Command Line Tools have no SwiftUI macro plugin, and in the
221        // macOS 27 SDK `@State`, `@Entry` and `#Preview` are macros: use an
222        // installed Xcode for them (unless DEVELOPER_DIR chose a toolchain).
223        if !output.status.success() && needs_macro_plugin(&output.stderr) && env::var_os("DEVELOPER_DIR").is_none() {
224            match installed_xcode() {
225                Some(xcode) => {
226                    println!("cargo:warning=the selected developer tools can't expand SwiftUI's macros (@State…); compiling the Swift with {}", xcode.display());
227                    (sdk, swiftc, output) = compile(Some(&xcode))?;
228                }
229                None => {
230                    eprint!("{}", String::from_utf8_lossy(&output.stderr));
231                    return Err(Error::NeedsXcode);
232                }
233            }
234        }
235        if !output.status.success() {
236            eprint!("{}", String::from_utf8_lossy(&output.stderr));
237            return Err(Error::Compile);
238        }
239        // Swift's warnings, shown by Cargo (a build script's own output is
240        // shown only when it fails).
241        for line in String::from_utf8_lossy(&output.stderr).lines().filter(|l| l.contains(": warning: ")) {
242            println!("cargo:warning={line}");
243        }
244
245        println!("cargo:rustc-link-search=native={}", out.display());
246        println!("cargo:rustc-link-lib=static=ferrokit_swift");
247        // The runtime's link stubs; the libraries themselves are in the OS.
248        println!("cargo:rustc-link-search=native={sdk}/usr/lib/swift");
249        // Compatibility libraries for older targets, in the toolchain.
250        if let Some(toolchain) = swiftc.parent().and_then(Path::parent) {
251            println!("cargo:rustc-link-search=native={}", toolchain.join("lib/swift/macosx").display());
252        }
253        // Some runtime libraries (Swift Concurrency) are linked by @rpath.
254        println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");
255        Ok(lib)
256    }
257}
258
259/// `.swift` files under `dir`, sorted (so builds are repeatable).
260fn sources(dir: &Path) -> Vec<PathBuf> {
261    fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
262        let Ok(entries) = std::fs::read_dir(dir) else { return };
263        for e in entries.flatten() {
264            let p = e.path();
265            if p.is_dir() {
266                walk(&p, out);
267            } else if p.extension().is_some_and(|x| x == "swift") {
268                out.push(p);
269            }
270        }
271    }
272    let mut out = Vec::new();
273    walk(dir, &mut out);
274    out.sort();
275    out
276}
277
278fn xcrun(developer: Option<&Path>, args: &[&str]) -> Result<String, Error> {
279    let mut cmd = Command::new("xcrun");
280    if let Some(d) = developer {
281        cmd.env("DEVELOPER_DIR", d);
282    }
283    let o = cmd.args(args).output().map_err(|e| Error::NoToolchain(format!("xcrun: {e}")))?;
284    if !o.status.success() {
285        return Err(Error::NoToolchain(format!("xcrun {}: {}", args.join(" "), String::from_utf8_lossy(&o.stderr).trim())));
286    }
287    Ok(String::from_utf8_lossy(&o.stdout).trim().to_string())
288}
289
290/// Whether `swiftc` failed for want of a macro plugin (SwiftUI's, with
291/// the Command Line Tools).
292fn needs_macro_plugin(stderr: &[u8]) -> bool {
293    let text = String::from_utf8_lossy(stderr);
294    text.contains("plugin for module") && text.contains("not found")
295}
296
297/// An installed Xcode's developer folder, if it has SwiftUI's macro plugin.
298fn installed_xcode() -> Option<PathBuf> {
299    let mut apps: Vec<PathBuf> = std::fs::read_dir("/Applications")
300        .ok()?
301        .flatten()
302        .map(|e| e.path())
303        .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("Xcode") && n.ends_with(".app")))
304        .collect();
305    // Xcode.app first, then the others by name.
306    apps.sort_by_key(|p| (p.file_name().is_none_or(|n| n != "Xcode.app"), p.clone()));
307    apps.into_iter()
308        .map(|app| app.join("Contents/Developer"))
309        .find(|dev| dev.join("Platforms/MacOSX.platform/Developer/usr/lib/swift/host/plugins/libSwiftUIMacros.dylib").exists())
310}
311
312/// A package name as a Swift module name: `my-app` → `MyApp`, `2d_tools` →
313/// `_2dTools`.
314fn module_name(package: &str) -> String {
315    let mut name: String = package
316        .split(|c: char| !c.is_ascii_alphanumeric())
317        .filter(|p| !p.is_empty())
318        .map(|p| {
319            let mut cs = p.chars();
320            cs.next().map(|c| c.to_ascii_uppercase().to_string() + cs.as_str()).unwrap_or_default()
321        })
322        .collect();
323    if name.is_empty() {
324        name = "App".into();
325    }
326    if name.starts_with(|c: char| c.is_ascii_digit()) {
327        name.insert(0, '_');
328    }
329    name
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn module_names() {
338        assert_eq!(module_name("my-app"), "MyApp");
339        assert_eq!(module_name("sql_browser"), "SqlBrowser");
340        assert_eq!(module_name("2d-tools"), "_2dTools");
341        assert_eq!(module_name("habits"), "Habits");
342        assert_eq!(module_name(""), "App");
343    }
344
345    #[test]
346    fn sources_are_found_in_subfolders_and_sorted() {
347        let dir = env::temp_dir().join(format!("ferrokit-build-test-{}", std::process::id()));
348        std::fs::create_dir_all(dir.join("views")).unwrap();
349        for f in ["b.swift", "a.swift", "notes.txt", "views/c.swift"] {
350            std::fs::write(dir.join(f), "").unwrap();
351        }
352        let names: Vec<String> = sources(&dir).iter().map(|p| p.strip_prefix(&dir).unwrap().display().to_string()).collect();
353        std::fs::remove_dir_all(&dir).unwrap();
354        assert_eq!(names, ["a.swift", "b.swift", "views/c.swift"]);
355    }
356
357    #[test]
358    fn outside_a_build_script_it_says_so() {
359        // Cargo sets this for build scripts only.
360        if env::var("CARGO_CFG_TARGET_OS").is_err() {
361            assert!(matches!(swift("swift").try_compile(), Err(Error::NotInBuildScript(_))));
362        }
363    }
364}