Файли
openidea/crates/ide-lsp/src/java_project.rs
T
l0ng-ai 7668e4a5ba fix(java): open library classes through java-analyzer when it is the Java server (#7234)
Opening a class from a jar in Project › External Libraries always went through jdtls, so with java-analyzer as the Java server it failed with "no Java language server (jdtls) is configured". When the server advertises java-analyzer/classFile, the class is resolved there and opens like go to definition (attached sources, else decompiled); jdtls stays first when configured.

Fixes #7212
2026-12-01 20:27:04 +08:00

231 рядки
9.9 KiB
Rust

//! Java project queries and class-file navigation for servers other than jdtls.
use crate::jdtls::{JavaClasspath, SERVER as JDTLS};
use crate::{ErrorKind, LspManager, Target, uri};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde_json::{Value, json};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `{ uri, scope: "runtime" | "test" }` → `{ projectRoot, classPaths, modulePaths, jdkHome }`.
const CLASSPATH: &str = "java-analyzer/projectClasspath";
const CLASS_FILE: &str = "java-analyzer/classFile";
/// 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<PathBuf>,
}
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 && !s.gave_up())
}
/// 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<PathBuf> {
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)
})
}
/// Resolve a compiled class to the document that the project's Java server opens.
/// The internal name is only read for disk classes handled by a server other than jdtls.
pub async fn java_class_file(
&self,
path: &Path,
archive: Option<(PathBuf, String)>,
internal_name: impl Future<Output = IdeResult<String>>,
) -> IdeResult<String> {
if self.java_served_by_jdtls(&self.project_root) {
let result = self.jdtls_class_file(path, archive.clone()).await;
// Starting jdtls can expose a configured fallback.
if result.is_ok() || self.java_served_by_jdtls(&self.project_root) {
return result;
}
}
// Use the workspace's server for archives, which can live outside the project.
let route = if archive.is_some() { &self.project_root } else { path };
let servers: Vec<_> = self
.servers_for(&LanguageId::new("java"), route)
.into_iter()
.filter(|s| s.name != JDTLS && !s.gave_up())
.collect();
if servers.is_empty() {
return self.jdtls_class_file(path, archive).await;
}
for server in &servers {
self.ensure_started(server);
let Some(run) = server.wait_ready(READY_TIMEOUT).await else { continue };
if run.caps.read().raw["experimental"][CLASS_FILE] != true {
continue;
}
let params = match archive {
Some((jar, entry)) => json!({ "archive": uri::path_to_uri_string(&jar), "entry": entry }),
None => disk_class_params(path, &internal_name.await?),
};
let target = Target { server: server.clone(), run };
let result: Option<ClassFileDocument> =
self.call(&target, CLASS_FILE, params, None, REQUEST_TIMEOUT).await?;
let doc = result
.ok_or_else(|| IdeError::not_found(format!("{} could not resolve {}", server.name, path.display())))?;
// Go-to-definition also opens these materialized file URIs as ordinary editor paths.
return uri::uri_to_path(&doc.uri)
.map(|path| path.to_string_lossy().into_owned())
.ok_or_else(|| IdeError::new(ErrorKind::Protocol, format!("{CLASS_FILE}: expected a file URI")));
}
Err(crate::unsupported(&servers, "Java class-file resolution"))
}
/// 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<Option<ServerClasspath>> {
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::<Value, Value>(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()
))),
}
}
}
#[derive(serde::Deserialize)]
struct ClassFileDocument {
uri: String,
}
fn disk_class_params(path: &Path, name: &str) -> Value {
let entry = format!("{name}.class");
// Supplying the output directory disambiguates classes with the same name in different modules.
if path.ends_with(&entry)
&& let Some(output) = path.ancestors().nth(Path::new(&entry).components().count())
&& !output.as_os_str().is_empty()
{
json!({ "archive": uri::path_to_uri_string(output), "entry": entry })
} else {
json!({ "binaryName": name.replace('/', ".") })
}
}
/// `None` for a `null` answer (the server has no module for the path).
fn parse(v: &Value) -> Option<ServerClasspath> {
if v.is_null() {
return None;
}
let strings = |key: &str| -> Vec<String> {
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::*;
use crate::server::Conn;
use ide_core::event::ServerStatus;
use ide_language::LanguageRegistry;
use std::sync::Arc;
#[test]
fn missing_jdtls_leaves_java_analyzer_to_serve_the_module() {
let project = tempfile::tempdir().unwrap();
let root = project.path();
let manager =
LspManager::new(root.to_path_buf(), Arc::new(LanguageRegistry::load(None).unwrap()), Arc::new(|_| {}));
assert!(manager.java_served_by_jdtls(root));
assert!(manager.java_analyzer_binary(root).is_none());
let jdtls = manager.servers_for(&LanguageId::new("java"), root).into_iter().find(|s| s.name == JDTLS).unwrap();
let generation = jdtls.begin_start().unwrap();
assert!(jdtls.fail_start(generation, Conn::Missing, manager.sink(), ServerStatus::Missing, None));
assert!(!manager.java_served_by_jdtls(root));
assert_eq!(manager.java_analyzer_binary(root).as_deref(), Some(Path::new("java-analyzer")));
}
#[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);
}
}