дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ea7c9b354d |
No files matched your search
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
|
||||
@@ -929,9 +929,14 @@ pub async fn lsp_library_sources(
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
|
||||
// Opens compiled classes through JDT as decompiled class documents.
|
||||
let archive = ide_vfs::split_archive_path(&path);
|
||||
host.project(window)?.lsp.java_class_file(&path, archive).await
|
||||
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
|
||||
}
|
||||
|
||||
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
|
||||
let bytes = tokio::fs::read(path).await?;
|
||||
ide_build::jbuild::class_file_name(&bytes)
|
||||
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
@@ -2492,6 +2497,18 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[tokio::test]
|
||||
async fn disk_class_name_comes_from_bytecode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("moved.class");
|
||||
// Class header, UTF-8 and Class constants, then access_flags and this_class.
|
||||
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
|
||||
std::fs::write(&path, b"invalid").unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
|
||||
use super::*;
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
//! 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.
|
||||
//! Java project queries and class-file navigation for servers other than jdtls.
|
||||
|
||||
use crate::LspManager;
|
||||
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);
|
||||
@@ -37,6 +38,54 @@ impl LspManager {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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(
|
||||
@@ -77,6 +126,24 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[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() {
|
||||
|
||||
@@ -1257,7 +1257,7 @@ impl LspManager {
|
||||
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
|
||||
/// A class in an output directory opens as itself even when its project source exists:
|
||||
/// the user asked for the compiled class, not the file it was built from.
|
||||
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
|
||||
pub(crate) async fn jdtls_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;
|
||||
}
|
||||
|
||||
@@ -5770,7 +5770,12 @@ async fn jar_library_sources_reload_with_another_encoding() {
|
||||
async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["workspaceSymbolProvider"] = json!(true);
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let h = harness_for(
|
||||
"java",
|
||||
"java",
|
||||
&[("jdtls", caps), ("java-analyzer", json!({"experimental":{"java-analyzer/classFile":true}}))],
|
||||
&[],
|
||||
);
|
||||
h.open("App.java", "class App {}\n");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
@@ -5779,12 +5784,17 @@ async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
{"name":"Outer", "kind":5, "location":{"uri":jdt,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":0}}}}
|
||||
]));
|
||||
let archive = Some((PathBuf::from("/m2/lib.jar"), "p/Outer$1.class".into()));
|
||||
assert_eq!(h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive).await.unwrap(), jdt);
|
||||
let unused_name = || async { panic!("jdtls does not need the internal class name") };
|
||||
assert_eq!(
|
||||
h.mgr.java_class_file(Path::new("/m2/lib.jar!/p/Outer$1.class"), archive, unused_name()).await.unwrap(),
|
||||
jdt
|
||||
);
|
||||
assert!(
|
||||
h.mgr
|
||||
.java_class_file(
|
||||
Path::new("/other/lib.jar!/p/Outer.class"),
|
||||
Some(("/other/lib.jar".into(), "p/Outer.class".into()))
|
||||
Some(("/other/lib.jar".into(), "p/Outer.class".into())),
|
||||
unused_name(),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
@@ -5797,16 +5807,71 @@ async fn class_file_opening_routes_archive_and_output_classes() {
|
||||
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
|
||||
for class in ["Outer", "Outer$Nested", "Outer$1"] {
|
||||
let path = h.root.join(format!("target/classes/p/{class}.class"));
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri_of(&path));
|
||||
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri_of(&path));
|
||||
}
|
||||
let path = h.root.join("build/classes/java/main/p/Missing.class");
|
||||
let uri = uri_of(&path);
|
||||
assert_eq!(h.mgr.java_class_file(&path, None).await.unwrap(), uri);
|
||||
assert_eq!(h.mgr.java_class_file(&path, None, unused_name()).await.unwrap(), uri);
|
||||
let vd = h.mgr.virtual_document(&uri).await.unwrap();
|
||||
assert!(vd.decompiled);
|
||||
assert_eq!(vd.language_id.as_str(), "java");
|
||||
assert_eq!(vd.title, "Missing.class");
|
||||
assert!(s.requested("java/classFileContents").iter().any(|p| p["uri"] == uri));
|
||||
assert!(h.launcher.state("java-analyzer").requested("java-analyzer/classFile").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn class_file_opening_starts_java_analyzer_for_archive_classes() {
|
||||
const METHOD: &str = "java-analyzer/classFile";
|
||||
for with_jdtls in [false, true] {
|
||||
let mut servers = vec![("java-analyzer", json!({"experimental":{METHOD:true}}))];
|
||||
if with_jdtls {
|
||||
servers.insert(0, ("jdtls", incremental_caps()));
|
||||
}
|
||||
let h = harness_for("java", "java", &servers, &["java-analyzer"]);
|
||||
h.launcher.state("jdtls").missing.store(true, Ordering::SeqCst);
|
||||
let server = h.launcher.state("java-analyzer");
|
||||
let source = h.root.join("cache with spaces/p/Outer.java");
|
||||
server.respond(METHOD, json!({"uri":uri_of(&source)}));
|
||||
let archive = h.root.join("external Maven cache/lib.jar");
|
||||
let entry = "META-INF/versions/17/p/Outer$Inner.class";
|
||||
let path = PathBuf::from(format!("{}!/{entry}", archive.display()));
|
||||
let opened = h
|
||||
.mgr
|
||||
.java_class_file(&path, Some((archive.clone(), entry.into())), async {
|
||||
panic!("archive entries do not need the internal class name")
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(Path::new(&opened), source);
|
||||
assert_eq!(server.requested(METHOD), [json!({"archive":uri_of(&archive), "entry":entry})]);
|
||||
assert!(server.requested("workspace/textDocumentContent").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn class_file_opening_routes_disk_classes_by_internal_name() {
|
||||
const METHOD: &str = "java-analyzer/classFile";
|
||||
let h = harness_for("java", "java", &[("java-analyzer", json!({"experimental":{METHOD:true}}))], &[]);
|
||||
let server = h.launcher.state("java-analyzer");
|
||||
let source = h.root.join("src/main/java/p/Outer.java");
|
||||
server.respond(METHOD, json!({"uri":uri_of(&source)}));
|
||||
let output = h.root.join("target/classes");
|
||||
let class = output.join("p/Outer$Inner.class");
|
||||
let moved = h.root.join("moved.class");
|
||||
let internal_name = || async { Ok("p/Outer$Inner".into()) };
|
||||
for path in [&class, &moved] {
|
||||
assert_eq!(Path::new(&h.mgr.java_class_file(path, None, internal_name()).await.unwrap()), source);
|
||||
}
|
||||
assert_eq!(
|
||||
server.requested(METHOD),
|
||||
[json!({"archive":uri_of(&output), "entry":"p/Outer$Inner.class"}), json!({"binaryName":"p.Outer$Inner"})]
|
||||
);
|
||||
server.respond(METHOD, Value::Null);
|
||||
assert_eq!(
|
||||
h.mgr.java_class_file(&class, None, internal_name()).await.unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::NotFound
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
Reference in new issue
Заблокувати користувача