From c10b9a755d55f5e498120c4d06d82eb432267df4 Mon Sep 17 00:00:00 2001 From: fwrq41251 <6220591+fwrq41251@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:34:38 +0900 Subject: [PATCH] Add Java main-method gutter debugging for JDTLS and Metals --- README.md | 80 ++++++++ debug_adapter_schemas/Java.json | 4 + extension.toml | 2 + languages/java/tasks.json | 3 + proxy/src/http.rs | 149 ++++++++++++++- src/debug_locator.rs | 231 +++++++++++++++++++++++ src/debugger.rs | 317 +++++++++++++++++++++++++++++++- src/java.rs | 16 ++ 8 files changed, 796 insertions(+), 6 deletions(-) create mode 100644 src/debug_locator.rs diff --git a/README.md b/README.md index bbe789a..ff4cf47 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,86 @@ JDTLS uses **CamelCase fuzzy matching** for symbol queries. For example, searchi ## Debugger +### Main-method gutter actions + +Java main-method gutter positions come from the Tree-sitter runnable queries. +The debug locator recognizes main tasks by their `ZED_JAVA_RUNNABLE=main` +environment marker, independently of the language server and debug adapter. +It then generates a launch configuration for the selected debug adapter. +Neither step calls a language server, starts a debug session, or runs the task's +shell command. + +The locator supports the `Java` (JDTLS) and `Metals` debug adapters. With either +adapter selected, Java main-method gutter actions include `Debug: Run `; +no `.zed/debug.json` is required. Other adapters need their own configuration +mapping. + +If you disable the built-in Java tasks and provide your own main-method task, +add `"ZED_JAVA_RUNNABLE": "main"` to that task's `env` object to opt in. Its +environment variables are forwarded to the debug configuration, excluding this +marker. Test runnables are not handled by this locator. + +### Main methods with JDTLS + +Use the `Java` debug adapter with JDTLS enabled: + +```jsonc +{ + "languages": { + "Java": { + "language_servers": ["jdtls", "!metals"], + "debuggers": ["Java"] + } + } +} +``` + +The gutter scenario records `mainFile: "$ZED_FILE"`. When you start debugging, +the adapter asks JDTLS to resolve the main method in that file, preserves its +project identity, and builds before resolving the classpath and starting the +session. A failed or cancelled build stops the launch. JDTLS must have imported +the project for this launch step. +Build requests have a five-minute proxy timeout; other requests retain their +five-second timeout. + +If a source file contains multiple main classes, the adapter reports an ambiguity +instead of choosing one. Create a configuration in `.zed/debug.json` with +`mainFile`, `mainClass`, and, if needed, `projectName` to select the entry. +Existing launch configurations without `mainFile` retain their current behavior. + +### Main methods with Metals + +If you use Metals instead of JDTLS, install the +[Scala extension](https://github.com/scalameta/metals-zed) and select its debug +adapter for Java: + +```jsonc +{ + "languages": { + "Java": { + "language_servers": ["metals", "!jdtls"], + "debuggers": ["Metals"] + } + } +} +``` + +With the Metals adapter selected, the gutter actions for Java main methods and +their classes include `Debug: Run `. No `.zed/debug.json` is required. +The generated configuration contains `path: "$ZED_FILE"` and +`runType: "runOrTestFile"`. When you start debugging, the Metals adapter contacts +its language server to discover the main class and build target and prepare the +session through its existing build-server integration. Metals must have imported +your project for this launch step. Debugging uses Metals' file discovery rather +than the task's command or arguments. + +This requires Metals to be available for Java in your Scala extension +installation, and its DAP proxy to be enabled. The Scala extension's +[debugging documentation](https://github.com/scalameta/metals-zed#debugging) +describes its setup and restrictions. + +### Debugging with JDTLS + Debug support is enabled via our [Fork of Java Debug](https://github.com/zed-industries/java-debug), which the extension will automatically download and start for you. Please refer to the [Zed Documentation](https://zed.dev/docs/debugger#getting-started) for general information about how debugging works in Zed. ### Launch Mode diff --git a/debug_adapter_schemas/Java.json b/debug_adapter_schemas/Java.json index e36b5bf..678d821 100644 --- a/debug_adapter_schemas/Java.json +++ b/debug_adapter_schemas/Java.json @@ -18,6 +18,10 @@ "type": "string", "description": "The fully qualified name of the class containing the main method. If not specified, the debugger automatically resolves the possible main class from the current project." }, + "mainFile": { + "type": "string", + "description": "The absolute path to a Java source file, or $ZED_FILE. Resolves the main class and project from this file and builds before launch. Use mainClass and projectName to disambiguate multiple entries." + }, "args": { "oneOf": [ { diff --git a/extension.toml b/extension.toml index a6a76a0..48b9a16 100644 --- a/extension.toml +++ b/extension.toml @@ -36,6 +36,8 @@ languages = ["Gradle", "Gradle KTS"] [debug_adapters.Java] +[debug_locators.java] + [[capabilities]] kind = "process:exec" command = "*" diff --git a/languages/java/tasks.json b/languages/java/tasks.json index 4f757f9..d15f216 100644 --- a/languages/java/tasks.json +++ b/languages/java/tasks.json @@ -7,6 +7,9 @@ "tags": [ "java-main" ], + "env": { + "ZED_JAVA_RUNNABLE": "main" + }, "shell": { "with_arguments": { "program": "/bin/sh", diff --git a/proxy/src/http.rs b/proxy/src/http.rs index f4446b7..3bed463 100644 --- a/proxy/src/http.rs +++ b/proxy/src/http.rs @@ -12,7 +12,8 @@ use std::{ use crate::pending::PendingResponses; use proxy_common::encode_lsp; -pub const TIMEOUT: Duration = Duration::from_secs(5); +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); +const BUILD_TIMEOUT: Duration = Duration::from_secs(300); #[derive(Deserialize)] struct HttpBody { @@ -20,6 +21,19 @@ struct HttpBody { params: Value, } +impl HttpBody { + fn timeout(&self) -> Duration { + if self.method == "workspace/executeCommand" + && self.params.get("command").and_then(Value::as_str) + == Some("vscode.java.buildWorkspace") + { + BUILD_TIMEOUT + } else { + DEFAULT_TIMEOUT + } + } +} + #[derive(Serialize)] struct LspRequest { jsonrpc: &'static str, @@ -80,6 +94,7 @@ pub fn handle_http( let seq = counter.fetch_add(1, Ordering::Relaxed); let id = Value::String(format!("{owned_id_prefix}http-{seq}")); let rx = pending.register(id.clone()); + let timeout = req.timeout(); let lsp_req = LspRequest { jsonrpc: "2.0", @@ -94,7 +109,7 @@ pub fn handle_http( }; let response = if request_sent { - match rx.recv_timeout(TIMEOUT) { + match rx.recv_timeout(timeout) { Ok(resp) => resp, Err(_) => { pending.remove(&id); @@ -112,7 +127,10 @@ pub fn handle_http( "id": id, "error": { "code": -32803, - "message": "Request to language server timed out after 5000ms." + "message": format!( + "Request to language server timed out after {}ms.", + timeout.as_millis() + ) } }) } @@ -137,3 +155,128 @@ pub fn handle_http( let _ = stream.write_all(http_resp.as_bytes()); let _ = stream.write_all(&resp_body); } + +#[cfg(test)] +mod tests { + use super::*; + use proxy_common::{parse_lsp_content, LspReader}; + use serde_json::json; + use std::{ + net::{TcpListener, TcpStream}, + thread::{self, JoinHandle}, + }; + + struct HttpExchange { + client: TcpStream, + lsp: LspReader, + pending: Arc, + handler: JoinHandle<()>, + } + + impl HttpExchange { + fn start(method: &str, params: Value) -> Self { + let (mut client, server) = connected_streams(); + let (writer, lsp) = connected_streams(); + let pending = Arc::new(PendingResponses::new()); + let handler_pending = pending.clone(); + let handler = thread::spawn(move || { + handle_http( + server, + Arc::new(Mutex::new(writer)), + handler_pending, + Arc::new(AtomicU64::new(1)), + "test-", + ); + }); + let body = json!({ "method": method, "params": params }).to_string(); + write!( + client, + "POST / HTTP/1.1\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .unwrap(); + + Self { + client, + lsp: LspReader::new(lsp), + pending, + handler, + } + } + + fn next_lsp_message(&mut self) -> Value { + let message = self.lsp.read_message().unwrap().unwrap(); + parse_lsp_content(&message).unwrap() + } + + fn finish(mut self) -> Value { + let mut response = String::new(); + self.client.read_to_string(&mut response).unwrap(); + self.handler.join().unwrap(); + let (headers, body) = response.split_once("\r\n\r\n").unwrap(); + assert!(headers.starts_with("HTTP/1.1 200 OK")); + serde_json::from_str(body).unwrap() + } + } + + fn connected_streams() -> (TcpStream, TcpStream) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (server, _) = listener.accept().unwrap(); + for stream in [&client, &server] { + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .unwrap(); + } + (client, server) + } + + #[test] + fn build_succeeding_after_the_default_timeout_returns_success() { + let mut exchange = HttpExchange::start( + "workspace/executeCommand", + json!({ + "command": "vscode.java.buildWorkspace", + "arguments": ["{\"mainClass\":\"example.Main\",\"isFullBuild\":false}"], + }), + ); + let request = exchange.next_lsp_message(); + + thread::sleep(DEFAULT_TIMEOUT + Duration::from_secs(1)); + let response = json!({ "jsonrpc": "2.0", "id": request["id"], "result": 1 }); + assert!(exchange.pending.route(&response)); + + assert_eq!(exchange.finish(), response); + } + + #[test] + fn ordinary_request_timeout_cancels_the_request_and_reports_its_duration() { + let mut exchange = HttpExchange::start( + "workspace/executeCommand", + json!({ "command": "vscode.java.resolveMainMethod" }), + ); + let request = exchange.next_lsp_message(); + + let cancellation = exchange.next_lsp_message(); + let response = exchange.finish(); + + assert_eq!(cancellation["method"], "$/cancelRequest"); + assert_eq!(cancellation["params"]["id"], request["id"]); + assert_eq!(response["id"], request["id"]); + assert_eq!(response["error"]["code"], -32803); + assert_eq!( + response["error"]["message"], + "Request to language server timed out after 5000ms." + ); + } + + #[test] + fn build_command_in_another_method_keeps_the_default_timeout() { + let request = HttpBody { + method: "textDocument/hover".into(), + params: json!({ "command": "vscode.java.buildWorkspace" }), + }; + + assert_eq!(request.timeout(), DEFAULT_TIMEOUT); + } +} diff --git a/src/debug_locator.rs b/src/debug_locator.rs new file mode 100644 index 0000000..3a6edd0 --- /dev/null +++ b/src/debug_locator.rs @@ -0,0 +1,231 @@ +use zed_extension_api::{self as zed, serde_json::json}; + +const RUNNABLE_ENV: &str = "ZED_JAVA_RUNNABLE"; + +#[derive(Debug, PartialEq)] +enum JavaRunnable { + Main, +} + +impl JavaRunnable { + fn from_task(task: &zed::TaskTemplate) -> Option { + task.env + .iter() + .any(|(name, value)| name == RUNNABLE_ENV && value == "main") + .then_some(Self::Main) + } + + fn debug_config(self, debug_adapter_name: &str) -> Option { + match (self, debug_adapter_name) { + (Self::Main, "Java") => Some(json!({ + "request": "launch", + "mainFile": "$ZED_FILE", + })), + (Self::Main, "Metals") => Some(json!({ + "request": "launch", + "path": "$ZED_FILE", + "runType": "runOrTestFile", + })), + _ => None, + } + } +} + +pub fn create_scenario( + locator_name: &str, + build_task: zed::TaskTemplate, + resolved_label: String, + debug_adapter_name: &str, +) -> Option { + if locator_name != "java" { + return None; + } + + let runnable = JavaRunnable::from_task(&build_task)?; + let mut config = runnable.debug_config(debug_adapter_name)?; + let env = build_task + .env + .into_iter() + .filter(|(name, _)| name != RUNNABLE_ENV) + .map(|(name, value)| (name, value.into())) + .collect::>(); + if !env.is_empty() { + config["env"] = env.into(); + } + + Some(zed::DebugScenario { + label: resolved_label, + adapter: debug_adapter_name.to_owned(), + build: None, + config: config.to_string(), + tcp_connection: None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use zed::serde_json::{Value, from_str}; + + fn main_task() -> zed::TaskTemplate { + let tasks: Vec = from_str(include_str!("../languages/java/tasks.json")).unwrap(); + let task = tasks + .into_iter() + .find(|task| { + task["tags"] + .as_array() + .unwrap() + .iter() + .any(|tag| tag == "java-main") + }) + .unwrap(); + + zed::TaskTemplate { + label: task["label"].as_str().unwrap().to_owned(), + command: task["command"].as_str().unwrap().to_owned(), + args: Vec::new(), + env: task["env"] + .as_object() + .unwrap() + .iter() + .map(|(name, value)| (name.clone(), value.as_str().unwrap().to_owned())) + .collect(), + cwd: None, + } + } + + #[test] + fn main_runnable_detection_uses_only_the_task_marker() { + let mut task = main_task(); + task.label.clear(); + task.command.clear(); + task.args = vec!["custom-argument".into()]; + task.cwd = Some("$ZED_WORKTREE_ROOT/module with spaces".into()); + task.env.push(("APP_MODE".into(), "development".into())); + + assert_eq!(JavaRunnable::from_task(&task), Some(JavaRunnable::Main)); + } + + #[test] + fn main_runnable_uses_metals_file_discovery_without_starting_a_session() { + let scenario = create_scenario("java", main_task(), "Run Main".into(), "Metals").unwrap(); + + assert_eq!(scenario.label, "Run Main"); + assert_eq!(scenario.adapter, "Metals"); + assert!(scenario.build.is_none()); + assert!(scenario.tcp_connection.is_none()); + assert_eq!( + from_str::(&scenario.config).unwrap(), + json!({ + "request": "launch", + "path": "$ZED_FILE", + "runType": "runOrTestFile", + }) + ); + } + + #[test] + fn main_runnable_defers_jdtls_resolution_until_launch() { + let scenario = create_scenario("java", main_task(), "Run Main".into(), "Java").unwrap(); + + assert_eq!(scenario.label, "Run Main"); + assert_eq!(scenario.adapter, "Java"); + assert!(scenario.build.is_none()); + assert!(scenario.tcp_connection.is_none()); + assert_eq!( + from_str::(&scenario.config).unwrap(), + json!({ + "request": "launch", + "mainFile": "$ZED_FILE", + }) + ); + } + + #[test] + fn task_environment_is_preserved_without_the_runnable_marker() { + let mut task = main_task(); + task.env.push(("APP_MODE".into(), "development".into())); + task.env.push(( + "CONFIG_FILE".into(), + "$ZED_WORKTREE_ROOT/config.json".into(), + )); + + for adapter in ["Java", "Metals"] { + let scenario = + create_scenario("java", task.clone(), "Run Main".into(), adapter).unwrap(); + let config: Value = from_str(&scenario.config).unwrap(); + + assert_eq!( + config["env"], + json!({ + "APP_MODE": "development", + "CONFIG_FILE": "$ZED_WORKTREE_ROOT/config.json", + }) + ); + } + } + + #[test] + fn unrelated_tasks_are_not_identified_by_their_labels_or_commands() { + let mut task = main_task(); + task.env.clear(); + + assert_eq!(JavaRunnable::from_task(&task), None); + for adapter in ["Java", "Metals"] { + assert!(create_scenario("java", task.clone(), "Run Main".into(), adapter).is_none()); + } + } + + #[test] + fn test_runnables_are_not_converted_to_main_sessions() { + for runnable in ["test-method", "test-class", "test-all"] { + let mut task = main_task(); + task.env = vec![(RUNNABLE_ENV.into(), runnable.into())]; + + assert_eq!(JavaRunnable::from_task(&task), None); + for adapter in ["Java", "Metals"] { + assert!( + create_scenario("java", task.clone(), "Test Main".into(), adapter).is_none() + ); + } + } + } + + #[test] + fn unsupported_adapters_do_not_receive_java_configuration() { + for adapter in ["IntelliJ", "Python", ""] { + assert!(JavaRunnable::Main.debug_config(adapter).is_none()); + assert!(create_scenario("java", main_task(), "Run Main".into(), adapter).is_none()); + } + } + + #[test] + fn other_locators_are_not_intercepted() { + for adapter in ["Java", "Metals"] { + assert!(create_scenario("scala", main_task(), "Run Main".into(), adapter).is_none()); + } + } + + #[test] + fn main_discovery_does_not_depend_on_package_or_class_captures() { + let mut task = main_task(); + task.label = "Run current file".into(); + task.command = "custom-runner".into(); + task.cwd = Some("$ZED_WORKTREE_ROOT/module with spaces".into()); + + for adapter in ["Java", "Metals"] { + let scenario = + create_scenario("java", task.clone(), "Run current file".into(), adapter).unwrap(); + let config: Value = from_str(&scenario.config).unwrap(); + + let file_key = if adapter == "Java" { + "mainFile" + } else { + "path" + }; + assert_eq!(config[file_key], "$ZED_FILE"); + assert!(config.get("mainClass").is_none()); + assert!(config.get("buildTarget").is_none()); + } + } +} diff --git a/src/debugger.rs b/src/debugger.rs index c751dda..3a24ebf 100644 --- a/src/debugger.rs +++ b/src/debugger.rs @@ -14,8 +14,9 @@ use crate::{ downloadable::Downloadable, lsp, util::{ - ArgsStringOrList, create_path_if_not_exists, get_curr_dir, path_to_string, - record_successful_update_check, should_use_local_or_download, update_check_path, + ArgsStringOrList, create_path_if_not_exists, get_curr_dir, path_to_file_uri, + path_to_string, record_successful_update_check, should_use_local_or_download, + update_check_path, }, }; @@ -23,6 +24,8 @@ use crate::{ #[serde(rename_all = "camelCase")] struct JavaDebugLaunchConfig { request: String, + #[serde(skip_serializing)] + main_file: Option, #[serde(skip_serializing_if = "Option::is_none")] project_name: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -55,12 +58,74 @@ struct JavaDebugLaunchConfig { java_exec: Option, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct MainMethod { + main_class: String, + project_name: Option, +} + +impl JavaDebugLaunchConfig { + fn prepare_main_file( + &mut self, + mut execute_command: impl FnMut(&str, Value) -> zed::Result, + ) -> zed::Result { + let Some(main_file) = &self.main_file else { + return Ok(false); + }; + + let response = execute_command( + "vscode.java.resolveMainMethod", + json!([path_to_file_uri(main_file)]), + ) + .map_err(|err| format!("Failed to resolve main method in {main_file}: {err}"))?; + let entries: Vec = serde_json::from_value(response) + .map_err(|err| format!("Invalid main method response for {main_file}: {err}"))?; + let mut entries = entries.into_iter().filter(|entry| { + self.main_class + .as_ref() + .is_none_or(|main_class| main_class == &entry.main_class) + && self + .project_name + .as_ref() + .is_none_or(|project_name| Some(project_name) == entry.project_name.as_ref()) + }); + let entry = entries + .next() + .ok_or_else(|| format!("No matching Java main method found in {main_file}"))?; + if entries.next().is_some() { + return Err(format!( + "Multiple Java main methods found in {main_file}; specify mainClass and projectName in .zed/debug.json" + )); + } + + let params = json!({ + "mainClass": entry.main_class, + "projectName": entry.project_name, + "isFullBuild": false, + }); + let status = execute_command("vscode.java.buildWorkspace", json!([params.to_string()])) + .map_err(|err| format!("Failed to build Java workspace: {err}"))?; + if status.as_u64() != Some(BUILD_SUCCEEDED) { + return Err(format!( + "Java build did not succeed ({status}); fix compilation errors or retry before debugging" + )); + } + + self.main_class = Some(entry.main_class); + self.project_name = entry.project_name; + Ok(true) + } +} + const TEST_SCOPE: &str = "$Test"; const AUTO_SCOPE: &str = "$Auto"; const RUNTIME_SCOPE: &str = "$Runtime"; const SCOPES: [&str; 3] = [TEST_SCOPE, AUTO_SCOPE, RUNTIME_SCOPE]; +const BUILD_SUCCEEDED: u64 = 1; + const DEBUGGER_INSTALL_PATH: &str = "debugger"; const JAVA_DEBUG_PLUGIN_FORK_URL: &str = "https://github.com/zed-industries/java-debug/releases/download/0.53.2/com.microsoft.java.debug.plugin-0.53.2.jar"; @@ -287,7 +352,17 @@ impl Debugger { let workspace_folder = worktree.root_path(); - let (main_class, project_name) = { + let file_launch = config.prepare_main_file(|command, arguments| { + lsp::request( + &workspace_folder, + "workspace/executeCommand", + json!({ "command": command, "arguments": arguments }), + ) + })?; + + let (main_class, project_name) = if file_launch { + (config.main_class.take(), config.project_name.take()) + } else { let arguments = [config.main_class.clone(), config.project_name.clone()] .iter() .flatten() @@ -480,6 +555,242 @@ impl Downloadable for Debugger { mod tests { use super::*; + fn prepare_file_launch( + config: Value, + main_methods: Value, + build_status: Value, + ) -> ( + JavaDebugLaunchConfig, + zed::Result, + Vec<(String, Value)>, + ) { + let mut config: JavaDebugLaunchConfig = serde_json::from_value(config).unwrap(); + let mut requests = Vec::new(); + let result = config.prepare_main_file(|command, arguments| { + requests.push((command.to_string(), arguments)); + match command { + "vscode.java.resolveMainMethod" => Ok(main_methods.clone()), + "vscode.java.buildWorkspace" => Ok(build_status.clone()), + _ => panic!("Unexpected command: {command}"), + } + }); + + (config, result, requests) + } + + #[test] + fn file_launch_resolves_the_source_project_and_builds_before_launch() { + let (config, result, requests) = prepare_file_launch( + json!({ + "request": "launch", + "mainFile": "/workspace/module b/src/主类 #1%.java", + "env": { "APP_MODE": "development" }, + "args": ["hello"], + }), + json!([{ + "mainClass": "example.Main", + "projectName": "module-b", + "range": { + "start": { "line": 3, "character": 23 }, + "end": { "line": 3, "character": 27 }, + }, + }]), + json!(1), + ); + + assert!(result.unwrap()); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0], + ( + "vscode.java.resolveMainMethod".into(), + json!(["file:///workspace/module%20b/src/%E4%B8%BB%E7%B1%BB%20%231%25.java"]), + ) + ); + assert_eq!(requests[1].0, "vscode.java.buildWorkspace"); + assert_eq!( + serde_json::from_str::(requests[1].1[0].as_str().unwrap()).unwrap(), + json!({ + "mainClass": "example.Main", + "projectName": "module-b", + "isFullBuild": false, + }) + ); + let config = serde_json::to_value(config).unwrap(); + assert_eq!(config["mainClass"], "example.Main"); + assert_eq!(config["projectName"], "module-b"); + assert_eq!(config["env"], json!({ "APP_MODE": "development" })); + assert_eq!(config["args"], "hello"); + assert!(config.get("mainFile").is_none()); + } + + #[test] + fn manual_launch_without_main_file_skips_file_resolution_and_build() { + let mut config: JavaDebugLaunchConfig = serde_json::from_value(json!({ + "request": "launch", + "mainClass": "example.Main", + "projectName": "module-a", + })) + .unwrap(); + + assert!( + !config + .prepare_main_file(|command, _| panic!("Unexpected command: {command}")) + .unwrap() + ); + assert_eq!(config.main_class.as_deref(), Some("example.Main")); + assert_eq!(config.project_name.as_deref(), Some("module-a")); + } + + #[test] + fn missing_main_method_does_not_build_or_fall_back_to_another_project() { + for (filters, entries) in [ + (json!({}), json!([])), + ( + json!({ "mainClass": "example.Missing" }), + json!([{ "mainClass": "example.Main", "projectName": "module-a" }]), + ), + ( + json!({ "projectName": "module-b" }), + json!([{ "mainClass": "example.Main", "projectName": "module-a" }]), + ), + ] { + let mut config = json!({ + "request": "launch", + "mainFile": "/workspace/Main.java", + }); + config + .as_object_mut() + .unwrap() + .extend(filters.as_object().unwrap().clone()); + let (_, result, requests) = prepare_file_launch(config, entries, json!(1)); + + assert!(result.unwrap_err().contains("No matching Java main method")); + assert_eq!(requests.len(), 1); + } + } + + #[test] + fn multiple_main_methods_require_selection_before_building() { + let (_, result, requests) = prepare_file_launch( + json!({ "request": "launch", "mainFile": "/workspace/Main.java" }), + json!([ + { "mainClass": "example.Main", "projectName": "module-a" }, + { "mainClass": "example.Other", "projectName": "module-a" }, + ]), + json!(1), + ); + + assert!(result.unwrap_err().contains("Multiple Java main methods")); + assert_eq!(requests.len(), 1); + } + + #[test] + fn explicit_class_and_project_select_the_matching_file_entry() { + let (config, result, requests) = prepare_file_launch( + json!({ + "request": "launch", + "mainFile": "/workspace/Main.java", + "mainClass": "example.Main", + "projectName": "module-b", + }), + json!([ + { "mainClass": "example.Main", "projectName": "module-a" }, + { "mainClass": "example.Other", "projectName": "module-b" }, + { "mainClass": "example.Main", "projectName": "module-b" }, + ]), + json!(1), + ); + + assert!(result.unwrap()); + assert_eq!(config.main_class.as_deref(), Some("example.Main")); + assert_eq!(config.project_name.as_deref(), Some("module-b")); + assert_eq!( + serde_json::from_str::(requests[1].1[0].as_str().unwrap()).unwrap()["projectName"], + "module-b" + ); + } + + #[test] + fn file_resolution_preserves_an_unnamed_project() { + let (config, result, requests) = prepare_file_launch( + json!({ "request": "launch", "mainFile": "/workspace/Main.java" }), + json!([{ "mainClass": "Main", "projectName": null }]), + json!(1), + ); + + assert!(result.unwrap()); + assert_eq!(config.main_class.as_deref(), Some("Main")); + assert!(config.project_name.is_none()); + assert!( + serde_json::from_str::(requests[1].1[0].as_str().unwrap()).unwrap()["projectName"] + .is_null() + ); + } + + #[test] + fn unsuccessful_or_unknown_build_status_stops_the_launch() { + for status in [ + json!(0), + json!(2), + json!(3), + json!(100), + json!("SUCCEED"), + json!("UNKNOWN"), + Value::Null, + ] { + let (config, result, requests) = prepare_file_launch( + json!({ "request": "launch", "mainFile": "/workspace/Main.java" }), + json!([{ "mainClass": "example.Main", "projectName": "module-a" }]), + status, + ); + + assert!(result.unwrap_err().contains("Java build did not succeed")); + assert!(config.main_class.is_none()); + assert_eq!(requests.len(), 2); + } + } + + #[test] + fn file_resolution_and_build_request_failures_stop_the_launch() { + for failed_command in [ + "vscode.java.resolveMainMethod", + "vscode.java.buildWorkspace", + ] { + let mut config: JavaDebugLaunchConfig = serde_json::from_value(json!({ + "request": "launch", + "mainFile": "/workspace/Main.java", + })) + .unwrap(); + let mut requests = Vec::new(); + let result = config.prepare_main_file(|command, _| { + requests.push(command.to_string()); + if command == failed_command { + return Err("LSP request failed".into()); + } + Ok(json!([{ "mainClass": "example.Main", "projectName": "module-a" }])) + }); + + assert!(result.unwrap_err().contains("LSP request failed")); + assert_eq!(requests.last().unwrap(), failed_command); + assert!(config.main_class.is_none()); + } + } + + #[test] + fn invalid_main_method_responses_stop_before_building() { + for response in [Value::Null, json!({}), json!([{ "mainClass": 42 }])] { + let (_, result, requests) = prepare_file_launch( + json!({ "request": "launch", "mainFile": "/workspace/Main.java" }), + response, + json!(1), + ); + + assert!(result.unwrap_err().contains("Invalid main method response")); + assert_eq!(requests.len(), 1); + } + } + fn injected_bundle(plugin_path: PathBuf) -> String { let debugger = Debugger { plugin_path: Some(plugin_path), diff --git a/src/java.rs b/src/java.rs index b65526b..c81bf38 100644 --- a/src/java.rs +++ b/src/java.rs @@ -1,4 +1,5 @@ mod config; +mod debug_locator; mod debugger; mod downloadable; mod gradle_bridge; @@ -193,6 +194,21 @@ impl Extension for Java { } } + fn dap_locator_create_scenario( + &mut self, + locator_name: String, + build_task: zed::TaskTemplate, + resolved_label: String, + debug_adapter_name: String, + ) -> Option { + debug_locator::create_scenario( + &locator_name, + build_task, + resolved_label, + &debug_adapter_name, + ) + } + fn dap_config_to_scenario( &mut self, config: zed::DebugConfig,