mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
fix(run): debug Zig build steps via the executable config (#4002)
Debug on a detected 'zig build run' configuration said it had no debug adapter: build-step configs only run 'zig build <step>'. Steps that run an executable (addRunArtifact in build.zig) now link to that executable's config, and Debug delegates to it — running its before-launch build and keeping the clicked step as the session's origin. Refs #3260 Co-authored-by: akbar1214 <43771058+akbar1214@users.noreply.github.com>
This commit is contained in:
@@ -13,12 +13,18 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let src = code_only(&src);
|
||||
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
|
||||
let roots = test_roots(&src);
|
||||
let run_exes = run_step_exes(&src);
|
||||
for step in steps(&src) {
|
||||
// `install` is what plain `zig build` runs.
|
||||
if step == "install" || step == "uninstall" {
|
||||
continue;
|
||||
}
|
||||
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
|
||||
// A build step that runs an executable has no debug adapter of its own; point it at the
|
||||
// executable config, which builds first and debugs the installed binary under CodeLLDB.
|
||||
if let Some(exe) = run_exes.iter().find(|(name, _)| name == &step) {
|
||||
c.extras.params.insert("debugTarget".into(), format!("zig:exe:{}", exe.1));
|
||||
}
|
||||
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
|
||||
c = c.test();
|
||||
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
|
||||
@@ -109,52 +115,51 @@ struct Executable {
|
||||
source: Option<String>,
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … .root_source_file = <b>.path("…") … })`: the name at the
|
||||
/// options' top level (an `imports` entry has its own `.name`) and the first root source file.
|
||||
/// `.name` and `.root_source_file` of an `addExecutable` call body (just after its `(`).
|
||||
/// The name is read at the options' top level — an `imports` entry has its own `.name`.
|
||||
fn add_executable_fields(body: &str) -> (Option<String>, Option<String>) {
|
||||
let (mut depth, mut in_string, mut escaped) = (0usize, false, false);
|
||||
let (mut name, mut source) = (None, None);
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'{' | '[' => depth += 1,
|
||||
'}' | ']' => depth -= 1,
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value = |key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 1 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(name, source)
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … })`: the name at the options' top level and the first root source file.
|
||||
fn executables(src: &str) -> Vec<Executable> {
|
||||
let mut out: Vec<Executable> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = &src[start + "addExecutable(".len()..];
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
let mut name = None;
|
||||
let mut source = None;
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value =
|
||||
|key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 2 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (name, source) = add_executable_fields(body);
|
||||
if let Some(name) = name
|
||||
&& !name.is_empty()
|
||||
&& !out.iter().any(|e| e.name == name)
|
||||
@@ -165,6 +170,109 @@ fn executables(src: &str) -> Vec<Executable> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `addExecutable` calls, mapped to the executable's name.
|
||||
fn executable_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (Some(name), Some(var)) = (add_executable_fields(body).0, assigned_var(src, start)) else { continue };
|
||||
if !name.is_empty() && !out.iter().any(|(v, _)| v == var) {
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `b.addRunArtifact(x)` calls, mapped to `x` (an executable or test).
|
||||
fn run_artifact_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addRunArtifact(") {
|
||||
let body = call_body(src, start + "addRunArtifact(".len());
|
||||
let arg: String = body.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
if arg.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(var) = assigned_var(src, start)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), arg));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Step variables assigned from `b.step("name", …)` calls, mapped to the step's name.
|
||||
fn step_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
if let Some(var) = assigned_var(src, i + 1)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The argument of a `.dependOn(&…)` call: `after` starts just past its `&`. Stopping at the
|
||||
/// matching `)` keeps a later `addRunArtifact(` in a different step from being mistaken for this
|
||||
/// step's artifact.
|
||||
fn depend_arg(after: &str) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
for (i, c) in after.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return &after[..i];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// Steps whose `dependOn` runs an executable: `(step name, executable name)`. Both the inline
|
||||
/// (`step.dependOn(&b.addRunArtifact(exe).step)`) and the assigned form
|
||||
/// (`const cmd = b.addRunArtifact(exe); step.dependOn(&cmd.step)`) are handled.
|
||||
fn run_step_exes(src: &str) -> Vec<(String, String)> {
|
||||
let exes = executable_vars(src);
|
||||
let artifacts = run_artifact_vars(src);
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step_var) = receiver_var(src, i + 1) else { continue };
|
||||
let Some((_, name)) = steps.iter().find(|(v, _)| v == step_var) else { continue };
|
||||
let arg = depend_arg(&src[i + ".dependOn(&".len()..]);
|
||||
let exe_var = if let Some(at) = arg.find("addRunArtifact(") {
|
||||
let v = &arg[at + "addRunArtifact(".len()..];
|
||||
v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>()
|
||||
} else {
|
||||
let v: String = arg.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
artifacts.iter().find(|(var, _)| var == &v).map(|(_, exe)| exe.clone()).unwrap_or_default()
|
||||
};
|
||||
if let Some((_, exe_name)) = exes.iter().find(|(var, _)| var == &exe_var)
|
||||
&& !out.iter().any(|(n, _)| n == name)
|
||||
{
|
||||
out.push((name.clone(), exe_name.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The call's argument text: from just after its `(` to the matching `)`.
|
||||
fn call_body(src: &str, start: usize) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
@@ -255,14 +363,7 @@ fn test_roots(src: &str) -> Vec<(String, String)> {
|
||||
tests.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
// The match includes the dot, so the assignment ends one character earlier.
|
||||
if let Some(var) = assigned_var(src, i + 1) {
|
||||
steps.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step) = receiver_var(src, i + 1) else { continue };
|
||||
@@ -325,6 +426,7 @@ pub fn build(b: *std.Build) void {
|
||||
}) });
|
||||
_ = tool;
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&b.addRunArtifact(exe).step);
|
||||
const tests = b.addTest(.{ .root_module = mod });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
@@ -358,6 +460,11 @@ pub fn build(b: *std.Build) void {
|
||||
(test.command.as_str(), test.args.as_slice()),
|
||||
("zig", ["build".to_owned(), "test".to_owned()].as_slice())
|
||||
);
|
||||
// The run step has no adapter of its own, but points at the executable config that does.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.debug_adapter, None);
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
assert!(!out.iter().find(|c| c.id == "zig:docs").unwrap().extras.params.contains_key("debugTarget"));
|
||||
let app = out.iter().find(|c| c.id == "zig:exe:app").unwrap();
|
||||
assert_eq!(app.kind, "zig-application");
|
||||
assert!(app.command.ends_with(if cfg!(windows) { "app.exe" } else { "zig-out/bin/app" }));
|
||||
@@ -400,4 +507,36 @@ pub fn build(b: *std.Build) void {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
const ASSIGNED_RUN: &str = r#"const std = @import("std");
|
||||
pub fn build(b: *std.Build) void {
|
||||
const exe = b.addExecutable(.{ .name = "app", .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
}) });
|
||||
b.installArtifact(exe);
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
const tests = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/tally.zig"),
|
||||
}) });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn a_run_step_linked_through_an_assigned_command_finds_its_executable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("build.zig"), ASSIGNED_RUN).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(dir.path(), &mut out);
|
||||
// The test step below the run step has its own inline addRunArtifact; it must not be
|
||||
// mistaken for the run step's executable.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
let test = out.iter().find(|c| c.id == "zig:test").unwrap();
|
||||
assert!(!test.extras.params.contains_key("debugTarget"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ import { compoundChildren } from "./configs";
|
||||
import { containerDebuggable, remoteDebugBlocked } from "./remote";
|
||||
import { debugInContainer } from "./containerDebug";
|
||||
import { isDebugOnly, registerBuiltinTypes } from "./types";
|
||||
import { isZigBuildStep, zigDebugTarget } from "./zigDebug";
|
||||
import { junitType } from "./junitType";
|
||||
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
|
||||
import { npmGutter } from "./npmGutter";
|
||||
@@ -221,6 +222,21 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
await debugWithAgent(config, show);
|
||||
return;
|
||||
}
|
||||
// `zig build run` (and other steps that run an executable) have no adapter of their own: debug
|
||||
// through the executable config, which builds the binary first and launches it under CodeLLDB.
|
||||
if (isZigBuildStep(config)) {
|
||||
const target = zigDebugTarget(config, useRun.getState().configs);
|
||||
if (target && getAction("debug.startConfig")) {
|
||||
// Run the executable's before-launch build, then keep the clicked step as the session's
|
||||
// origin so the Run widget, tab identity, rerun and stop follow what the user asked to debug.
|
||||
if (!(await prepareLaunch(target, [config.id], show))) return;
|
||||
await executeAction(
|
||||
"debug.startConfig",
|
||||
show === false ? { config: target, origin: config, show: false } : { config: target, origin: config },
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (getAction("debug.startConfig")) {
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { isZigBuildStep, zigDebugTarget } from "./zigDebug";
|
||||
|
||||
const config = (over: Partial<RunConfig> = {}): RunConfig =>
|
||||
({
|
||||
id: "zig:run",
|
||||
name: "zig build run",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["build", "run"],
|
||||
detected: true,
|
||||
debugAdapter: null,
|
||||
isTest: false,
|
||||
env: {},
|
||||
cwd: null,
|
||||
...over,
|
||||
}) as RunConfig;
|
||||
|
||||
const exe = (id: string, over: Partial<RunConfig> = {}): RunConfig =>
|
||||
config({
|
||||
id,
|
||||
name: id,
|
||||
kind: "zig-application",
|
||||
command: "./zig-out/bin/app",
|
||||
args: [],
|
||||
debugAdapter: "codelldb",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("debugging a Zig build step", () => {
|
||||
it("recognises detected build steps, but not the build, tests or executables", () => {
|
||||
expect(isZigBuildStep(config())).toBe(true);
|
||||
expect(isZigBuildStep(config({ id: "zig:serve", args: ["build", "serve"] }))).toBe(true);
|
||||
expect(isZigBuildStep(config({ id: "zig:test", args: ["build", "test"], isTest: true }))).toBe(false);
|
||||
expect(isZigBuildStep(config({ id: "zig:build", args: ["build"] }))).toBe(false);
|
||||
expect(isZigBuildStep(config({ detected: false }))).toBe(false);
|
||||
expect(isZigBuildStep(exe("zig:exe:app"))).toBe(false);
|
||||
});
|
||||
|
||||
it("never sends a test step to the app binary", () => {
|
||||
const test = config({ id: "zig:test", args: ["build", "test"], isTest: true });
|
||||
expect(zigDebugTarget(test, [exe("zig:exe:app")])).toBeNull();
|
||||
});
|
||||
|
||||
it("delegates to the executable the backend linked via debugTarget", () => {
|
||||
const step = config({ params: { debugTarget: "zig:exe:two" } });
|
||||
const configs = [exe("zig:exe:one"), exe("zig:exe:two")];
|
||||
expect(zigDebugTarget(step, configs)?.id).toBe("zig:exe:two");
|
||||
});
|
||||
|
||||
it("does not guess which executable to debug when there is no link", () => {
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:app")])).toBeNull();
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:one"), exe("zig:exe:two")])).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores a stale or non-debuggable link", () => {
|
||||
expect(zigDebugTarget(config({ params: { debugTarget: "zig:exe:gone" } }), [exe("zig:exe:app")])).toBeNull();
|
||||
expect(
|
||||
zigDebugTarget(config({ params: { debugTarget: "zig:exe:app" } }), [exe("zig:exe:app", { debugAdapter: null })]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the project has no debuggable Zig executable", () => {
|
||||
expect(zigDebugTarget(config(), [])).toBeNull();
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:app", { debugAdapter: null })])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* A Zig build step (`zig build <step>`) builds but has no debug adapter of its own. The project's
|
||||
* executable configs build the binary first and debug it under CodeLLDB, so debugging a step is
|
||||
* delegated to the executable it runs.
|
||||
*/
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
|
||||
const EXE_KIND = "zig-application";
|
||||
|
||||
/**
|
||||
* A detected `zig build <step>` config that runs an executable, which has no debug adapter of its
|
||||
* own. Test steps are excluded: their tests are not the project's app binary.
|
||||
*/
|
||||
export function isZigBuildStep(config: RunConfig): boolean {
|
||||
return (
|
||||
config.detected &&
|
||||
!config.isTest &&
|
||||
config.kind === "zig" &&
|
||||
config.id.startsWith("zig:") &&
|
||||
config.args[0] === "build" &&
|
||||
config.args.length > 1
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The debuggable executable config for a Zig build step, as linked by the backend. Detected
|
||||
* configs are regenerated on load, so a step that runs an executable always carries the link;
|
||||
* without one there is nothing to safely delegate to (a test step, an unparsed build script…).
|
||||
*/
|
||||
export function zigDebugTarget(step: RunConfig, configs: readonly RunConfig[]): RunConfig | null {
|
||||
if (!isZigBuildStep(step)) return null;
|
||||
const linked = step.params?.debugTarget;
|
||||
if (!linked) return null;
|
||||
return configs.find((c) => c.kind === EXE_KIND && !!c.debugAdapter && c.id === linked) ?? null;
|
||||
}
|
||||
Reference in New Issue
Block a user