diff --git a/crates/ide-dap/src/adapter.rs b/crates/ide-dap/src/adapter.rs index c5aec361a..75affc815 100644 --- a/crates/ide-dap/src/adapter.rs +++ b/crates/ide-dap/src/adapter.rs @@ -22,6 +22,8 @@ use tokio::process::{Child, Command}; pub const PORT_PLACEHOLDER: &str = "${port}"; /// Replaced by the session's working directory (the project) in adapter arguments. pub const ROOT_PLACEHOLDER: &str = "${root}"; +/// java-analyzer's debug adapter (`java-analyzer dap`), a separate process over stdio. +pub const JAVA_ANALYZER: &str = "java-analyzer"; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Transport { @@ -134,6 +136,14 @@ fn builtin(adapter: &str) -> Option { "tcp", "Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)", ), + // The Java language server's own debugger, for modules jdtls doesn't serve; the host + // runs the executable of the java-analyzer serving the module. + JAVA_ANALYZER => cfg( + "java-analyzer", + &["dap"], + "stdio", + "Configure java-analyzer as a Java language server (Settings › Languages & Frameworks › Language Servers)", + ), "bun-dap" => cfg( "bun-dap", &["${port}", "127.0.0.1"], @@ -920,6 +930,13 @@ mod tests { } let delve = resolve(&builtin("delve").unwrap(), PathBuf::from("/")); assert_eq!(delve.transport, Transport::Tcp); + // java-analyzer debugs over stdio with its `dap` subcommand. + let java_analyzer = resolve(&builtin(JAVA_ANALYZER).unwrap(), PathBuf::from("/")); + assert_eq!( + (java_analyzer.command.as_str(), java_analyzer.args.as_slice()), + ("java-analyzer", &["dap".to_owned()][..]) + ); + assert_eq!(java_analyzer.transport, Transport::Stdio); // GDB's own DAP interpreter over stdio, with the required version in its hint. let gdb = builtin("gdb").unwrap(); assert_eq!(gdb.command, "gdb"); diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index e77a5ffbe..ec2cd2c47 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -113,7 +113,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide }) .await?; } + let java_analyzer = java_analyzer_command(host, window, &config)?; let custom = |command: &str| { + if let Some(binary) = java_analyzer { + return Some(binary.to_string_lossy().into_owned()); + } let path = ide_sdk::apply::tool_command(&root, &settings, command) .or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?; Some(path.to_string_lossy().into_owned()) @@ -142,6 +146,28 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide result } +/// For java-analyzer's debugger, the executable of the java-analyzer serving the module +/// (`projectRoot`, else the working directory), so the session debugs with the server that +/// analyzes the code. +fn java_analyzer_command(host: &Host, window: &str, config: &LaunchConfig) -> IdeResult> { + if config.adapter != ide_dap::adapter::JAVA_ANALYZER { + return Ok(None); + } + let project = host.project(window)?; + let extra: serde_json::Value = + config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok()).unwrap_or_default(); + let module = extra["projectRoot"] + .as_str() + .map(PathBuf::from) + .or_else(|| config.cwd.clone().map(PathBuf::from)) + .unwrap_or_else(|| project.root.clone()); + project.lsp.java_analyzer_binary(&module).map(Some).ok_or_else(|| { + ide_core::IdeError::unavailable( + "No java-analyzer serves this module: configure it as a Java language server to debug without jdtls", + ) + }) +} + fn require_unity_editor(pid: u32) -> IdeResult<()> { if !ide_core::process::process_alive(pid) { return Err(ide_core::IdeError::unavailable(format!( @@ -178,13 +204,16 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port } /// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by -/// java-debug or the Kotlin debugger (JAR Application debugs through a run with a JDWP agent). +/// java-debug, java-analyzer or the Kotlin debugger (JAR Application debugs through a run with a +/// JDWP agent). fn is_jvm_launch(config: &LaunchConfig) -> bool { - config.request == "launch" && matches!(config.adapter.as_str(), "java-debug" | ide_dap::kotlin::ADAPTER) + config.request == "launch" + && matches!(config.adapter.as_str(), "java-debug" | ide_dap::kotlin::ADAPTER | ide_dap::adapter::JAVA_ANALYZER) } /// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options: -/// java-debug's `vmArgs` (one line, or a list) or the Kotlin debugger's `vmArguments` (a list). +/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's +/// `vmArguments` (a list). fn add_java_agents(mut config: LaunchConfig, options: &[String]) -> LaunchConfig { if options.is_empty() || !is_jvm_launch(&config) { return config; @@ -194,7 +223,7 @@ fn add_java_agents(mut config: LaunchConfig, options: &[String]) -> LaunchConfig else { return config; }; - let key = if config.adapter == "java-debug" { "vmArgs" } else { "vmArguments" }; + let key = if config.adapter == ide_dap::kotlin::ADAPTER { "vmArguments" } else { "vmArgs" }; let value = match extra.get(key) { None | Some(serde_json::Value::Null) if key == "vmArgs" => { ide_run::java_agent::add_to_vm_args_text("", options).into() @@ -735,6 +764,9 @@ mod tests { assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!(["-Xmx1g", agent])); let kotlin = launch(ide_dap::kotlin::ADAPTER, "launch", serde_json::json!({})); assert_eq!(field(&add_java_agents(kotlin, options), "vmArguments"), serde_json::json!([agent])); + let java_analyzer = + launch(ide_dap::adapter::JAVA_ANALYZER, "launch", serde_json::json!({"vmArgs": ["-Xmx1g"]})); + assert_eq!(vm_args(&add_java_agents(java_analyzer, options)), serde_json::json!(["-Xmx1g", agent])); // Attaching (remote debug included), other adapters, and no granted agent: unchanged. for config in [ launch("java-debug", "attach", serde_json::json!({"vmArgs": "-Xmx1g"})), diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 53eb6545c..33c462673 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -5,12 +5,14 @@ use crate::Host; use ide_command::command; use super::build::load; +use ide_build::BuildModel; use ide_build::compile; use ide_core::error::ErrorKind; +use ide_core::settings::Settings; use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; use ide_lsp::jdtls::{JavaBuildStatus, JavaLaunchInfo}; use ide_run::BuildPolicy; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// Cancellable with `cancel_request(request)`. /// Builds according to `policy`, then resolves the runtime (or test) @@ -45,6 +47,9 @@ pub(crate) async fn resolve_launch( let started = std::time::Instant::now(); let project = host.project(window)?; let module = project.root.join(module); + if !project.lsp.java_served_by_jdtls(&module) { + return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await; + } let settings = project.settings.effective(); // A launch builds incrementally unless the configuration asks for Rebuild or NoBuild. let build = policy != BuildPolicy::NoBuild; @@ -161,35 +166,7 @@ pub(crate) async fn resolve_launch( } } let compile_ms = started.elapsed().as_millis() - lsp_ms; - // The module/project JDK, else the JDK jdtls compiles the module against, else one matching its Java version. - let project_jdk = ide_sdk::apply::module_jdk(&project.root, &module, &settings); - let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file()); - let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| { - // The build model's level includes what the module inherits from its parent POMs. - let release = model - .maven - .as_ref() - .and_then(|m| m.projects.iter().find(|p| project.root.join(&p.dir) == module)) - .and_then(|p| p.java_version) - .or_else(|| ide_sdk::java::project_java_version(&module)); - let jdks = ide_sdk::java::installed_jdks(); - info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release)); - ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home)) - }); - info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned())); - let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java")); - let shorten = - ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows)); - info.shorten_command_line = Some(shorten.as_str().to_owned()); - if info.error_count > 0 { - let own = ide_sdk::lombok::agent_in_args(settings.languages.java.jdtls_vm_args.split_whitespace()); - let managed = ide_tools::managed_bundle(&data_dir, "lombok"); - let repo = ide_sdk::apply::maven_local_repository(&project.root, &settings); - let root = project.root.clone(); - // Detection may read the project's sources. - let lombok = ide_sdk::lombok::lombok_agent(&root, own, managed, repo); - info.hints.extend(lombok.problem()); - } + finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } @@ -206,6 +183,151 @@ pub(crate) async fn resolve_launch( .map_err(|e| IdeError::internal(e.to_string()))? } +/// A launch of a module jdtls doesn't serve (another Java language server, or none): the +/// build tool compiles it, and the classpath comes from that server, else from Maven. +async fn resolve_launch_without_jdtls( + host: &Host, + project: &std::sync::Arc, + module: PathBuf, + test: bool, + policy: BuildPolicy, + cancel: &CancellationToken, +) -> IdeResult { + let started = std::time::Instant::now(); + let settings = project.settings.effective(); + let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build }; + let (model, built) = { + let (root, cache, settings, module, cancel) = + (project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone()); + tokio::task::spawn_blocking(move || { + let model = load(&root, &cache, &settings); + let built = if policy == BuildPolicy::NoBuild { + None + } else { + Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel)) + }; + (model, built) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + }; + let mut info = + JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() }; + let mut class_paths = Vec::new(); + match built { + None => {} + Some(Err(e)) if e.kind == ErrorKind::Cancelled => return Err(e), + Some(Err(e)) => { + return Err(IdeError::unavailable(format!( + "Cannot build the module without jdtls: {}. Running needs a Maven or Gradle build, or jdtls", + e.message + ))); + } + Some(Ok(built)) => { + info.build = Some(match built.failure { + None => JavaBuildStatus::Succeeded, + Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => { + info.hints.push(failure); + JavaBuildStatus::Failed + } + Some(failure) => return Err(IdeError::internal(failure)), + }); + class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned())); + } + } + let build_ms = started.elapsed().as_millis(); + let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?; + let data_dir = host.local_data_dir.clone(); + let project = project.clone(); + let cancel = cancel.clone(); + tokio::task::spawn_blocking(move || { + match from_server { + Some(server) => { + info.project_root = server.classpath.project_root; + info.module_paths = server.classpath.module_paths; + info.java_home = server.jdk_home.map(Into::into); + append_unique_class_paths(&mut class_paths, server.classpath.class_paths); + } + None => { + let is_maven = model + .maven + .as_ref() + .is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module)); + if !is_maven { + return Err(IdeError::unavailable( + "Cannot resolve the classpath: the Java language server does not report it \ + (java-analyzer/projectClasspath), and the module is not a Maven project", + )); + } + let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings); + let classpath = compile::module_classpath( + &project.root, + &model, + &module, + test, + local_repo, + &project.build_cache_dir(), + &cancel, + )?; + append_unique_class_paths( + &mut class_paths, + std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), + ); + } + } + info.class_paths = class_paths; + apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test); + finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + tracing::info!(build_ms, total_ms = started.elapsed().as_millis(), "Java launch resolved without jdtls"); + Ok(info) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))? +} + +/// Picks the `java` launcher and how to shorten its command line, and explains likely +/// causes of compile errors. +fn finish_launch( + info: &mut JavaLaunchInfo, + root: &Path, + module: &Path, + settings: &Settings, + model: &BuildModel, + data_dir: &Path, +) { + // The module/project JDK, else the JDK the Java language server builds the module with, else one + // matching its Java version. + let project_jdk = ide_sdk::apply::module_jdk(root, module, settings); + let from_server = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file()); + let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_server).or_else(|| { + // The build model's level includes what the module inherits from its parent POMs. + let release = model + .maven + .as_ref() + .and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) + .and_then(|p| p.java_version) + .or_else(|| ide_sdk::java::project_java_version(module)); + let jdks = ide_sdk::java::installed_jdks(); + info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release)); + ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home)) + }); + info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned())); + let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java")); + let shorten = ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows)); + info.shorten_command_line = Some(shorten.as_str().to_owned()); + if info.error_count > 0 { + let own = ide_sdk::lombok::agent_in_args(settings.languages.java.jdtls_vm_args.split_whitespace()); + let managed = ide_tools::managed_bundle(data_dir, "lombok"); + let repo = ide_sdk::apply::maven_local_repository(root, settings); + // Detection may read the project's sources. + let lombok = ide_sdk::lombok::lombok_agent(root, own, managed, repo); + info.hints.extend(lombok.problem()); + } +} + /// With Settings › Maven › Delegate IDE build/run actions to Maven, javac's verdict replaces /// JDT's. Classes JDT wrote for sources with errors look up to date to Maven's incremental /// compiler, so a launch JDT reports errors for recompiles everything. @@ -374,6 +496,21 @@ fn use_snapshot_on( copies } +/// The debug adapter for the JVMs of `module`: `java-debug` inside jdtls, or `java-analyzer` +/// (`java-analyzer dap`) when jdtls doesn't serve the module and java-analyzer does. +#[command(trust = trusted)] +pub fn java_debug_adapter(host: &Host, window: &str, module: PathBuf) -> IdeResult { + let project = host.project(window)?; + let module = project.root.join(module); + let lsp = &project.lsp; + Ok(if !lsp.java_served_by_jdtls(&module) && lsp.java_analyzer_binary(&module).is_some() { + ide_dap::adapter::JAVA_ANALYZER + } else { + "java-debug" + } + .to_owned()) +} + /// Port of java-debug's DAP server inside the jdtls serving `module` (started on demand). #[command(trust = trusted)] pub async fn java_debug_server(host: &Host, window: &str, module: PathBuf) -> IdeResult { @@ -671,4 +808,4 @@ mod tests { } } -ide_command::domain!(java: java_build_workspace, java_debug_server, java_resolve_launch); +ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch); diff --git a/crates/ide-lsp/src/java_project.rs b/crates/ide-lsp/src/java_project.rs new file mode 100644 index 000000000..9df24db65 --- /dev/null +++ b/crates/ide-lsp/src/java_project.rs @@ -0,0 +1,142 @@ +//! Java project queries for launches when jdtls does not serve the module: another Java +//! language server (java-analyzer) answers the classpath and JDK, if it supports it. + +use crate::LspManager; +use crate::jdtls::{JavaClasspath, SERVER as JDTLS}; +use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// `{ uri, scope: "runtime" | "test" }` → `{ projectRoot, classPaths, modulePaths, jdkHome }`. +const CLASSPATH: &str = "java-analyzer/projectClasspath"; +/// Waiting for the server to start and import the project. +const READY_TIMEOUT: Duration = Duration::from_secs(120); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); + +/// Classpath and JDK of a module, as a Java language server other than jdtls computes them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ServerClasspath { + pub classpath: JavaClasspath, + pub jdk_home: Option, +} + +impl LspManager { + /// Whether jdtls serves the Java files of `path`. Without it, launches build with the + /// build tool and take the classpath from [`Self::java_server_classpath`] or the build model. + pub fn java_served_by_jdtls(&self, path: &Path) -> bool { + self.servers_for(&LanguageId::new("java"), path).iter().any(|s| s.name == JDTLS) + } + + /// The java-analyzer executable among the Java servers of `path`, whatever the server is + /// named in settings: its `dap` subcommand debugs modules jdtls doesn't serve. + pub fn java_analyzer_binary(&self, path: &Path) -> Option { + self.servers_for(&LanguageId::new("java"), path).into_iter().find_map(|s| { + let binary = s.resolved_binary.read().clone().unwrap_or_else(|| s.effective_config().command.into()); + is_java_analyzer(&binary).then_some(binary) + }) + } + + /// Runtime (`test == false`) or test classpath of the module at `path` from the first + /// Java server other than jdtls. `None` when there is none or it doesn't support the query. + pub async fn java_server_classpath( + &self, + path: &Path, + test: bool, + cancel: &CancellationToken, + ) -> IdeResult> { + let Some(server) = + self.servers_for(&LanguageId::new("java"), path).into_iter().find(|s| s.name != JDTLS && !s.gave_up()) + else { + return Ok(None); + }; + self.ensure_started(&server); + let Some(run) = crate::jdtls::cancellable_wait(cancel, server.wait_ready(READY_TIMEOUT)).await? else { + tracing::debug!(server = server.name, "Java server not ready; no classpath from it"); + return Ok(None); + }; + let params = json!({ + "uri": crate::uri::path_to_uri_string(path), + "scope": if test { "test" } else { "runtime" }, + }); + let request = run.peer.request::(CLASSPATH, params, Some(cancel.clone())); + match tokio::time::timeout(REQUEST_TIMEOUT, request).await { + Ok(Ok(v)) => Ok(parse(&v)), + Ok(Err(ide_jsonrpc::RpcError::Server { code: ide_jsonrpc::codes::METHOD_NOT_FOUND, .. })) => Ok(None), + Ok(Err(e)) if cancel.is_cancelled() => { + tracing::debug!("{CLASSPATH}: {e}"); + Err(IdeError::cancelled()) + } + Ok(Err(e)) => Err(crate::rpc_err(&server.name, CLASSPATH, e)), + Err(_) => Err(IdeError::unavailable(format!( + "{}: {CLASSPATH} timed out after {} s", + server.name, + REQUEST_TIMEOUT.as_secs() + ))), + } + } +} + +/// `None` for a `null` answer (the server has no module for the path). +fn parse(v: &Value) -> Option { + if v.is_null() { + return None; + } + let strings = |key: &str| -> Vec { + v.get(key) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect()) + .unwrap_or_default() + }; + let path = |key: &str| v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(PathBuf::from); + Some(ServerClasspath { + classpath: JavaClasspath { + project_root: path("projectRoot").map(Into::into), + class_paths: strings("classPaths"), + module_paths: strings("modulePaths"), + }, + jdk_home: path("jdkHome"), + }) +} + +/// `java-analyzer` or `java-analyzer.exe`, wherever it is installed. +fn is_java_analyzer(binary: &Path) -> bool { + binary.file_stem().is_some_and(|stem| stem == "java-analyzer") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognises_java_analyzer_by_its_executable() { + assert!(is_java_analyzer(Path::new("/src/java-analyzer/target/release/java-analyzer"))); + assert!(is_java_analyzer(Path::new("java-analyzer"))); + assert!(is_java_analyzer(Path::new("/tools/java-analyzer.exe"))); + assert!(!is_java_analyzer(Path::new("/opt/jdtls/bin/jdtls"))); + assert!(!is_java_analyzer(Path::new("/opt/java-analyzer/bin/start.sh"))); + } + + #[test] + fn parses_a_classpath_answer() { + let v = json!({ + "projectRoot": "/p/app", + "classPaths": ["/p/app/target/classes", "/m2/a.jar"], + "modulePaths": [], + "outputDirs": ["/p/app/target/classes"], + "jdkHome": "/jdk", + "languageLevel": 17, + }); + let cp = parse(&v).unwrap(); + assert_eq!(cp.classpath.class_paths, ["/p/app/target/classes", "/m2/a.jar"]); + assert!(cp.classpath.module_paths.is_empty()); + assert_eq!(cp.classpath.project_root, Some(PathBuf::from("/p/app").into())); + assert_eq!(cp.jdk_home, Some(PathBuf::from("/jdk"))); + } + + #[test] + fn a_null_answer_has_no_classpath() { + assert_eq!(parse(&Value::Null), None); + assert_eq!(parse(&json!({ "classPaths": [], "jdkHome": "" })).unwrap().jdk_home, None); + } +} diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index a7294c18e..0c2e37293 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -523,7 +523,10 @@ fn missing_bundle(e: &IdeError) -> bool { } /// Cancel local waits without interrupting a shared server's startup or import. -async fn cancellable_wait(cancel: &CancellationToken, wait: impl std::future::Future) -> IdeResult { +pub(crate) async fn cancellable_wait( + cancel: &CancellationToken, + wait: impl std::future::Future, +) -> IdeResult { tokio::select! { biased; _ = cancel.cancelled() => Err(IdeError::cancelled()), diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index a6871ca0c..2e3052090 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -20,6 +20,7 @@ mod go_scope; mod handler; mod injections; mod inspect; +pub mod java_project; pub mod jdtls; mod kotlin_lsp; mod launch; diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 2890cbe4c..d4f9dfc62 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -298,6 +298,7 @@ index_file_extensions always project_host bin index_status always project_host bindings sync inspect_code trusted project_host bindings async java_build_workspace trusted project_host bindings async +java_debug_adapter trusted project_host bindings sync java_debug_server trusted project_host bindings async java_resolve_launch trusted project_host bindings async jdk_download always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 956c7e203..de41cc2fa 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -718,6 +718,11 @@ export const commands = { inspectCode: (request: RequestId, scope: SearchScope, onEvent: Channel) => typedError(__TAURI_INVOKE("inspect_code", { request, scope, onEvent })), /** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */ javaBuildWorkspace: (module: string, request: number | null) => typedError(__TAURI_INVOKE("java_build_workspace", { module, request })), + /** + * The debug adapter for the JVMs of `module`: `java-debug` inside jdtls, or `java-analyzer` + * (`java-analyzer dap`) when jdtls doesn't serve the module and java-analyzer does. + */ + javaDebugAdapter: (module: string) => typedError(__TAURI_INVOKE("java_debug_adapter", { module })), /** Port of java-debug's DAP server inside the jdtls serving `module` (started on demand). */ javaDebugServer: (module: string) => typedError(__TAURI_INVOKE("java_debug_server", { module })), /** diff --git a/src/editor/lsp/features.test.ts b/src/editor/lsp/features.test.ts index 37366cd84..e979aff2e 100644 --- a/src/editor/lsp/features.test.ts +++ b/src/editor/lsp/features.test.ts @@ -40,7 +40,7 @@ describe("semanticRanges", () => { expect(semanticRanges(doc, input, false, "python")[0]?.className).toBe( "cm-sem-function cm-sem-builtin cm-sem-python-builtin", ); - expect(semanticRanges(doc, input, false, "java")[0]?.className).toBe("cm-sem-function cm-sem-builtin"); + expect(semanticRanges(doc, input, false, "typescript")[0]?.className).toBe("cm-sem-function cm-sem-builtin"); }); it("ignores type and modifier names that only exist on Object.prototype", () => { diff --git a/src/editor/lsp/semantic/index.ts b/src/editor/lsp/semantic/index.ts index e8ed6f1d3..a6b3a897d 100644 --- a/src/editor/lsp/semantic/index.ts +++ b/src/editor/lsp/semantic/index.ts @@ -30,6 +30,7 @@ import "./kotlin"; import "./python"; import "./php"; import "./go"; +import "./java"; const semanticBackoff = featureBackoff(); diff --git a/src/editor/lsp/semantic/java/index.test.ts b/src/editor/lsp/semantic/java/index.test.ts new file mode 100644 index 000000000..09d3c42e1 --- /dev/null +++ b/src/editor/lsp/semantic/java/index.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { Text } from "@codemirror/state"; +import { semanticRanges } from "../index"; + +const doc = Text.of(["name"]); +const token = (type: string, modifiers: string[], language: string) => + semanticRanges( + doc, + { tokenTypes: [type], tokenModifiers: modifiers, data: [0, 0, 4, 0, (1 << modifiers.length) - 1] }, + false, + language, + )[0]?.className.split(" "); + +describe("Java semantic tokens", () => { + it.each([ + ["class", ["cm-sem-type"]], + ["interface", ["cm-sem-type"]], + ["method", ["cm-sem-function"]], + ])("colours JDK %s references like library and workspace ones", (type, classes) => { + expect(token(type, ["defaultLibrary"], "java")).toEqual(classes); + expect(token(type, ["defaultLibrary"], "java")).toEqual(token(type, [], "java")); + }); + + it("keeps the other modifiers of JDK symbols", () => { + expect(token("property", ["static", "defaultLibrary"], "java")?.sort()).toEqual([ + "cm-sem-property", + "cm-sem-static", + ]); + }); + + it("leaves defaultLibrary colouring to other languages", () => { + expect(token("function", ["defaultLibrary"], "python")).toContain("cm-sem-builtin"); + }); +}); diff --git a/src/editor/lsp/semantic/java/index.ts b/src/editor/lsp/semantic/java/index.ts new file mode 100644 index 000000000..94f72ee84 --- /dev/null +++ b/src/editor/lsp/semantic/java/index.ts @@ -0,0 +1,11 @@ +import { registerLanguageSemantics, type LanguageSemantics } from "../languages"; + +const javaSemantics: LanguageSemantics = { + // Java colours JDK types and calls like any other: `defaultLibrary` (sent for JDK symbols) gets no colour of its own. + tokenClasses({ classes }) { + const i = classes.indexOf("cm-sem-builtin"); + if (i >= 0) classes.splice(i, 1); + }, +}; + +registerLanguageSemantics("java", javaSemantics); diff --git a/src/features/debugger/__tests__/java.test.ts b/src/features/debugger/__tests__/java.test.ts index 157622b9a..bbe338593 100644 --- a/src/features/debugger/__tests__/java.test.ts +++ b/src/features/debugger/__tests__/java.test.ts @@ -4,6 +4,7 @@ import type { RunConfig } from "@/platform/ipc"; const invoked: Array<[string, unknown[]]> = []; let shortenCommandLine: string | null = null; let kotlinFiles = false; +let debugAdapter = "java-debug"; const files: Record = {}; let missingTools: string[] = []; vi.mock("@/platform/ipc", async (orig) => { @@ -50,6 +51,10 @@ vi.mock("@/platform/ipc", async (orig) => { hints: [], }); }, + javaDebugAdapter: (...a: unknown[]) => { + invoked.push(["javaDebugAdapter", a]); + return ok(debugAdapter); + }, javaDebugServer: (...a: unknown[]) => { invoked.push(["javaDebugServer", a]); return ok(41234); @@ -80,6 +85,7 @@ describe("Java debugging (java-debug through jdtls)", () => { invoked.length = 0; shortenCommandLine = null; kotlinFiles = false; + debugAdapter = "java-debug"; }); it("launches Application configs with the resolved classpath on jdtls' debug server", async () => { @@ -88,6 +94,7 @@ describe("Java debugging (java-debug through jdtls)", () => { const l = await javaLaunchConfig(app, "/p"); expect(invoked).toEqual([ ["javaResolveLaunch", ["api", false, "automatic", expect.any(Number)]], + ["javaDebugAdapter", ["api"]], ["javaDebugServer", ["api"]], ]); expect(l).toMatchObject({ adapter: "java-debug", request: "launch", cwd: "/p/api", args: [], env: { A: "1" } }); @@ -182,6 +189,30 @@ describe("Java debugging (java-debug through jdtls)", () => { expect(invoked.some(([command]) => command === "javaDebugServer")).toBe(false); }); + it("debugs a module jdtls doesn't serve with java-analyzer's adapter", async () => { + debugAdapter = "java-analyzer"; + const l = await javaLaunchConfig(app, "/p"); + expect(l).toMatchObject({ adapter: "java-analyzer", request: "launch", cwd: "/p/api", env: { A: "1" } }); + expect(JSON.parse(l.extraJson!)).toEqual({ + projectRoot: "/p/api", + mainClass: "a.Main", + classPaths: ["/p/target/classes", "/m2/a.jar"], + modulePaths: [], + javaExec: "/jdk21/bin/java", + vmArgs: ["-Xmx1g"], + args: ["--port", "8081 x"], + }); + const a = await javaAttachConfig({ name: "mvn test", module: "api", hostName: "remote", port: 5005 }, "/p"); + expect(a).toMatchObject({ adapter: "java-analyzer", request: "attach", cwd: "/p/api" }); + expect(JSON.parse(a.extraJson!)).toEqual({ + projectRoot: "/p/api", + hostName: "remote", + port: 5005, + timeout: 30_000, + }); + expect(invoked.some(([command]) => command === "javaDebugServer")).toBe(false); + }); + it("attaches to a JDWP agent", async () => { const l = await javaAttachConfig({ name: "mvn test", module: "", hostName: "127.0.0.1", port: 5005 }, "/p"); expect(l).toMatchObject({ request: "attach", cwd: "/p" }); diff --git a/src/features/debugger/__tests__/javaCancel.test.ts b/src/features/debugger/__tests__/javaCancel.test.ts index 5c77ce6de..86f8fa7e4 100644 --- a/src/features/debugger/__tests__/javaCancel.test.ts +++ b/src/features/debugger/__tests__/javaCancel.test.ts @@ -9,6 +9,7 @@ import { useDebug } from "../state"; const ipc = vi.hoisted(() => ({ javaResolveLaunch: vi.fn(), cancelRequest: vi.fn(async () => undefined), + javaDebugAdapter: vi.fn(async () => ({ status: "ok", data: "java-debug" })), javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })), debugStart: vi.fn(async () => ({ status: "ok", data: 42 })), debugStop: vi.fn(async () => ({ status: "ok", data: null })), diff --git a/src/features/debugger/__tests__/javaSeparator.test.ts b/src/features/debugger/__tests__/javaSeparator.test.ts index 4673acc2a..506e22435 100644 --- a/src/features/debugger/__tests__/javaSeparator.test.ts +++ b/src/features/debugger/__tests__/javaSeparator.test.ts @@ -4,6 +4,7 @@ import { resolveJavaCommand } from "@/platform/javaLaunch"; const ipc = vi.hoisted(() => ({ javaResolveLaunch: vi.fn(), + javaDebugAdapter: vi.fn(async () => ({ status: "ok", data: "java-debug" })), javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })), fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })), })); diff --git a/src/features/debugger/__tests__/remote.test.ts b/src/features/debugger/__tests__/remote.test.ts index 9aaedc75b..83b89dc51 100644 --- a/src/features/debugger/__tests__/remote.test.ts +++ b/src/features/debugger/__tests__/remote.test.ts @@ -10,6 +10,7 @@ vi.mock("@/platform/ipc", async (orig) => { ...real, commands: { ...real.commands, + javaDebugAdapter: () => ok("java-debug"), javaDebugServer: (...a: unknown[]) => { invoked.push(["javaDebugServer", a]); return ok(41234); diff --git a/src/features/debugger/__tests__/runOrigin.test.ts b/src/features/debugger/__tests__/runOrigin.test.ts index 12fe981d1..eb22f2e6d 100644 --- a/src/features/debugger/__tests__/runOrigin.test.ts +++ b/src/features/debugger/__tests__/runOrigin.test.ts @@ -22,6 +22,7 @@ import { } from "../state"; const ipc = vi.hoisted(() => ({ + javaDebugAdapter: vi.fn(async () => ({ status: "ok", data: "java-debug" })), javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })), debugStart: vi.fn(async () => ({ status: "ok", data: 42 })), debugStop: vi.fn(async () => ({ status: "ok", data: null })), diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index 51490b484..ee984006a 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -2,7 +2,8 @@ * Java debugging through Microsoft java-debug, a jdtls bundle: jdtls starts its * DAP server (`vscode.java.startDebugSession`) and the session connects to that * port (`debugServer`). Application configurations are launched by java-debug; - * JVMs started by Maven / Gradle with a JDWP agent are attached to. + * JVMs started by Maven / Gradle with a JDWP agent are attached to. Modules that + * jdtls doesn't serve debug with java-analyzer's own adapter (`java-analyzer dap`). */ import { executeAction } from "@/platform/actions"; import { call, commands, IpcError, nextRequestId, type LaunchConfig, type RunConfig } from "@/platform/ipc"; @@ -21,6 +22,7 @@ import { withEnvFiles } from "./launch"; export const JAVA_ADAPTER = "java-debug"; export const KOTLIN_ADAPTER = "kotlin-debug-adapter"; +export const JAVA_ANALYZER_ADAPTER = "java-analyzer"; const KOTLIN_LSP = "kotlin-lsp"; export function isJavaDebuggable(rc: RunConfig): boolean { @@ -191,6 +193,27 @@ export async function javaLaunchConfig( }), }; } + if ((await call(commands.javaDebugAdapter(module))) === JAVA_ANALYZER_ADAPTER) { + preparation?.signal.throwIfAborted(); + return { + name: rc.name, + adapter: JAVA_ANALYZER_ADAPTER, + request: "launch", + program: null, + args: [], + cwd, + env: { ...rc.env }, + extraJson: JSON.stringify({ + projectRoot: join(root, module), + mainClass: parsed.mainClass, + classPaths, + modulePaths: info.modulePaths, + javaExec: resolved.command === "java" ? undefined : resolved.command, + vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs], + args: parsed.programArgs, + }), + }; + } const port = await debugServer(module, preparation?.signal); preparation?.signal.throwIfAborted(); // java-debug resolves the Java project for Evaluate on its own from `mainClass` only when @@ -252,6 +275,18 @@ export async function javaAttachConfig(target: JavaAttachTarget, root: string): extraJson: JSON.stringify({ projectRoot: cwd, hostName: target.hostName, port: target.port, timeout: 30_000 }), }; } + if ((await call(commands.javaDebugAdapter(target.module))) === JAVA_ANALYZER_ADAPTER) { + return { + name: target.name, + adapter: JAVA_ANALYZER_ADAPTER, + request: "attach", + program: null, + args: [], + cwd, + env: {}, + extraJson: JSON.stringify({ projectRoot: cwd, hostName: target.hostName, port: target.port, timeout: 30_000 }), + }; + } const port = await debugServer(target.module); // java-debug resolves the Java project for Evaluate from `mainClass` only when the class is in // a project it imported; a JDWP attach cannot even see the main class, so name the project the