Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。

插件包不带 JDT LS,也不带运行它的 JDK,和 Go 插件使用你自己的 `gopls` 一样。需要:

1. **Eclipse JDT Language Server**。按以下顺序找,用第一个:
1. **Eclipse JDT Language Server**。按以下顺序找,优先使用当前 `jdtls-runtime` 可满足其最低 Java 版本要求的安装;若都不满足则落到第一个并报出该安装所需的最低 Java 版本:
1. 设置 → 语言与框架 → Java →「语言服务器目录」。选了目录就只用它,目录里没有 JDT LS 时直接报错,不会退回别的安装;
2. 环境变量 `JDTLS_HOME`;
3. `PATH` 上的 `jdtls` 启动脚本所属的安装(沿符号链接找到真实目录);
Expand All @@ -207,9 +207,9 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。
`config_<平台>/config.ini`。安装方式举例:macOS / Linux 用 `brew install jdtls`;也可以从
[download.eclipse.org/jdtls](https://download.eclipse.org/jdtls/milestones/) 下载解压,再在设置里选目录。
已测试 JDT LS 1.61.0(CI 固定,见 `third_party/jdtls/manifest.json`)和 Homebrew 1.60.0。
2. **JDK 21 或更新版本**,用来运行 JDT LS。它是插件新增的「JDK for JDT LS」工具(`jdtls-runtime`),
在设置 → 构建、执行、部署 → 工具链里显示和选择;没选时依次用登录 shell 的 `java` 和找到的最高版本 JDK。
宿主报告的版本低于 21 时,启动直接报错并提示去工具链里选择。项目自己的 JDK 是原来的「JDK」工具(`java`),两者互不影响。
2. **满足目标 JDT LS 要求的 JDK(至少 JDK 21;JDT LS 1.63+ 要求 JDK 25)**,用来运行 JDT LS。它是插件新增的「JDK for JDT LS」工具(`jdtls-runtime`),
在设置 → 构建、执行、部署 → 工具链里显示和选择;没选时依次用登录 shell 的 `java`(仅匹配 21 及更新版本,跳过 `PATH` 上的 Java 8/11/17)和找到的最高版本 JDK(含系统 JDK 目录与 VS Code / Cursor `redhat.java` 扩展自带的 `jre/`)。
后端会从目标 JDT LS 核心 bundle 的 `MANIFEST.MF`(`Bundle-RequiredExecutionEnvironment`)读取实际最低 Java 版本,低于该版本时启动直接报错并提示去工具链里选择。项目自己的 JDK 是原来的「JDK」工具(`java`),两者互不影响。
JDT 只能为它支持的 Java 版本编译:没有为项目选 JDK 时,JDT 用运行它的 JDK 编译,这个 JDK 比 JDT LS 支持的最新 Java 还新时编译会报错。

找不到 JDT LS 时,语言服务启动失败(`launch.server_missing`),错误信息说明如何安装或去哪里设置。
Expand Down Expand Up @@ -245,7 +245,7 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。
| 其余函数成功(编辑器驱动或启动时的读取,如 `java.runMarkers`、`java.codeVision`、`spring.index`) | 不记录 | `suppress_success_diagnostics`(`backend/src/lib.rs`) | — |
| 任一函数失败 | ERROR | SDK 自动 | 类别为 `pluginErrorCode`(如 `java.invalidRequest`;`languageImport.settingsChanged` 的 `relay.caller_missing`、`relay.context_missing`、`relay.invalid_params`)、耗时;不含消息与 `details` |
| 领域命令失败类别 | ERROR | `plugin_error_code` | `java.invalidRequest`、`java.workspaceNotFound`、`java.permissionDenied`、`java.notSupported`、`java.runtimeMissing`、`java.processStartFailed`、`java.processFailed`、`java.parseFailed`、`java.cancelled`、`java.timedOut`、`java.connectionClosed`、`java.unknown`;SDK 识别的取消不记录 |
| JDT 启动规划失败 | ERROR | SDK 自动 | `launch.invalid_params`、`launch.package_unavailable`、`launch.resource_missing`、`launch.configuration_failed`、`launch.server_missing`(找不到 JDT LS)、`launch.server_invalid`(设置的目录不是 JDT LS)、`launch.runtime_too_old`(运行 JDT LS 的 JDK 低于 21) |
| JDT 启动规划失败 | ERROR | SDK 自动 | `launch.invalid_params`、`launch.package_unavailable`、`launch.resource_missing`、`launch.configuration_failed`、`launch.server_missing`(找不到 JDT LS)、`launch.server_invalid`(设置的目录不是 JDT LS)、`launch.runtime_too_old`(运行 JDT LS 的 JDK 低于目标 JDT LS 要求的最低版本,至少 21) |
| JDT 配置清理或工作区读取降级 | WARN | SDK `degraded` | `launch.configuration_cleanup_failed`、`launch.workspace_folders_unavailable` |
| 取消 | 不记录 | SDK | — |
| 列出 `languageImport.settings` 提供方失败、单个提供方失败或超时、答复不可用、答复含越界键、提供方导出的函数版本不符 | WARN(`degraded`) | `backend/src/plugin_functions.rs` | 类别 `relay.providers_unavailable`、`relay.provider_failed`、`relay.provider_timed_out`、`relay.settings_rejected`、`relay.keys_rejected`、`relay.provider_version_mismatch`,计数;不含提供方 ID |
Expand Down
201 changes: 195 additions & 6 deletions backend/src/jdtls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,22 @@

use lithe_plugin_sdk::PluginError;
use std::ffi::OsString;
use std::fs;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use zip::ZipArchive;

/// Oldest Java feature release any JDT LS installation runs on.
pub const DEFAULT_MINIMUM_JAVA_VERSION: u64 = 21;
/// Core OSGi bundles whose `META-INF/MANIFEST.MF` declares the Java release
/// an installation requires (for example `JavaSE-25` in JDT LS 1.63+).
const CORE_RUNTIME_BUNDLE_PREFIXES: &[&str] = &[
"org.eclipse.jdt.ls.core_",
"org.eclipse.jdt.core_",
"org.eclipse.core.resources_",
"org.eclipse.core.filesystem_",
"org.eclipse.equinox.common_",
];

/// No JDT LS installation was found on the machine.
pub const LAUNCH_SERVER_MISSING: &str = "launch.server_missing";
Expand Down Expand Up @@ -95,6 +109,9 @@ pub struct ServerInstallation {
/// The read-only Equinox configuration of the platform; the launch uses a
/// writable copy of it.
pub configuration: PathBuf,
/// Oldest Java feature release the bundles of this installation require,
/// at least [`DEFAULT_MINIMUM_JAVA_VERSION`].
pub minimum_java_version: u64,
}

/// What [`locate`] reads from the backend's process environment, so tests
Expand Down Expand Up @@ -156,18 +173,88 @@ fn installation_at(home: &Path, configuration: &str) -> Option<ServerInstallatio
// Java cannot load `-jar` or `-javaagent` through a Windows verbatim
// prefix, so the paths keep their ordinary spelling.
let home = dunce::canonicalize(home).ok()?;
let launcher_jar = launcher_in(&home.join(PLUGINS_DIRECTORY))?;
let plugins = home.join(PLUGINS_DIRECTORY);
let launcher_jar = launcher_in(&plugins)?;
let configuration = home.join(configuration);
if !configuration.join(CONFIG_INI).is_file() {
return None;
}
let minimum_java_version = required_java_version(&plugins);
Some(ServerInstallation {
home,
launcher_jar,
configuration,
minimum_java_version,
})
}

/// Oldest Java feature release the core OSGi bundles in `plugins` declare,
/// floored at [`DEFAULT_MINIMUM_JAVA_VERSION`]. Unreadable or synthetic JARs
/// keep the floor.
pub fn required_java_version(plugins: &Path) -> u64 {
let Ok(entries) = fs::read_dir(plugins) else {
return DEFAULT_MINIMUM_JAVA_VERSION;
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
let path = entry.path();
let name = path.file_name()?.to_str()?;
if !name.ends_with(".jar")
|| !CORE_RUNTIME_BUNDLE_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
{
return None;
}
bundle_java_version(&path)
})
.fold(DEFAULT_MINIMUM_JAVA_VERSION, u64::max)
}

fn bundle_java_version(jar_path: &Path) -> Option<u64> {
let file = File::open(jar_path).ok()?;
let mut archive = ZipArchive::new(file).ok()?;
let entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
let mut manifest = String::new();
entry.take(256 * 1024).read_to_string(&mut manifest).ok()?;
manifest_java_version(&manifest)
}

/// Extracts the highest Java feature version declared in an OSGi
/// `META-INF/MANIFEST.MF` (`Bundle-RequiredExecutionEnvironment: JavaSE-25` or
/// `Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=25))"`).
pub fn manifest_java_version(manifest: &str) -> Option<u64> {
let unfolded = manifest.replace("\r\n ", "").replace("\n ", "");
let mut highest = None;
for line in unfolded.lines() {
let trimmed = line.trim();
if !trimmed.starts_with("Bundle-RequiredExecutionEnvironment:")
&& !trimmed.starts_with("Require-Capability:")
{
continue;
}
for marker in ["JavaSE-", "(version="] {
let mut rest = trimmed;
while let Some(index) = rest.find(marker) {
rest = &rest[index + marker.len()..];
let digits: String = rest
.chars()
.take_while(|character| character.is_ascii_digit())
.collect();
// `JavaSE-1.8` has a dot after `1`; only feature releases >= 9 count.
if rest.as_bytes().get(digits.len()) == Some(&b'.') && digits == "1" {
continue;
}
if let Ok(version) = digits.parse::<u64>() {
highest = Some(highest.map_or(version, |current: u64| current.max(version)));
}
}
}
}
highest
}

/// The one Equinox launcher JAR in `directory`. None or several mean the
/// folder is no usable installation.
fn launcher_in(directory: &Path) -> Option<PathBuf> {
Expand Down Expand Up @@ -199,17 +286,41 @@ pub fn locate(
environment: &SearchEnvironment,
os: &str,
arch: &str,
) -> Result<ServerInstallation, PluginError> {
locate_for_runtime(configured, environment, os, arch, None)
}

/// Finds the JDT LS installation for `os` and `arch`, preferring a discovered
/// installation whose required Java release is at most `runtime_java_version`
/// when `configured` is `None`. When no discovered installation can run on
/// `runtime_java_version`, the first installation found is returned so the
/// caller reports the Java version that installation requires.
pub fn locate_for_runtime(
configured: Option<&Path>,
environment: &SearchEnvironment,
os: &str,
arch: &str,
runtime_java_version: Option<u64>,
) -> Result<ServerInstallation, PluginError> {
let configuration = configuration_name(os, arch)
.ok_or_else(|| PluginError::new(LAUNCH_SERVER_MISSING, SERVER_MISSING_MESSAGE))?;
if let Some(folder) = configured {
return inspect(folder, configuration)
.ok_or_else(|| PluginError::new(LAUNCH_SERVER_INVALID, SERVER_INVALID_MESSAGE));
}
candidates(environment, os)
.iter()
.find_map(|folder| inspect(folder, configuration))
.ok_or_else(|| PluginError::new(LAUNCH_SERVER_MISSING, SERVER_MISSING_MESSAGE))
let mut first = None;
for folder in candidates(environment, os) {
let Some(installation) = inspect(&folder, configuration) else {
continue;
};
if runtime_java_version.is_none_or(|feature| installation.minimum_java_version <= feature) {
return Ok(installation);
}
if first.is_none() {
first = Some(installation);
}
}
first.ok_or_else(|| PluginError::new(LAUNCH_SERVER_MISSING, SERVER_MISSING_MESSAGE))
}

/// The folders [`locate`] tries without a configured one, in order. A folder
Expand Down Expand Up @@ -511,4 +622,82 @@ mod tests {
assert!(folders.contains(&temp.0.join("scoop/apps/jdtls/current")));
assert!(!folders.contains(&PathBuf::from("/opt/homebrew/opt/jdtls")));
}

fn write_bundle_manifest(jar_path: &Path, manifest: &str) {
use std::io::Write;
let file = File::create(jar_path).unwrap();
let mut zip = zip::ZipWriter::new(file);
zip.start_file(
"META-INF/MANIFEST.MF",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(manifest.as_bytes()).unwrap();
zip.finish().unwrap();
}

#[test]
fn bundle_manifests_report_the_java_release_the_installation_requires() {
assert_eq!(
manifest_java_version(
"Manifest-Version: 1.0\r\nBundle-RequiredExecutionEnvironment: JavaSE-1.8\r\n"
),
None
);
assert_eq!(
manifest_java_version(
"Manifest-Version: 1.0\r\nBundle-RequiredExecutionEnvironment: JavaSE-25\r\n"
),
Some(25)
);
assert_eq!(
manifest_java_version(
"Require-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=\r\n 21))\"\r\n"
),
Some(21)
);

let temp = TempDir::new();
let modern = temp.0.join(".vscode/extensions/redhat.java-1.58.0/server");
install(&modern, &["config_win"]);
write_bundle_manifest(
&modern.join("plugins/org.eclipse.core.filesystem_1.12.0.jar"),
"Manifest-Version: 1.0\nBundle-RequiredExecutionEnvironment: JavaSE-25\n",
);
let legacy = temp.0.join(".vscode/extensions/redhat.java-1.47.0/server");
install(&legacy, &["config_win"]);
write_bundle_manifest(
&legacy.join("plugins/org.eclipse.jdt.ls.core_1.61.0.jar"),
"Manifest-Version: 1.0\nRequire-Capability: osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=21))\"\n",
);

assert_eq!(
inspect(&modern, "config_win").unwrap().minimum_java_version,
25
);
assert_eq!(
inspect(&legacy, "config_win").unwrap().minimum_java_version,
21
);

// On JDK 21, automatic discovery skips the Java-25 server and picks
// the Java-21 server; on JDK 25, the newest server wins; on JDK 17,
// the first installation is returned so the caller reports its requirement.
let search = environment(&temp.0);
assert_eq!(
locate_for_runtime(None, &search, "windows", "x86_64", Some(21))
.unwrap()
.home,
legacy
);
assert_eq!(
locate_for_runtime(None, &search, "windows", "x86_64", Some(25))
.unwrap()
.home,
modern
);
let fallback = locate_for_runtime(None, &search, "windows", "x86_64", Some(17)).unwrap();
assert_eq!(fallback.home, modern);
assert_eq!(fallback.minimum_java_version, 25);
}
}
Loading
Loading