diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index a60b306fc..537a17aa7 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -5,6 +5,7 @@ pub(crate) mod cmake; mod dotnet; +mod swiftpm; mod zig; use crate::RunConfig; @@ -84,6 +85,7 @@ pub(crate) fn detect_with_profiles( } } detect_projects(root, &["build.zig"], zig::detect, &mut out); + detect_projects(root, &["Package.swift"], swiftpm::detect, &mut out); // A UE project's `.sln` lists the engine's own tool projects; expanding it would bury the // run menu under dozens of `.NET Project` entries that cannot run from here. if !ide_workspace::unreal::is_project(root) { diff --git a/crates/ide-run/src/detect/swiftpm.rs b/crates/ide-run/src/detect/swiftpm.rs new file mode 100644 index 000000000..a026844fa --- /dev/null +++ b/crates/ide-run/src/detect/swiftpm.rs @@ -0,0 +1,116 @@ +//! Swift packages (`Package.swift`): one `swift run ` per executable product, built +//! first by `swift build --product ` and debuggable with lldb-dap on the built +//! `.build/debug/`. Read from the manifest's source: `swift package describe` would +//! compile and run the manifest, and detection never runs the project's build code. + +use super::zig::{call_body, code_only, string_at}; +use super::{ConfigExt, config, read}; +use crate::{BeforeLaunchTask, RunConfig}; +use std::path::Path; + +pub(super) fn detect(dir: &Path, out: &mut Vec) { + let Some(src) = read(&dir.join("Package.swift")) else { return }; + for product in executables(&code_only(&src), dir) { + let mut c = config( + format!("swiftpm:run:{product}"), + format!("swift run {product}"), + "swiftpm", + "swift", + &["run", "--skip-build", &product], + ) + .debug("lldb-dap"); + c.extras + .before_launch + .push(BeforeLaunchTask { kind: "command".into(), target: format!("swift build --product {product}") }); + let exe = if cfg!(windows) { ".exe" } else { "" }; + c.extras.params.insert("program".into(), format!(".build/debug/{product}{exe}")); + c.extras.params.insert("product".into(), product); + out.push(c); + } +} + +/// The body of each `(` in `src`, from just after its `(` to the matching `)`. +fn bodies<'a>(src: &'a str, call: &'a str) -> impl Iterator + 'a { + src.match_indices(call).map(move |(i, _)| call_body(src, i + call.len())) +} + +/// The call's first argument, `name: "…"`. +fn name(body: &str) -> Option { + string_at(body.trim_start().strip_prefix("name:")?).filter(|n| !n.is_empty()) +} + +/// The string literals of a call's `targets: [ … ]` argument. +fn targets(body: &str) -> Vec { + let Some(at) = body.find("targets:") else { return Vec::new() }; + let Some(list) = body[at + "targets:".len()..].trim_start().strip_prefix('[') else { return Vec::new() }; + let list = &list[..list.find(']').unwrap_or(list.len())]; + list.split(',').filter_map(string_at).collect() +} + +/// Declared `.executable` products, then executable targets no declared product builds: +/// SwiftPM gives each of those a product of its own name. A `.target` with a `main.swift` +/// (tools before 5.4) is an executable target too. +fn executables(src: &str, dir: &Path) -> Vec { + let mut out: Vec = Vec::new(); + let mut built: Vec = Vec::new(); + for body in bodies(src, ".executable(") { + built.extend(targets(body)); + out.extend(name(body).filter(|n| !out.contains(n))); + } + let legacy = + bodies(src, ".target(").filter_map(name).filter(|n| dir.join("Sources").join(n).join("main.swift").is_file()); + for target in bodies(src, ".executableTarget(").filter_map(name).chain(legacy) { + if !built.contains(&target) && !out.contains(&target) { + out.push(target); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const MANIFEST: &str = r#"// swift-tools-version:5.9 +import PackageDescription + +let package = Package( + name: "Greeter", + products: [ + .executable(name: "greet", targets: ["Greet"]), + .library(name: "GreeterKit", targets: ["GreeterKit"]), + // .executable(name: "commented-out", targets: ["Old"]), + ], + targets: [ + .executableTarget(name: "Greet", dependencies: ["GreeterKit"]), + .executableTarget( + name: "tool" + ), + .target(name: "GreeterKit"), + .target(name: "Legacy"), + .testTarget(name: "GreeterKitTests", dependencies: ["GreeterKit"]), + ] +) +"#; + + #[test] + fn a_swift_package_gets_one_run_configuration_per_executable_product() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Package.swift"), MANIFEST).unwrap(); + for target in ["GreeterKit", "Legacy"] { + std::fs::create_dir_all(dir.path().join("Sources").join(target)).unwrap(); + } + std::fs::write(dir.path().join("Sources/Legacy/main.swift"), "print(1)").unwrap(); + let mut out = Vec::new(); + detect(dir.path(), &mut out); + let ids: Vec<_> = out.iter().map(|c| c.id.as_str()).collect(); + assert_eq!(ids, ["swiftpm:run:greet", "swiftpm:run:tool", "swiftpm:run:Legacy"]); + let greet = &out[0]; + assert_eq!((greet.command.as_str(), greet.args.join(" ").as_str()), ("swift", "run --skip-build greet")); + assert_eq!(greet.debug_adapter.as_deref(), Some("lldb-dap")); + assert_eq!(greet.extras.before_launch[0].kind, "command"); + assert_eq!(greet.extras.before_launch[0].target, "swift build --product greet"); + let program = greet.extras.params.get("program").unwrap(); + assert!(program.starts_with(".build/debug/greet")); + } +} diff --git a/crates/ide-run/src/detect/zig.rs b/crates/ide-run/src/detect/zig.rs index c20b4c3b8..41b23c40b 100644 --- a/crates/ide-run/src/detect/zig.rs +++ b/crates/ide-run/src/detect/zig.rs @@ -50,7 +50,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec) { } /// `src` with comments blanked out (Zig has only `//` comments) and string contents kept. -fn code_only(src: &str) -> String { +pub(super) fn code_only(src: &str) -> String { let mut out = String::with_capacity(src.len()); for line in src.lines() { let mut in_string = false; @@ -79,7 +79,7 @@ fn code_only(src: &str) -> String { } /// The string literal starting at `s` (after optional whitespace), unescaped only for `\"`. -fn string_at(s: &str) -> Option { +pub(super) fn string_at(s: &str) -> Option { let rest = s.trim_start().strip_prefix('"')?; let mut value = String::new(); let mut chars = rest.chars(); @@ -274,7 +274,7 @@ fn run_step_exes(src: &str) -> Vec<(String, String)> { } /// The call's argument text: from just after its `(` to the matching `)`. -fn call_body(src: &str, start: usize) -> &str { +pub(super) fn call_body(src: &str, start: usize) -> &str { let (mut depth, mut in_string, mut escaped) = (1usize, false, false); for (i, c) in src[start..].char_indices() { if in_string { diff --git a/src/features/debugger/__tests__/launch.test.ts b/src/features/debugger/__tests__/launch.test.ts index 818b6a3e0..d407c7d5b 100644 --- a/src/features/debugger/__tests__/launch.test.ts +++ b/src/features/debugger/__tests__/launch.test.ts @@ -557,6 +557,22 @@ describe("run config → launch config", () => { expect(gdb.extraJson).toBeNull(); }); + it("swift run under lldb-dap debugs the built product with the arguments after it", () => { + const run = rc({ + kind: "swiftpm", + command: "swift", + args: ["run", "--skip-build", "greet", "--loud"], + cwd: "pkg", + debugAdapter: "lldb-dap", + params: { product: "greet", program: ".build/debug/greet" }, + }); + expect(launchConfigFor(run, "/p")).toMatchObject({ + program: "/p/pkg/.build/debug/greet", + args: ["--loud"], + cwd: "/p/pkg", + }); + }); + it.each(["native", "cmake-application"])( "maps %s CMake debug-info paths to the editor's canonical source root", (kind) => { diff --git a/src/features/debugger/launch.ts b/src/features/debugger/launch.ts index bf5dc34f9..4d6326f8e 100644 --- a/src/features/debugger/launch.ts +++ b/src/features/debugger/launch.ts @@ -398,6 +398,11 @@ function godotLaunch(rc: RunConfig, cwd: string): LaunchConfig { /** A native program under CodeLLDB, lldb-dap or GDB: program, args, cwd, env. */ function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig { const out: LaunchConfig = { ...base(rc, adapter, cwd), program: resolveCommand(rc.command, cwd), args: [...rc.args] }; + // `swift run `: debug the product its before launch build left behind. + if (rc.kind === "swiftpm" && rc.params?.program && rc.params.product) { + out.program = join(cwd, rc.params.program); + out.args = rc.args.slice(rc.args.indexOf(rc.params.product) + 1); + } // lldb-dap takes the environment as `KEY=VALUE` strings. if (adapter === "lldb-dap") { const from = rc.params?.cmakeSourceRoot; diff --git a/src/features/run/configs.ts b/src/features/run/configs.ts index ea1b60e67..b964b3e57 100644 --- a/src/features/run/configs.ts +++ b/src/features/run/configs.ts @@ -166,6 +166,7 @@ export function configIcon(config: Pick): string { case "r": return "file-r"; case "swift": + case "swiftpm": return "file-swift"; case "dart": return "file-dart";