feat(run): detect SwiftPM executable products as run configurations (#6792)

A Swift package now gets one run configuration per executable product, read from the manifest source without running it: declared .executable products plus executable targets no product builds (and legacy targets with main.swift). Each runs swift run --skip-build <product> after a swift build --product <product> before-launch task, and Debug launches .build/debug/<product> under lldb-dap with the configured arguments.

Closes #6786

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 14:39:13 +08:00
1 джерело f2641b9697
коміт 77e669c189
6 files changed
+143 -3

No files matched your search

+2
Переглянути файл
@@ -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) {
+116
Переглянути файл
@@ -0,0 +1,116 @@
//! Swift packages (`Package.swift`): one `swift run <product>` per executable product, built
//! first by `swift build --product <product>` and debuggable with lldb-dap on the built
//! `.build/debug/<product>`. 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<RunConfig>) {
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 `<call>(` in `src`, from just after its `(` to the matching `)`.
fn bodies<'a>(src: &'a str, call: &'a str) -> impl Iterator<Item = &'a str> + '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> {
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<String> {
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<String> {
let mut out: Vec<String> = Vec::new();
let mut built: Vec<String> = 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"));
}
}
+3 -3
Переглянути файл
@@ -50,7 +50,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
}
/// `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<String> {
pub(super) fn string_at(s: &str) -> Option<String> {
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 {
+16
Переглянути файл
@@ -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) => {
+5
Переглянути файл
@@ -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 <product> <args…>`: 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;
+1
Переглянути файл
@@ -166,6 +166,7 @@ export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {
case "r":
return "file-r";
case "swift":
case "swiftpm":
return "file-swift";
case "dart":
return "file-dart";