fix(kotlin): open jdtls' class when the Kotlin server names its jar by another path (#3922)

Going to a library class from Kotlin swaps the Kotlin server's signature stub for jdtls' decompiled class, matched by package, name and the jar's path. When the servers know the jar by different paths (a system-scope jar, as reported), nothing matched and the stub stayed. The redirect now takes jdtls' only class of that name and logs why when it still finds none; java_class_file keeps the exact-archive match for debugger line mapping. Refs #3447
This commit is contained in:
l0ng-ai
2026-11-17 14:55:12 +08:00
committed by GitHub
parent 3663556a2e
commit af55109b27
3 changed files with 100 additions and 30 deletions
+27 -25
View File
@@ -1025,36 +1025,38 @@ impl LspManager {
.map_err(|e| IdeError::internal(e.to_string()))
}
/// jdtls' document for class file `entry` of archive `jar`, from its Java model. With
/// `any_archive`, the one class of that name the model has when it knows `jar` by another path.
pub(crate) async fn archive_class(&self, jar: PathBuf, entry: String, any_archive: bool) -> IdeResult<String> {
let cancel = CancellationToken::new();
self.jdtls(&self.project_root, &cancel).await?;
let entry =
entry.strip_prefix("META-INF/versions/").and_then(|s| s.split_once('/').map(|(_, s)| s)).unwrap_or(&entry);
let class = entry.strip_suffix(".class").ok_or_else(|| IdeError::not_found("expected a class file"))?;
let outer = class.split('$').next().unwrap_or(class);
let (package, name) = outer.rsplit_once('/').unwrap_or(("", outer));
let query = outer.replace('/', ".");
let symbols = self.workspace_symbols(&query, cancel).await?;
let package = package.replace('/', ".");
let name = name.to_owned();
let outer = outer.to_owned();
tokio::task::spawn_blocking(move || {
let uris = symbols.into_iter().filter_map(|s| s.location.uri);
crate::virtual_doc::pick_class(uris, &jar, &package, &name, any_archive)
.ok_or_else(|| IdeError::not_found(format!("jdtls could not resolve {} in {}", outer, jar.display())))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Resolve a disk/archive class to project source or the server's binary document.
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
if let Some((jar, entry)) = archive {
return self.archive_class(jar, entry, false).await;
}
let cancel = CancellationToken::new();
self.jdtls(&self.project_root, &cancel).await?;
if let Some((jar, entry)) = archive {
let entry = entry
.strip_prefix("META-INF/versions/")
.and_then(|s| s.split_once('/').map(|(_, s)| s))
.unwrap_or(&entry);
let class = entry.strip_suffix(".class").ok_or_else(|| IdeError::not_found("expected a class file"))?;
let outer = class.split('$').next().unwrap_or(class);
let (package, name) = outer.rsplit_once('/').unwrap_or(("", outer));
let query = outer.replace('/', ".");
let symbols = self.workspace_symbols(&query, cancel).await?;
let package = package.replace('/', ".");
let name = name.to_owned();
let outer = outer.to_owned();
return tokio::task::spawn_blocking(move || {
symbols
.into_iter()
.filter_map(|s| s.location.uri)
.find(|uri| crate::virtual_doc::matches_class(uri, &jar, &package, &name))
.ok_or_else(|| {
IdeError::not_found(format!("jdtls could not resolve {} in {}", outer, jar.display()))
})
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let uri = crate::uri::path_to_uri_string(path);
// classFileContents accepts file URIs, but java-debug's line mapping only accepts JDT handles.
let doc = self.virtual_document(&uri).await?;
+10 -3
View File
@@ -1811,9 +1811,16 @@ impl LspManager {
out.push(loc);
continue;
};
let Ok(uri) = self.java_class_file(Path::new(""), Some((entry.jar, entry.entry))).await else {
out.push(loc);
continue;
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
}
};
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
+63 -2
View File
@@ -197,12 +197,17 @@ pub(crate) fn archive_modified(uri: &str) -> Option<std::time::SystemTime> {
std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok()
}
/// Check both the package and actual archive, so duplicate type names never pick another jar.
pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool {
/// Whether `uri` is jdtls' class `package.name`, in any archive.
pub(crate) fn matches_class_name(uri: &str, package: &str, name: &str) -> bool {
let segs = segments(uri);
scheme(uri) == "jdt"
&& (package.is_empty() && segs.len() == 3 || segs.get(2).is_some_and(|s| s == package))
&& segs.last().is_some_and(|s| s == &format!("{name}.class") || s == &format!("{name}.java"))
}
/// Check both the package and actual archive, so duplicate type names never pick another jar.
pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool {
matches_class_name(uri, package, name)
&& description(uri).is_some_and(|p| {
let path = std::path::Path::new(&p);
path == jar
@@ -210,12 +215,68 @@ pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, nam
})
}
/// jdtls' document for class `package.name` of archive `jar` among `uris`. With `any_archive`,
/// when the caller names the archive by another path than the Java model does (a copy another
/// server made of a `system`-scope jar, say), the one class of that name in the model; with
/// several, none rather than another jar's.
pub(crate) fn pick_class(
uris: impl IntoIterator<Item = String>,
jar: &std::path::Path,
package: &str,
name: &str,
any_archive: bool,
) -> Option<String> {
let named: Vec<String> = uris.into_iter().filter(|uri| matches_class_name(uri, package, name)).collect();
if let Some(uri) = named.iter().find(|uri| matches_class(uri, jar, package, name)) {
return Some(uri.clone());
}
match named.as_slice() {
[only] if any_archive => Some(only.clone()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
#[test]
fn picks_the_class_of_the_archive_or_the_only_one_of_that_name() {
let jdt = |jar: &str, file: &str| {
format!(
"jdt://contents/{file}/org.springframework.boot/SpringApplication.class?=demo/%5C/repo%5C/{jar}%3Corg.springframework.boot%28SpringApplication.class"
)
};
let (a, b) = (jdt("a.jar", "a.jar"), jdt("b.jar", "b.jar"));
let pick = |uris: &[&String], jar: &str| {
pick_class(
uris.iter().map(|u| (*u).clone()),
std::path::Path::new(jar),
"org.springframework.boot",
"SpringApplication",
true,
)
};
assert_eq!(pick(&[&a, &b], "/repo/b.jar"), Some(b.clone()));
// Another path for the archive: the only class of that name.
assert_eq!(pick(&[&a], "/elsewhere/copy.jar"), Some(a.clone()));
// Two candidates and neither archive matches: none rather than a guess.
assert_eq!(pick(&[&a, &b], "/elsewhere/copy.jar"), None);
let other = JDT.replace("SpringApplication.class", "Banner.class");
assert_eq!(pick(&[&other], "/elsewhere/copy.jar"), None);
// Strict: only the named archive.
let strict = pick_class(
[a.clone()],
std::path::Path::new("/elsewhere/copy.jar"),
"org.springframework.boot",
"SpringApplication",
false,
);
assert_eq!(strict, None);
}
#[test]
fn class_stubs_in_java_or_kotlin() {
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";