diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cbf975b..c5e1545 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,9 +65,7 @@ jobs: - name: Restore verified third-party downloads uses: actions/cache@v4 with: - path: | - .artifacts/jdtls-downloads - .artifacts/jdk-downloads + path: .artifacts/jdtls-downloads key: third-party-${{ hashFiles('third_party/*/manifest.json') }} - name: Build, verify and archive both architectures run: | @@ -76,7 +74,13 @@ jobs: package=$(scripts/build-package.sh --arch "$arch") scripts/archive-package.sh --package "$package" --arch "$arch" done - - name: Verify native compiler settings and JARs with JDT + # The package ships no JDK; the integration tests run the tested JDT LS + # release on this one, as a user's JDK 21+ would. + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" + - name: Verify native compiler settings and JARs with the user's JDT LS run: | package=".artifacts/package/$(uname -m)/io.github.lithe-idea.java-support" node scripts/compiler/test-live.mjs "$package" @@ -118,18 +122,22 @@ jobs: node-version: 22 - name: Install packaging tools run: sudo apt-get update && sudo apt-get install -y zsh zip unzip + # The package ships no JDK; the integration tests run the tested JDT LS + # release on this one, as a user's JDK 21+ would. + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" - name: Restore checksum-verified downloads uses: actions/cache@v4 with: - path: | - .artifacts/jdtls-downloads - .artifacts/jdk-downloads + path: .artifacts/jdtls-downloads key: linux-${{ matrix.arch }}-${{ hashFiles('third_party/*/manifest.json') }} - name: Test the native backend run: cargo test --workspace --locked - name: Build and verify the archive run: node scripts/package/build-linux.mjs "${{ matrix.arch }}" - - name: Start the packaged backend and language server + - name: Start the packaged backend and the user's language server run: node scripts/package/smoke-linux.mjs dist/*-linux-${{ matrix.arch }}.zip - uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c09ba9c..2e51b99 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -171,18 +171,22 @@ jobs: node-version: 22 - name: Install packaging tools run: sudo apt-get update && sudo apt-get install -y zsh zip unzip + # The package ships no JDK; the integration tests run the tested JDT LS + # release on this one, as a user's JDK 21+ would. + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" - name: Restore checksum-verified downloads uses: actions/cache@v4 with: - path: | - .artifacts/jdtls-downloads - .artifacts/jdk-downloads + path: .artifacts/jdtls-downloads key: linux-${{ matrix.arch }}-${{ hashFiles('third_party/*/manifest.json') }} - name: Test the native backend run: cargo test --workspace --locked - name: Build and verify the archive run: node scripts/package/build-linux.mjs "${{ matrix.arch }}" - - name: Start the packaged backend and language server + - name: Start the packaged backend and the user's language server run: node scripts/package/smoke-linux.mjs dist/*-linux-${{ matrix.arch }}.zip - uses: actions/upload-artifact@v4 with: diff --git a/MIGRATION.md b/MIGRATION.md index 26cf425..0bda742 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,5 +1,8 @@ # 迁移说明:Java 逻辑从 Lithe 主仓库移到本仓库 +> 3.0.0 起插件包不再附带 JDT LS 和 JDK,改用用户自己的安装(`backend/src/jdtls.rs`);`scripts/prepare-jdk.sh`、 +> `third_party/jdk/` 和 JDT 反编译补丁已删除。下文的打包与资源条目是迁移时的历史记录。 + 本文是 Java Support 插件(`io.github.lithe-idea.java-support`)从 Lithe 主仓库拆分出来的移植账本,回答四个问题: 1. 主仓库里的每个 Java 相关文件或符号,现在在本仓库的哪里,状态是什么。 diff --git a/NOTICE b/NOTICE index a96b945..f7f0b00 100644 --- a/NOTICE +++ b/NOTICE @@ -8,17 +8,16 @@ is downloaded at build time from pinned sources and verified by SHA-256 (see third_party/). Each component keeps its own license, and the license text is copied into the package next to the component: - Eclipse JDT Language Server Eclipse Public License 2.0 - https://download.eclipse.org/jdtls/ Project Lombok MIT License https://projectlombok.org/ Microsoft java-debug Eclipse Public License 1.0 (vscode-java-debug) https://github.com/microsoft/java-debug Microsoft vscode-java-test MIT License (JUnit runner and plugin) https://github.com/microsoft/vscode-java-test - Eclipse Temurin JDK GNU General Public License v2 with the - Classpath Exception - https://adoptium.net/ + +The package does not include the Eclipse JDT Language Server or a Java +runtime. The plugin runs the JDT LS installation and the JDK the user installs +(https://download.eclipse.org/jdtls/, Eclipse Public License 2.0). The icons java.svg and java_dark.svg in io.github.lithe-idea.java-support/icons/ come from the JetBrains IntelliJ Platform diff --git a/README.md b/README.md index 25daeb7..89536a9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Java Support for Lithe +> **3.0.0 起使用你自己的 JDT LS**:插件包不再附带 Eclipse JDT Language Server 和运行它的 JDK(包从约 250 MB 降到约 11 MB), +> 做法和 Go 插件使用你自己的 `gopls` 一样。需要先安装 JDT LS(例如 `brew install jdtls`)和 JDK 21 或更新版本, +> 详见下文[语言服务器与 JDK](#语言服务器与-jdk)。 + > **Viva 预览版 Java 支持(1.2.0)**:清单已迁到当前契约 0,后端使用 Core > `65cf82343c5e315aae2e335b2e8f0217b703e89a` 中的 Rust SDK 0.4.0(尚无对应发布标签)。 > 本轮验证含第三方 JAR 依赖的普通 Maven 工程:JDT 补全、Maven 编译、main 运行和断点调试,包含变量读取、继续和退出。 @@ -13,14 +17,14 @@ [Lithe](https://github.com/1lck/Lithe-IDEA) 的 Java 插件(`io.github.lithe-idea.java-support`): -打包 Eclipse JDT Language Server、Lombok、java-debug、vscode-java-test 运行器和每个架构一份 Temurin JDK, +用你电脑上的 Eclipse JDT Language Server,加上随包的 Lombok、java-debug、vscode-java-test 扩展, 为 Java 项目提供补全、诊断、导航、运行/调试入口、测试运行和 Spring Boot / MyBatis 索引。 它是普通插件(vendor 为 `Lithe Community`),插件包不带发布者签名。 > English: The Java plugin for Lithe, a regular plugin (vendor `Lithe Community`) whose package carries no publisher -> signature. It bundles Eclipse JDT LS, Lombok, the java-debug and vscode-java-test runners and a per-architecture -> Temurin JDK, and provides Java language features, run/debug entry points, test runs and Spring Boot / MyBatis -> indexes. The Java rules live in a Rust domain crate and a plugin backend built on the published Lithe Rust plugin +> signature. It runs your own Eclipse JDT LS on your own JDK 21+, adds the packaged Lombok, java-debug and +> vscode-java-test extensions, and provides Java language features, run/debug entry points, test runs and Spring Boot / +> MyBatis indexes. The Java rules live in a Rust domain crate and a plugin backend built on the published Lithe Rust plugin > SDK. Maven and Gradle import settings come from the Maven and Gradle plugins through a function interface that > Lithe Core relays between plugins. @@ -38,10 +42,8 @@ 跳到依赖的其他类;方法定位使用 JDT 返回的行号。每份内容最多 1 MiB,插件不持有额外 源码缓存,关闭标签或工作区沿用宿主资源回收。缺失依赖的成员不能保证解析。 -针对残缺旧库,构建阶段修正锁定 JDT 1.61.0 对缺失内部类的遍历,避免整个外部类为空; -无法恢复缺失的内部类本身。修改后的 JDT core JAR 不再具有 Eclipse JAR 签名,随包包含 -修改的 EPL 源码和完整哈希清单;原生 JVM 签名不变。来源、验证和移除条件见 -[补丁说明](third_party/jdtls/patches/README.md)。安装包和下载缓存运行时保持只读。 +2.x 曾在构建阶段修补随包 JDT LS 1.61.0 对缺失内部类的遍历。3.0.0 起使用你自己的 JDT LS, +插件不修改它,这个修补不再生效:缺少内部类的残缺旧库,反编译出的外部类可能为空。 `.jsp` 仍按 HTML 打开;Java 补全、跳转和 JSP 源码断点不属于此次新增能力。 @@ -132,7 +134,7 @@ JUnit 的 Maven goal 也不代表 Java 插件的每一种行内测试运行器 `LITHE_TEST_JAVA_HISTORICAL_ROOT` 指向固定 commit,`LITHE_TEST_JAVA_HISTORICAL_PROBE` 提供验证表达式。 原配置与显式 `LITHE_TEST_JAVA_HISTORICAL_SOURCE=1.8` 的临时 POM 修改必须分开报告;后者不能证明 原 Java 5 配置可用。Java 8/11 运行时由 `LITHE_TEST_JAVA8_HOME`、`LITHE_TEST_JAVA11_HOME` 提供,测试 -会核对 class 目标版本与实际 JVM,不从 JDT 使用的随包 JDK 推断项目运行时。 +会核对 class 目标版本与实际 JVM,不从运行 JDT 的 JDK 推断项目运行时。 | 历史源码基线 | 原 Java 5 POM | 仅在副本把 source/target 改为 1.8 | | --- | --- | --- | @@ -177,27 +179,52 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。 | 功能 | 说明 | | --- | --- | -| 语言服务 | 用打包的 JDT LS(含 Lombok)提供补全、诊断、导航;JDK 随包提供,只用来运行语言服务器,项目自己的 SDK 仍由用户选择 | +| 语言服务 | 用你电脑上的 JDT LS(加上随包的 Lombok)提供补全、诊断、导航;运行它的 JDK 21+ 和项目自己的 JDK 分别选择 | | 运行与调试 | 在 `main` 方法和测试旁显示 Run/Debug 行内动作;点击后后端经 JDT LS 构建并解析类路径,用用户选择的 JDK 通过宿主 Run 窗口启动,调试经 java-debug 连接;当前 Viva 包暂不提供控制台堆栈链接 | | 测试 | 发现 JUnit/TestNG 测试项,按类或方法启动 Eclipse JUnit 运行器(TestNG 用 vscode-java-test 运行器),运行结束后显示通过/失败计数 | | Spring Boot / MyBatis | 索引 Spring 端点与 MyBatis 映射,支持跳转 | | 新建项目 | 两个声明式项目生成器:Java(无构建系统,可选示例代码)、Spring Boot;Maven 原型和 Maven/Gradle 项目模板由 Maven、Gradle 插件提供 | | Maven / Gradle 工程 | 导入设置(settings 文件、本地仓库、offline、Gradle user home 等)由 Maven、Gradle 插件通过 `languageImport.settings` 提供,Java 不计算也不解析它们;后端收下后推给 JDT LS,Maven profiles 变化时触发 `java.project.updateSettings` | +## 语言服务器与 JDK + +插件包不带 JDT LS,也不带运行它的 JDK,和 Go 插件使用你自己的 `gopls` 一样。需要: + +1. **Eclipse JDT Language Server**。按以下顺序找,用第一个: + 1. 设置 → 语言与框架 → Java →「语言服务器目录」。选了目录就只用它,目录里没有 JDT LS 时直接报错,不会退回别的安装; + 2. 环境变量 `JDTLS_HOME`; + 3. `PATH` 上的 `jdtls` 启动脚本所属的安装(沿符号链接找到真实目录); + 4. Homebrew(`/opt/homebrew/opt/jdtls`、`/usr/local/opt/jdtls`)、Linuxbrew、mason.nvim、Scoop 的安装目录; + 5. VS Code 及其衍生编辑器里 Java 扩展(`redhat.java`)自带的 `server/`,取最新版本。 + + 目录(或其中的 `libexec/`)里要有唯一一个 `plugins/org.eclipse.equinox.launcher_*.jar` 和当前平台的 + `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`),两者互不影响。 + JDT 只能为它支持的 Java 版本编译:没有为项目选 JDK 时,JDT 用运行它的 JDK 编译,这个 JDK 比 JDT LS 支持的最新 Java 还新时编译会报错。 + +找不到 JDT LS 时,语言服务启动失败(`launch.server_missing`),错误信息说明如何安装或去哪里设置。 +宿主当前的 `commandInstallers` 只能安装 `systemCommand` 启动的命令,JDT LS 由插件后端启动,所以还不能像 Go 插件那样在插件详情里一键安装。 + ## 工作方式 - Java 专属的 URI、JDT 初始化、编译/运行/调试和长 classpath 规划属于本插件及成熟上游;宿主只提供通用服务。 Maven / Gradle 自己解析配置,通过 `languageImport.settings` 接口提供 JDT 导入设置,Java 不维护第二套构建模型。 -- `backend/src/launch.rs` 定位已打包的 JDT、Lombok、java-debug、java-test 和运行语言服务器的 JDK。 - 宿主传入用户所选项目 JDK 的安装事实,插件据此设置 JDT 运行时;随包 JDK 不代替项目的目标版本。 +- `backend/src/jdtls.rs` 找到你安装的 JDT LS,`backend/src/launch.rs` 加上随包的 Lombok、java-debug、java-test, + 用 `jdtls-runtime` 工具(JDK 21+)启动它。宿主传入用户所选项目 JDK 的安装事实,插件据此设置 JDT 运行时; + 运行 JDT LS 的 JDK 不代替项目的目标版本。 - 初始化就绪不等于索引完成。JDT 公开的 `progressReportProvider` 扩展将完成事件发到已声明的 `language/progressReport` 通道。只有动作查询发生瞬态失败才在完成边界刷新;同时处理完成与超时倒序, 每个失败周期最多自动刷新三次,成功重置预算,工作区/服务器代际隔离旧结果,关闭后删除状态。不增加空闲轮询。 - Windows 使用原生 `java.exe`,文件 URI 由 `url` crate 处理,包路径通过 `dunce` 去除可安全简化的 verbatim 前缀, 避免 Lombok 的 `-javaagent` 加载失败。过长 classpath 复用领域层的 manifest JAR 规划,适用于 Java 8 及更新版本; ASCII 百分号编码覆盖中文/空格,宿主写入临时 JAR 并在运行结束删除。长 module-path 尚未覆盖。 -- 已安装插件包始终只读。JDT 配置副本、索引、日志、锁和临时文件写到宿主提供的用户状态/缓存/临时目录; - 插件包、app bundle 和 Windows 安装目录不作为可写目标。构建期固定来源、校验资源哈希,运行期不下载。 +- 已安装插件包和你的 JDT LS 安装始终只读。JDT 配置副本(从安装里的 `config_<平台>/config.ini` 复制)、索引、日志、锁和临时文件 + 写到宿主提供的用户状态/缓存/临时目录;插件包、JDT LS 安装、app bundle 和 Windows 安装目录不作为可写目标。 + 随包扩展在构建期固定来源、校验哈希,运行期不下载。 ## 日志 @@ -212,7 +239,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` | +| 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 配置清理或工作区读取降级 | 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 | @@ -242,7 +269,7 @@ io.github.lithe-idea.java-support/ # 插件包的静态部分:plugin.json、 crates/java-domain/ # Java 领域规则(Rust),测试在各模块内和 tests/ 下 backend/ # 插件后端进程(lithe-java-backend),基于 Lithe Rust 插件 SDK fixtures/ # 与主仓库共享的契约样例(JSON) -third_party/ # JDT LS 与 JDK 的来源地址和 SHA-256 +third_party/ # 随包扩展(Lombok、java-debug、java-test)与测试用 JDT LS 的来源地址和 SHA-256 sdk.lock.json # 后端链接的 Rust SDK:标签、提交、crate 归档的 SHA-256 scripts/ # 组装、校验、归档插件包,检查 SDK 锁 .github/workflows/ci.yml # PR:格式、lint、测试、SDK 锁,以及 macOS 双架构打包和 Linux 双架构原生验证 @@ -263,7 +290,7 @@ scripts/verify-sdk-lock.sh Rust 单元测试使用有界资源;真实 Viva 集成测试需要显式 ZIP、JDK、构建工具输入,外部依赖首次解析可能联网,不属于离线单元测试。 -构建并归档插件包(会下载并校验 JDT LS 与 JDK,体积较大)。本地开发、CI 和发布使用同一组命令,产出同一种归档: +构建并归档插件包(会下载并校验随包扩展,以及测试用的 JDT LS 1.61.0;JDT LS 本身不进包)。本地开发、CI 和发布使用同一组命令,产出同一种归档: ```bash scripts/build-package.sh --arch arm64 # 或 x86_64;打印包目录 .artifacts/package//io.github.lithe-idea.java-support @@ -273,7 +300,12 @@ scripts/archive-package.sh --package <上一步打印的目录> --arch arm64 # `build-package.sh` 会在输出包目录前校验它;`archive-package.sh` 把归档解开后再校验一次。单独校验一个包目录用 `scripts/verify-package.sh --package <目录> --arch arm64|x86_64|universal`:它要求 `plugin.json` 的 `vendor.signatureRequirement` 为 `none`, 包里不能有 `lithe-plugin-signature.json`,`bin/` 里只能有 `backend.launch.path` 指向的后端二进制,它必须可执行且包含请求的架构(`lipo -archs`), -并检查打包的 JDK 保留着上游的 Apple 代码签名。归档不需要签名密钥,也不调用任何签名工具。 +并确认包里没有 JDT LS(Equinox 启动器、`config_*`)或 JDK。归档不需要签名密钥,也不调用任何签名工具。 + +真实 JDT 集成测试(`scripts/compiler/test-live.mjs`、Linux 的 `scripts/package/smoke-linux.mjs`)默认用 +`scripts/prepare-jdtls.sh` 准备在 `.artifacts/jdtls` 的 JDT LS 1.61.0,运行它的 JDK 取 `JAVA_HOME`(需 21+)。 +`LITHE_TEST_JDTLS_HOME`、`LITHE_TEST_JDTLS_JAVA` 可换成别的安装,`LITHE_TEST_PROJECT_JAVA_HOME` 模拟宿主传入的项目 JDK; +测试结束时核对插件包和 JDT LS 安装的全部文件没有变化。 `plugin.json` 的完整格式只在固定 Core 的 `shared/plugins/contract/v1/`,不在本仓库维护副本。 @@ -285,14 +317,14 @@ scripts/archive-package.sh --package <上一步打印的目录> --arch arm64 # node scripts/package/build-windows.mjs /path/to/lithe-java-backend.exe ``` -脚本验证 x64 PE 与锁定 JDK 的 SHA-256,复用 JDT 构建入口,写入 `.artifacts/` 并清理组装临时目录。 +脚本验证 x64 PE,复用随包扩展的构建入口,写入 `.artifacts/` 并清理组装临时目录。 发布工作流在 Windows 从同一标签构建并测试 x64 后端,静态链接编译器运行库,再通过此入口组装 ZIP;本地验证复用相同入口。发布前用成熟的 PE 检查工具拒绝额外的 VC++/MinGW 运行库 DLL 依赖,保持后端无需另装编译器运行库。包不带发布者签名,不含安装器,打包成功也不能代替 Windows 运行验收。 ## 发布新版本 构建和发布由现有工作流执行,正式发布前按 Lithe 的版本规则决定版本并核验兼容宿主。 当前依赖 Viva preview,只能作为预发布。推送匹配版本的标签后,工作流为 macOS arm64/x64、Windows x64 与 Linux ARM64/x64 生成 ZIP 和 SHA-256,并创建草稿预发布;维护者下载核对后再公开草稿。发布说明必须位于 `docs/releases/v<版本>.md`,缺失则终止发布。 -不得覆盖已发布 ZIP,也不得将本地隔离试验的 JDT/JDK 资源当作生产升级:本轮生产仍固定 JDT LS 1.61 和 Temurin 21。 +不得覆盖已发布 ZIP。随包扩展的版本只在 `third_party/jdtls/manifest.json` 升级;JDT LS 和 JDK 由用户安装,不随插件发布。 ## 许可 diff --git a/backend/src/jdtls.rs b/backend/src/jdtls.rs new file mode 100644 index 0000000..0ff00cf --- /dev/null +++ b/backend/src/jdtls.rs @@ -0,0 +1,514 @@ +//! Finds the Eclipse JDT Language Server installed on the user's machine. +//! +//! The plugin package does not ship JDT LS or a Java runtime for it, the same +//! way the Go plugin uses the user's own `gopls`: the user installs JDT LS +//! with a package manager or an editor, and the launch reads its files from +//! there. The backend only reads that installation. Equinox gets a writable +//! copy of the installation's `config.ini` under the host's state directory +//! (`prepare_jdt_configuration_area`), so neither the backend nor JDT LS +//! writes into the user's installation. +//! +//! # Where the launch looks +//! +//! [`locate`] takes the first installation of these, in order: +//! +//! 1. the `languageServerHome` setting. A folder set there is the user's +//! explicit choice, so an unusable one fails the launch instead of falling +//! back to another installation; +//! 2. the `JDTLS_HOME` environment variable; +//! 3. a `jdtls` launcher on `PATH`, resolved through its symbolic links to the +//! installation it belongs to; +//! 4. the folders package managers install JDT LS into (Homebrew, Linuxbrew, +//! mason.nvim, Scoop); +//! 5. the language server inside an installed VS Code Java extension +//! (`redhat.java`), newest version first. +//! +//! A folder holds an installation when it, or its `libexec/` (Homebrew keeps +//! the files there), contains exactly one Equinox launcher JAR in `plugins/` +//! and the `config_/config.ini` of the host platform. Nothing else +//! is checked: JDT LS reports a version it cannot run at `initialize`. + +use lithe_plugin_sdk::PluginError; +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; + +/// No JDT LS installation was found on the machine. +pub const LAUNCH_SERVER_MISSING: &str = "launch.server_missing"; +/// The folder chosen in the `languageServerHome` setting holds no JDT LS +/// installation for this platform. +pub const LAUNCH_SERVER_INVALID: &str = "launch.server_invalid"; + +/// Plugin setting naming the JDT LS folder; empty for automatic discovery. +pub const SERVER_HOME_SETTING: &str = "languageServerHome"; +/// Environment variable that may name the JDT LS folder. +pub const SERVER_HOME_VARIABLE: &str = "JDTLS_HOME"; +/// Directory of an installation that holds the Equinox launcher JAR. +pub const PLUGINS_DIRECTORY: &str = "plugins"; +/// File name prefix of the Equinox launcher JAR; the version follows it. +pub const LAUNCHER_PREFIX: &str = "org.eclipse.equinox.launcher_"; +/// File name suffix of the Equinox launcher JAR. +pub const LAUNCHER_SUFFIX: &str = ".jar"; +/// Subdirectory Homebrew installs the JDT LS files into. +const LIBEXEC_DIRECTORY: &str = "libexec"; +/// The only file Equinox reads from a platform configuration directory. +const CONFIG_INI: &str = "config.ini"; +/// Folder name prefix of the VS Code Java extension; its version follows. +const EDITOR_EXTENSION_PREFIX: &str = "redhat.java-"; +/// Directory of the VS Code Java extension that holds JDT LS. +const EDITOR_EXTENSION_SERVER: &str = "server"; +/// Extension directories of VS Code and the editors built from it, below the +/// user's home directory. +const EDITOR_EXTENSION_ROOTS: &[&str] = &[ + ".vscode/extensions", + ".vscode-insiders/extensions", + ".vscode-oss/extensions", + ".cursor/extensions", +]; +/// Most entries read from one editor extension directory, so a large one +/// delays the launch by a bounded amount. +const EDITOR_EXTENSION_ENTRY_BUDGET: usize = 4096; + +/// Message of [`LAUNCH_SERVER_MISSING`]. +/// +/// TODO(host-api: API-37 i18n): user-facing text must go through the host's +/// i18n table. +pub const SERVER_MISSING_MESSAGE: &str = "Java Support needs the Eclipse JDT Language Server, \ +which was not found on this computer. Install it (for example with `brew install jdtls`), \ +or choose its folder in Settings > Languages & Frameworks > Java > Language server folder."; +/// Message of [`LAUNCH_SERVER_INVALID`]. +/// +/// TODO(host-api: API-37 i18n): user-facing text must go through the host's +/// i18n table. +pub const SERVER_INVALID_MESSAGE: &str = "The language server folder chosen in the Java \ +settings does not contain the Eclipse JDT Language Server for this platform. Choose the \ +folder that contains plugins and the config folders, or clear the setting to find JDT LS \ +automatically."; + +/// The JDT LS files a launch uses, absolute. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServerInstallation { + /// The installation folder: the parent of `plugins/`. + pub home: PathBuf, + /// The Equinox launcher JAR passed after `-jar`. + pub launcher_jar: PathBuf, + /// The read-only Equinox configuration of the platform; the launch uses a + /// writable copy of it. + pub configuration: PathBuf, +} + +/// What [`locate`] reads from the backend's process environment, so tests +/// can supply their own. +#[derive(Debug, Clone, Default)] +pub struct SearchEnvironment { + /// The user's home directory. + pub home: Option, + /// `JDTLS_HOME`. + pub server_home: Option, + /// `PATH`. + pub path: Option, + /// `LOCALAPPDATA`, where mason.nvim installs on Windows. + pub local_app_data: Option, +} + +impl SearchEnvironment { + /// The environment of the running backend. + pub fn current() -> Self { + let directory = |name: &str| { + std::env::var_os(name) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + }; + SearchEnvironment { + home: directory(if cfg!(windows) { "USERPROFILE" } else { "HOME" }), + server_home: directory(SERVER_HOME_VARIABLE), + path: std::env::var_os("PATH"), + local_app_data: directory("LOCALAPPDATA"), + } + } +} + +/// The `config_` directory JDT LS ships for `os` (`macos`, +/// `linux` or `windows`, as `resolveParams.platform.os` names it) and `arch` +/// (`arm64` or `x86_64`). JDT LS ships one Windows configuration for every +/// architecture. +pub fn configuration_name(os: &str, arch: &str) -> Option<&'static str> { + match (os, arch) { + ("macos", "arm64") => Some("config_mac_arm"), + ("macos", "x86_64") => Some("config_mac"), + ("linux", "arm64") => Some("config_linux_arm"), + ("linux", "x86_64") => Some("config_linux"), + ("windows", _) => Some("config_win"), + _ => None, + } +} + +/// The installation in `folder` or in its `libexec/`, or `None` when neither +/// holds one for the configuration `configuration`. +pub fn inspect(folder: &Path, configuration: &str) -> Option { + [folder.to_path_buf(), folder.join(LIBEXEC_DIRECTORY)] + .into_iter() + .find_map(|home| installation_at(&home, configuration)) +} + +fn installation_at(home: &Path, configuration: &str) -> Option { + // 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 configuration = home.join(configuration); + if !configuration.join(CONFIG_INI).is_file() { + return None; + } + Some(ServerInstallation { + home, + launcher_jar, + configuration, + }) +} + +/// The one Equinox launcher JAR in `directory`. None or several mean the +/// folder is no usable installation. +fn launcher_in(directory: &Path) -> Option { + let mut launchers: Vec = fs::read_dir(directory) + .ok()? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + name.starts_with(LAUNCHER_PREFIX) && name.ends_with(LAUNCHER_SUFFIX) + }) + && path.is_file() + }) + .collect(); + if launchers.len() == 1 { + launchers.pop() + } else { + None + } +} + +/// Finds the JDT LS installation for `os` and `arch`. +/// +/// `configured` is the `languageServerHome` setting, `None` when it is empty. +pub fn locate( + configured: Option<&Path>, + environment: &SearchEnvironment, + os: &str, + arch: &str, +) -> Result { + 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)) +} + +/// The folders [`locate`] tries without a configured one, in order. A folder +/// may hold no installation; [`inspect`] decides. +pub fn candidates(environment: &SearchEnvironment, os: &str) -> Vec { + let mut folders = Vec::new(); + folders.extend(environment.server_home.clone()); + folders.extend(launcher_installations(environment.path.as_ref(), os)); + folders.extend(package_manager_folders(environment, os)); + if let Some(home) = &environment.home { + folders.extend(editor_extension_servers(home)); + } + folders +} + +/// The installation folders of the `jdtls` launchers on `path`: a launcher is +/// `/bin/jdtls`, possibly behind symbolic links. +fn launcher_installations(path: Option<&OsString>, os: &str) -> Vec { + let Some(path) = path else { + return Vec::new(); + }; + let names: &[&str] = if os == "windows" { + &["jdtls.bat", "jdtls.cmd"] + } else { + &["jdtls"] + }; + std::env::split_paths(path) + .filter(|directory| directory.is_absolute()) + .flat_map(|directory| names.iter().map(move |name| directory.join(name))) + .filter(|launcher| launcher.is_file()) + .filter_map(|launcher| dunce::canonicalize(launcher).ok()) + .filter_map(|launcher| launcher.parent()?.parent().map(Path::to_path_buf)) + .collect() +} + +/// The folders package managers install JDT LS into on `os`. +fn package_manager_folders(environment: &SearchEnvironment, os: &str) -> Vec { + let mut folders = Vec::new(); + let home = environment.home.as_deref(); + match os { + "macos" => { + folders.push(PathBuf::from("/opt/homebrew/opt/jdtls")); + folders.push(PathBuf::from("/usr/local/opt/jdtls")); + } + "linux" => { + folders.push(PathBuf::from("/home/linuxbrew/.linuxbrew/opt/jdtls")); + folders.extend(home.map(|home| home.join(".linuxbrew/opt/jdtls"))); + } + _ => {} + } + if os == "windows" { + folders.extend( + environment + .local_app_data + .as_deref() + .map(|data| data.join("nvim-data/mason/packages/jdtls")), + ); + folders.extend(home.map(|home| home.join("scoop/apps/jdtls/current"))); + } else { + folders.extend(home.map(|home| home.join(".local/share/nvim/mason/packages/jdtls"))); + } + folders +} + +/// The `server/` folders of the VS Code Java extensions under `home`, newest +/// extension version first. +fn editor_extension_servers(home: &Path) -> Vec { + let mut extensions: Vec<(Vec, PathBuf)> = Vec::new(); + for root in EDITOR_EXTENSION_ROOTS { + let Ok(entries) = fs::read_dir(home.join(root)) else { + continue; + }; + for entry in entries + .filter_map(Result::ok) + .take(EDITOR_EXTENSION_ENTRY_BUDGET) + { + let name = entry.file_name(); + let Some(version) = name + .to_str() + .and_then(|name| name.strip_prefix(EDITOR_EXTENSION_PREFIX)) + .and_then(extension_version) + else { + continue; + }; + extensions.push((version, entry.path().join(EDITOR_EXTENSION_SERVER))); + } + } + // Newest first; the path keeps the order stable for equal versions. + extensions.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| left.1.cmp(&right.1))); + extensions.into_iter().map(|(_, folder)| folder).collect() +} + +/// The dotted version that starts an extension folder name after its +/// publisher and name, such as `1.58.0` in `1.58.0-darwin-arm64`. +fn extension_version(text: &str) -> Option> { + let version = text.split('-').next()?; + let parts: Option> = version.split('.').map(|part| part.parse().ok()).collect(); + parts.filter(|parts| !parts.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + const LAUNCHER: &str = "org.eclipse.equinox.launcher_1.7.100.v20251111-0406.jar"; + + struct TempDir(PathBuf); + + impl TempDir { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-java-jdtls-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + TempDir(dunce::canonicalize(path).unwrap()) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + /// Lays out a JDT LS installation with the configurations of `configurations`. + fn install(home: &Path, configurations: &[&str]) { + fs::create_dir_all(home.join(PLUGINS_DIRECTORY)).unwrap(); + fs::write(home.join(PLUGINS_DIRECTORY).join(LAUNCHER), b"").unwrap(); + for configuration in configurations { + fs::create_dir_all(home.join(configuration)).unwrap(); + fs::write( + home.join(configuration).join(CONFIG_INI), + b"osgi.bundles=x\n", + ) + .unwrap(); + } + } + + fn environment(home: &Path) -> SearchEnvironment { + SearchEnvironment { + home: Some(home.to_path_buf()), + ..SearchEnvironment::default() + } + } + + #[test] + fn every_supported_platform_has_its_configuration() { + assert_eq!(configuration_name("macos", "arm64"), Some("config_mac_arm")); + assert_eq!(configuration_name("macos", "x86_64"), Some("config_mac")); + assert_eq!( + configuration_name("linux", "arm64"), + Some("config_linux_arm") + ); + assert_eq!(configuration_name("linux", "x86_64"), Some("config_linux")); + assert_eq!(configuration_name("windows", "x86_64"), Some("config_win")); + assert_eq!(configuration_name("windows", "arm64"), Some("config_win")); + assert_eq!(configuration_name("freebsd", "x86_64"), None); + } + + #[test] + fn an_installation_needs_one_launcher_and_the_platform_configuration() { + let temp = TempDir::new(); + let home = temp.0.join("jdtls"); + install(&home, &["config_mac_arm"]); + let found = inspect(&home, "config_mac_arm").unwrap(); + assert_eq!(found.home, home); + assert_eq!(found.launcher_jar, home.join("plugins").join(LAUNCHER)); + assert_eq!(found.configuration, home.join("config_mac_arm")); + + // Another platform's configuration does not count. + assert!(inspect(&home, "config_linux").is_none()); + // Two launchers leave the choice open. + fs::write(home.join("plugins/org.eclipse.equinox.launcher_9.jar"), b"").unwrap(); + assert!(inspect(&home, "config_mac_arm").is_none()); + assert!(inspect(&temp.0.join("missing"), "config_mac_arm").is_none()); + } + + #[test] + fn a_homebrew_keg_is_found_through_libexec() { + let temp = TempDir::new(); + let keg = temp.0.join("Cellar/jdtls/1.60.0"); + install(&keg.join("libexec"), &["config_mac_arm"]); + assert_eq!( + inspect(&keg, "config_mac_arm").unwrap().home, + keg.join("libexec") + ); + } + + #[test] + fn a_configured_folder_is_final() { + let temp = TempDir::new(); + let chosen = temp.0.join("chosen"); + install(&chosen, &["config_linux"]); + let discovered = temp.0.join("discovered"); + install(&discovered, &["config_linux"]); + let mut search = environment(&temp.0); + search.server_home = Some(discovered.clone()); + + let found = locate(Some(&chosen), &search, "linux", "x86_64").unwrap(); + assert_eq!(found.home, chosen); + // An unusable choice fails instead of falling back to another installation. + let error = locate(Some(&temp.0.join("empty")), &search, "linux", "x86_64").unwrap_err(); + assert_eq!(error.code(), LAUNCH_SERVER_INVALID); + assert_eq!(error.message(), SERVER_INVALID_MESSAGE); + // Without a choice the discovered installation is used. + assert_eq!( + locate(None, &search, "linux", "x86_64").unwrap().home, + discovered + ); + } + + #[test] + fn nothing_found_is_one_error_that_names_no_path() { + let temp = TempDir::new(); + let error = locate(None, &environment(&temp.0), "windows", "x86_64").unwrap_err(); + assert_eq!(error.code(), LAUNCH_SERVER_MISSING); + assert_eq!(error.message(), SERVER_MISSING_MESSAGE); + assert!(!error.message().contains(temp.0.to_string_lossy().as_ref())); + let error = locate(None, &environment(&temp.0), "plan9", "x86_64").unwrap_err(); + assert_eq!(error.code(), LAUNCH_SERVER_MISSING); + } + + #[cfg(unix)] + #[test] + fn a_launcher_on_path_leads_to_its_installation() { + let temp = TempDir::new(); + let keg = temp.0.join("Cellar/jdtls/1.63.0"); + install(&keg.join("libexec"), &["config_linux"]); + fs::create_dir_all(keg.join("bin")).unwrap(); + fs::write(keg.join("bin/jdtls"), b"#!/bin/sh\n").unwrap(); + let bin = temp.0.join("bin"); + fs::create_dir_all(&bin).unwrap(); + std::os::unix::fs::symlink(keg.join("bin/jdtls"), bin.join("jdtls")).unwrap(); + let mut search = environment(&temp.0); + search.path = Some(std::env::join_paths([temp.0.join("nothing"), bin]).unwrap()); + assert_eq!( + locate(None, &search, "linux", "x86_64").unwrap().home, + keg.join("libexec") + ); + } + + #[test] + fn mason_is_searched_in_the_home_directory() { + let temp = TempDir::new(); + let mason = temp.0.join(".local/share/nvim/mason/packages/jdtls"); + install(&mason, &["config_linux_arm"]); + assert_eq!( + locate(None, &environment(&temp.0), "linux", "arm64") + .unwrap() + .home, + mason + ); + } + + #[test] + fn the_newest_editor_extension_wins() { + let temp = TempDir::new(); + let extensions = temp.0.join(".vscode/extensions"); + for name in [ + "redhat.java-1.9.0-darwin-arm64", + "redhat.java-1.58.0-darwin-arm64", + "redhat.java-1.47.0", + ] { + install(&extensions.join(name).join("server"), &["config_win"]); + } + fs::create_dir_all(extensions.join("redhat.java-latest")).unwrap(); + fs::create_dir_all(extensions.join("vscjava.vscode-java-debug-0.60.0")).unwrap(); + assert_eq!( + editor_extension_servers(&temp.0), + vec![ + extensions.join("redhat.java-1.58.0-darwin-arm64/server"), + extensions.join("redhat.java-1.47.0/server"), + extensions.join("redhat.java-1.9.0-darwin-arm64/server"), + ] + ); + assert_eq!( + // Windows names no machine-wide folder, so only the extensions count. + locate(None, &environment(&temp.0), "windows", "x86_64") + .unwrap() + .home, + extensions.join("redhat.java-1.58.0-darwin-arm64/server") + ); + } + + #[test] + fn jdtls_home_comes_before_the_other_folders() { + let temp = TempDir::new(); + let mut search = environment(&temp.0); + search.server_home = Some(temp.0.join("explicit")); + let folders = candidates(&search, "macos"); + assert_eq!(folders[0], temp.0.join("explicit")); + assert!(folders.contains(&PathBuf::from("/opt/homebrew/opt/jdtls"))); + let folders = candidates(&search, "windows"); + assert!(folders.contains(&temp.0.join("scoop/apps/jdtls/current"))); + assert!(!folders.contains(&PathBuf::from("/opt/homebrew/opt/jdtls"))); + } +} diff --git a/backend/src/launch.rs b/backend/src/launch.rs index b193b4e..7b09325 100644 --- a/backend/src/launch.rs +++ b/backend/src/launch.rs @@ -3,24 +3,33 @@ //! Before the host starts the `java` language server it calls //! [`LAUNCH_FUNCTION_ID`] with the contract's `resolveParams` and the //! workspace `context`, and it starts the process the answer describes. This -//! module does what the host's `jdt` integration did: it finds the JDT LS -//! files in the installed package, gives Equinox a writable copy of the -//! packaged configuration, and builds the JDT LS command line, its -//! initialization options and its settings. +//! module does what the host's `jdt` integration did: it finds the user's +//! JDT LS installation, gives Equinox a writable copy of its configuration, +//! and builds the JDT LS command line, its initialization options and its +//! settings. //! //! # Where the files are //! -//! `resolveParams` carries no package directory. The manifest installs the -//! backend at `bin/lithe-java-backend`, so the package root is the parent of -//! the directory of the running executable ([`package_root`]). Every package -//! path below is relative to that root, and the launcher is found by name -//! instead of by a pinned version, so a JDT LS update changes no code. +//! JDT LS itself is not in the package: [`crate::jdtls`] finds the +//! installation on the machine, the way the Go plugin uses the user's own +//! `gopls`. The answer runs it with the plugin's `jdtls-runtime` tool +//! ([`SERVER_RUNTIME_TOOL`]), a JDK the host resolves from the user's choice +//! and discovery, and refuses one older than +//! [`MINIMUM_SERVER_JAVA_VERSION`] when the host reports its version. +//! +//! The package only carries what the plugin adds to JDT LS: the Lombok agent +//! and the Java Debug and Java Test extension bundles. `resolveParams` carries +//! no package directory. The manifest installs the backend at +//! `bin/lithe-java-backend`, so the package root is the parent of the +//! directory of the running executable ([`package_root`]), and every package +//! path below is relative to it. //! //! # Where the launch writes //! -//! The package is read-only: neither the backend nor JDT LS writes into it. -//! The launch writes only into the four directories the host provides for -//! this start, and the answer lists them as `writablePaths`: +//! The package and the JDT LS installation are read-only: neither the backend +//! nor JDT LS writes into them. The launch writes only into the four +//! directories the host provides for this start, and the answer lists them as +//! `writablePaths`: //! //! - `stateDirectory`: the Equinox configuration area, one per `config.ini` //! digest, which the backend prepares before it answers; @@ -39,6 +48,10 @@ //! //! [`settings_session::java_configuration`]: crate::settings_session::java_configuration +use crate::jdtls::{ + self, SearchEnvironment, ServerInstallation, LAUNCH_SERVER_INVALID, LAUNCH_SERVER_MISSING, + SERVER_HOME_SETTING, +}; use crate::run::file_uri; use crate::settings_session::{java_configuration, jdt_settings, SettingsSession, SERVER_ID}; use lithe_java_domain::jdt_integration::launch_resources::{bundles_in, missing_resource_message}; @@ -70,6 +83,9 @@ pub const LAUNCH_PACKAGE_UNAVAILABLE: &str = "launch.package_unavailable"; pub const LAUNCH_RESOURCE_MISSING: &str = "launch.resource_missing"; /// The writable Equinox configuration area could not be prepared. pub const LAUNCH_CONFIGURATION_FAILED: &str = "launch.configuration_failed"; +/// The JDK the host resolved for [`SERVER_RUNTIME_TOOL`] is older than +/// [`MINIMUM_SERVER_JAVA_VERSION`]. +pub const LAUNCH_RUNTIME_TOO_OLD: &str = "launch.runtime_too_old"; /// Every `pluginErrorCode` `java.resolveLaunch` answers with, one per cause. pub const LAUNCH_ERROR_CODES: &[&str] = &[ @@ -77,8 +93,25 @@ pub const LAUNCH_ERROR_CODES: &[&str] = &[ LAUNCH_PACKAGE_UNAVAILABLE, LAUNCH_RESOURCE_MISSING, LAUNCH_CONFIGURATION_FAILED, + LAUNCH_SERVER_MISSING, + LAUNCH_SERVER_INVALID, + LAUNCH_RUNTIME_TOO_OLD, ]; +/// The plugin's tool definition of the JDK that runs JDT LS. It is not the +/// `java` tool: that one is the project's JDK, which may be far older than +/// JDT LS accepts. +pub const SERVER_RUNTIME_TOOL: &str = "jdtls-runtime"; +/// Oldest Java feature release JDT LS runs on. +pub const MINIMUM_SERVER_JAVA_VERSION: u64 = 21; +/// Message of [`LAUNCH_RUNTIME_TOO_OLD`]. +/// +/// TODO(host-api: API-37 i18n): user-facing text must go through the host's +/// i18n table. +pub const RUNTIME_TOO_OLD_MESSAGE: &str = "The Eclipse JDT Language Server needs Java 21 or \ +later, but the JDK chosen for it is older. Choose a JDK 21 or later for \"JDK for JDT LS\" in \ +Settings > Build, Execution, Deployment > Toolchains."; + /// Configuration areas of older JDT LS versions could not be removed. Only /// disk space is at stake, so the launch goes on. pub const LAUNCH_CONFIGURATION_CLEANUP_FAILED: &str = "launch.configuration_cleanup_failed"; @@ -136,45 +169,34 @@ pub const ARCHITECTURES: &[&str] = &["arm64", "x86_64"]; /// service ready. pub const SERVICE_READY_GATE_ID: &str = "service-ready"; -// Package layout. `plugin.json` no longer names these files (a backend +// Package layout. `plugin.json` does not name these files (a backend // launch declares only the function); this module is the single source for // where `scripts/assemble-package.sh` puts them and `scripts/verify-package.sh` // checks them, and `backend/tests/repository_pins.rs` holds both scripts to // [`PACKAGE_LAYOUT`]. -/// Package directory that holds the Equinox launcher JAR. -pub const LAUNCHER_DIRECTORY: &str = "language-server/plugins"; -/// File name prefix of the Equinox launcher JAR; the version follows it. -pub const LAUNCHER_PREFIX: &str = "org.eclipse.equinox.launcher_"; -/// File name suffix of the Equinox launcher JAR. -pub const LAUNCHER_SUFFIX: &str = ".jar"; -/// Package directory with one Equinox configuration per architecture. -pub const CONFIGURATION_DIRECTORY: &str = "language-server/configuration"; +/// Package directory of everything the plugin adds to the user's JDT LS. +pub const EXTENSIONS_DIRECTORY: &str = "jdtls-extensions"; /// Package path of the Lombok agent JDT LS runs with. -pub const LOMBOK_AGENT: &str = "language-server/lombok/lombok.jar"; +pub const LOMBOK_AGENT: &str = "jdtls-extensions/lombok/lombok.jar"; /// Package directories whose JAR files JDT LS loads as extension bundles, in /// this order and then by file name: the Java Debug Server, then the Java /// Test extensions. pub const EXTENSION_BUNDLE_DIRECTORIES: &[&str] = &[ - "language-server/java-debug", - "language-server/java-test/extensions", + "jdtls-extensions/java-debug", + "jdtls-extensions/java-test/extensions", ]; /// Package path of the Java Test runner JAR the test flow adds to the class /// path of TestNG launches; JDT LS itself does not load it. pub const TEST_RUNNER: &str = - "language-server/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar"; -/// Package directory of the Java runtime; `/bin/java` follows it. -pub const RUNTIME_DIRECTORY: &str = "runtime"; + "jdtls-extensions/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar"; /// Every package path the backend resolves at launch or test time, so the /// package scripts can be held to the same list. pub const PACKAGE_LAYOUT: &[&str] = &[ - LAUNCHER_DIRECTORY, - CONFIGURATION_DIRECTORY, LOMBOK_AGENT, EXTENSION_BUNDLE_DIRECTORIES[0], EXTENSION_BUNDLE_DIRECTORIES[1], TEST_RUNNER, - RUNTIME_DIRECTORY, ]; /// Directory under `workspaceStateDirectory` passed to JDT LS as `-data`. const DATA_DIRECTORY: &str = "data"; @@ -188,8 +210,10 @@ const SERVICE_READY: &str = "ServiceReady"; /// The `resolveParams` of one start, checked. #[derive(Debug, Clone, PartialEq, Eq)] pub struct LaunchRequest { - /// `platform.arch`: `arm64` or `x86_64`, the runtime and the Equinox - /// configuration to use. + /// `platform.os`: `macos`, `linux` or `windows`. + pub os: String, + /// `platform.arch`: `arm64` or `x86_64`. With the operating system it + /// picks the Equinox configuration of the installation. pub architecture: String, /// `stateDirectory`: the plugin's writable directory for this server. pub state_directory: PathBuf, @@ -203,6 +227,12 @@ pub struct LaunchRequest { pub heap_max_mb: u64, /// `settings.logLevel`: the JDT LS log level. pub log_level: String, + /// `settings.languageServerHome`: the JDT LS folder the user chose; + /// `None` finds one ([`crate::jdtls::locate`]). + pub server_home: Option, + /// `tools["jdtls-runtime"].version`, when the host resolved the JDK that + /// runs JDT LS and read its version. + pub server_runtime_version: Option, /// `tools.java`, the installation the host resolved for the plugin's /// `java` tool, as the server's default runtime: Run starts the project /// with that JDK, so the server must compile for it. Empty when the host @@ -210,17 +240,18 @@ pub struct LaunchRequest { pub java_runtimes: Vec, } -/// The package files of a JDT LS launch, absolute. +/// The files of a JDT LS launch, absolute. #[derive(Debug, Clone, PartialEq, Eq)] pub struct LaunchFiles { - /// The Equinox launcher JAR passed after `-jar`. + /// The Equinox launcher JAR of the user's installation, passed after + /// `-jar`. pub launcher_jar: PathBuf, - /// The Lombok agent passed as `-javaagent`. + /// The packaged Lombok agent passed as `-javaagent`. pub lombok_agent: PathBuf, - /// The read-only Equinox configuration of the architecture; the launch - /// uses a writable copy of it. - pub packaged_configuration: PathBuf, - /// The extension bundle JARs, in load order. + /// The read-only Equinox configuration of the installation for this + /// platform; the launch uses a writable copy of it. + pub server_configuration: PathBuf, + /// The packaged extension bundle JARs, in load order. pub extension_bundles: Vec, } @@ -237,6 +268,12 @@ pub fn parse_launch_params(params: &Value) -> Result .and_then(Value::as_str) .filter(|arch| ARCHITECTURES.contains(arch)) .ok_or_else(|| invalid_params("The launch names no supported architecture."))?; + let os = params + .get("platform") + .and_then(|platform| platform.get("os")) + .and_then(Value::as_str) + .filter(|os| !os.is_empty()) + .ok_or_else(|| invalid_params("The launch names no operating system."))?; let settings = params.get("settings").cloned().unwrap_or_else(|| json!({})); let heap_max_mb = match settings.get("heapMaxMB") { None | Some(Value::Null) => DEFAULT_HEAP_MAX_MB, @@ -252,7 +289,20 @@ pub fn parse_launch_params(params: &Value) -> Result .filter(|level| LOG_LEVELS.contains(level)) .ok_or_else(|| invalid_params("The log level setting is not supported."))?, }; + let server_home = match settings.get(SERVER_HOME_SETTING) { + None | Some(Value::Null) => None, + Some(value) => match value.as_str() { + Some("") => None, + Some(folder) if Path::new(folder).is_absolute() => Some(PathBuf::from(folder)), + _ => { + return Err(invalid_params( + "The language server folder setting is not a folder.", + )) + } + }, + }; Ok(LaunchRequest { + os: os.to_string(), architecture: architecture.to_string(), state_directory: directory(params, "stateDirectory")?, workspace_state_directory: directory(params, "workspaceStateDirectory")?, @@ -260,10 +310,43 @@ pub fn parse_launch_params(params: &Value) -> Result temporary_directory: directory(params, "temporaryDirectory")?, heap_max_mb, log_level: log_level.to_string(), + server_home, + server_runtime_version: host_tool_version(params, SERVER_RUNTIME_TOOL), java_runtimes: jdt_java_runtimes(&host_java_tool(params)), }) } +/// The `version` of the `tool` installation in the optional `tools` of the +/// request. The contract promises no field, so a missing one is no error. +fn host_tool_version(params: &Value, tool: &str) -> Option { + params + .get("tools")? + .get(tool)? + .get("version")? + .as_str() + .map(str::trim) + .filter(|version| !version.is_empty()) + .map(str::to_string) +} + +/// Refuses a JDT LS runtime the host reported as older than +/// [`MINIMUM_SERVER_JAVA_VERSION`]. A runtime without a readable version is +/// left to the host and to JDT LS, which reports what it cannot run on. +pub fn check_server_runtime(request: &LaunchRequest) -> Result<(), PluginError> { + let feature = request + .server_runtime_version + .as_deref() + .and_then(|version| version.split(['.', '_', '+', '-']).next()) + .and_then(|feature| feature.parse::().ok()); + match feature { + Some(feature) if feature < MINIMUM_SERVER_JAVA_VERSION => Err(PluginError::new( + LAUNCH_RUNTIME_TOO_OLD, + RUNTIME_TOO_OLD_MESSAGE, + )), + _ => Ok(()), + } +} + /// The `java` installation the host resolved, from the optional `tools` /// of the request. The contract has the host leave out a tool it could not /// find and promises only the fields it knows, so a missing or incomplete @@ -333,32 +416,12 @@ fn package_root_from_executable(executable: &Path) -> Option { .map(Path::to_path_buf) } -/// The package path of the Java runtime of `architecture`, as the answer's -/// `executable.path` names it. -pub fn runtime_executable(architecture: &str) -> String { - let executable = if cfg!(windows) { "java.exe" } else { "java" }; - format!("{RUNTIME_DIRECTORY}/{architecture}/bin/{executable}") -} - -/// Finds the JDT LS files of `architecture` in the package at `package_root`. +/// Finds the packaged extensions in the package at `package_root` and +/// takes the JDT LS files from `server`. pub fn locate_launch_files( package_root: &Path, - architecture: &str, + server: &ServerInstallation, ) -> Result { - if !package_root - .join(runtime_executable(architecture)) - .is_file() - { - return Err(missing_resource("the Java runtime")); - } - let launcher_jar = launcher_in(&package_root.join(LAUNCHER_DIRECTORY)) - .ok_or_else(|| missing_resource("the JDT LS launcher"))?; - let packaged_configuration = package_root - .join(CONFIGURATION_DIRECTORY) - .join(architecture); - if !packaged_configuration.is_dir() { - return Err(missing_resource("the JDT LS configuration")); - } let lombok_agent = package_root.join(LOMBOK_AGENT); if !lombok_agent.is_file() { return Err(missing_resource("the Lombok agent")); @@ -368,36 +431,13 @@ pub fn locate_launch_files( .flat_map(|directory| bundles_in(&package_root.join(directory))) .collect(); Ok(LaunchFiles { - launcher_jar, + launcher_jar: server.launcher_jar.clone(), lombok_agent, - packaged_configuration, + server_configuration: server.configuration.clone(), extension_bundles, }) } -/// The one Equinox launcher JAR in `directory`. None or several mean the -/// package is damaged. -fn launcher_in(directory: &Path) -> Option { - let mut launchers: Vec = fs::read_dir(directory) - .ok()? - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| { - name.starts_with(LAUNCHER_PREFIX) && name.ends_with(LAUNCHER_SUFFIX) - }) - && path.is_file() - }) - .collect(); - if launchers.len() == 1 { - launchers.pop() - } else { - None - } -} - /// The `-data` directory of the workspace. pub fn data_directory(request: &LaunchRequest) -> PathBuf { request.workspace_state_directory.join(DATA_DIRECTORY) @@ -461,7 +501,8 @@ pub fn service_ready_gate() -> Value { }) } -/// Resolves the launch for `request` from the package at `package_root`. +/// Resolves the launch for `request` of the JDT LS installation `server` +/// with the extensions of the package at `package_root`. /// /// `fragments` are the settings other plugins contributed for the /// workspace, as the settings session last collected them. The function @@ -470,16 +511,18 @@ pub fn service_ready_gate() -> Value { /// `report` and does not fail the launch. pub fn resolve( request: &LaunchRequest, + server: &ServerInstallation, package_root: &Path, fragments: &[Value], trigger_files: &[String], now_unix_seconds: u64, report: &dyn Fn(&str, u64), ) -> Result { - let files = locate_launch_files(package_root, &request.architecture)?; + check_server_runtime(request)?; + let files = locate_launch_files(package_root, server)?; let area = prepare_jdt_configuration_area( &request.state_directory, - &files.packaged_configuration, + &files.server_configuration, now_unix_seconds, ) .map_err(|error| PluginError::new(LAUNCH_CONFIGURATION_FAILED, error.message))?; @@ -510,9 +553,10 @@ pub fn resolve( .map(|path| Value::String(path.to_string_lossy().into_owned())) .collect(); Ok(json!({ + // The host resolves the tool from the user's choice and discovery. "executable": { - "kind": "packaged", - "path": runtime_executable(&request.architecture), + "kind": "tool", + "tool": SERVER_RUNTIME_TOOL, }, "arguments": jdtls_arguments(request, &files, &area.directory), // JDT LS needs no variable beyond the ones the host passes. @@ -620,6 +664,13 @@ pub fn resolve_launch_function( ) -> Result { context.check_cancelled()?; let request = parse_launch_params(¶ms)?; + check_server_runtime(&request)?; + let server = jdtls::locate( + request.server_home.as_deref(), + &SearchEnvironment::current(), + &request.os, + &request.architecture, + )?; let package_root = package_root()?; let diagnostics = context.diagnostics(); let operation = context.function_id().to_owned(); @@ -649,6 +700,7 @@ pub fn resolve_launch_function( context.check_cancelled()?; let mut answer = resolve( &request, + &server, &package_root, &fragments, &trigger_files, @@ -682,19 +734,14 @@ mod tests { assert_eq!(root, Path::new(r"C:\plugins\Java 支持")); } - #[test] - #[cfg(windows)] - fn windows_runtime_uses_the_packaged_pe_launcher() { - assert_eq!(runtime_executable("x86_64"), "runtime/x86_64/bin/java.exe"); - } use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; - const LAUNCHER: &str = - "language-server/plugins/org.eclipse.equinox.launcher_1.8.0.v20260804-1928.jar"; + const LAUNCHER: &str = "plugins/org.eclipse.equinox.launcher_1.8.0.v20260804-1928.jar"; - /// A package laid out like the assembled one, and the host's four - /// directories, in a fresh directory that is removed on drop. + /// A package laid out like the assembled one, a JDT LS installation like + /// the user's, and the host's four directories, in a fresh directory that + /// is removed on drop. struct Fixture { root: PathBuf, } @@ -710,30 +757,30 @@ mod tests { let _ = fs::remove_dir_all(&root); let package = root.join("package"); for directory in [ - "runtime/arm64/bin", - "language-server/plugins", - "language-server/configuration/arm64", - "language-server/lombok", - "language-server/java-debug", - "language-server/java-test/extensions", + "jdtls-extensions/lombok", + "jdtls-extensions/java-debug", + "jdtls-extensions/java-test/extensions", ] { fs::create_dir_all(package.join(directory)).unwrap(); } - let runtime = runtime_executable("arm64"); for file in [ - runtime.as_str(), - LAUNCHER, - "language-server/plugins/org.eclipse.jdt.ls.core_1.50.0.jar", - "language-server/lombok/lombok.jar", - "language-server/java-debug/com.microsoft.java.debug.plugin-0.53.0.jar", - "language-server/java-test/extensions/b.jar", - "language-server/java-test/extensions/a.jar", - "language-server/java-test/extensions/notes.txt", + "jdtls-extensions/lombok/lombok.jar", + "jdtls-extensions/java-debug/com.microsoft.java.debug.plugin-0.53.0.jar", + "jdtls-extensions/java-test/extensions/b.jar", + "jdtls-extensions/java-test/extensions/a.jar", + "jdtls-extensions/java-test/extensions/notes.txt", ] { fs::write(package.join(file), b"").unwrap(); } + let server = root.join("jdtls"); + for directory in ["plugins", "config_mac_arm"] { + fs::create_dir_all(server.join(directory)).unwrap(); + } + for file in [LAUNCHER, "plugins/org.eclipse.jdt.ls.core_1.50.0.jar"] { + fs::write(server.join(file), b"").unwrap(); + } fs::write( - package.join("language-server/configuration/arm64/config.ini"), + server.join("config_mac_arm/config.ini"), b"osgi.bundles=example\n", ) .unwrap(); @@ -747,6 +794,10 @@ mod tests { self.root.join("package") } + fn server(&self) -> ServerInstallation { + jdtls::inspect(&self.root.join("jdtls"), "config_mac_arm").unwrap() + } + fn params(&self) -> Value { json!({ "serverID": "java", @@ -776,6 +827,7 @@ mod tests { let report = |code: &str, _count: u64| reports.lock().unwrap().push(code.to_string()); resolve( &fixture.request(), + &fixture.server(), &fixture.package(), fragments, &[], @@ -800,7 +852,10 @@ mod tests { fn the_params_are_read_with_the_declared_defaults() { let fixture = Fixture::new(); let request = fixture.request(); + assert_eq!(request.os, "macos"); assert_eq!(request.architecture, "arm64"); + assert_eq!(request.server_home, None); + assert_eq!(request.server_runtime_version, None); assert_eq!(request.heap_max_mb, 4096); assert_eq!(request.log_level, "INFO"); assert_eq!(request.state_directory, fixture.root.join("state")); @@ -810,6 +865,16 @@ mod tests { let request = parse_launch_params(¶ms).unwrap(); assert_eq!(request.heap_max_mb, DEFAULT_HEAP_MAX_MB); assert_eq!(request.log_level, DEFAULT_LOG_LEVEL); + + // An empty folder setting means "find JDT LS"; a folder is taken as is. + params["settings"] = json!({"languageServerHome": ""}); + assert_eq!(parse_launch_params(¶ms).unwrap().server_home, None); + let folder = fixture.root.join("jdtls"); + params["settings"] = json!({"languageServerHome": folder}); + assert_eq!( + parse_launch_params(¶ms).unwrap().server_home, + Some(folder) + ); } #[test] @@ -818,6 +883,8 @@ mod tests { let edits: Vec<(&str, Value)> = vec![ ("/serverID", json!("kotlin")), ("/platform/arch", json!("sparc")), + ("/platform/os", json!("")), + ("/platform/os", Value::Null), ("/stateDirectory", json!("relative/state")), ("/workspaceStateDirectory", Value::Null), ("/settings/heapMaxMB", json!(1024)), @@ -830,6 +897,12 @@ mod tests { let error = parse_launch_params(¶ms).unwrap_err(); assert_eq!(error.code(), LAUNCH_INVALID_PARAMS, "{pointer}"); } + for folder in [json!("relative/jdtls"), json!(7)] { + let mut params = fixture.params(); + params["settings"]["languageServerHome"] = folder; + let error = parse_launch_params(¶ms).unwrap_err(); + assert_eq!(error.code(), LAUNCH_INVALID_PARAMS); + } assert_eq!( parse_launch_params(&json!({})).unwrap_err().code(), LAUNCH_INVALID_PARAMS @@ -837,18 +910,18 @@ mod tests { } #[test] - fn the_answer_runs_the_packaged_runtime_with_the_full_command_line() { + fn the_answer_runs_the_users_jdt_ls_on_the_runtime_tool() { let fixture = Fixture::new(); let (answer, reports) = resolve_fixture(&fixture, &[]); assert!(reports.is_empty()); assert_eq!( answer["executable"], - json!({"kind": "packaged", "path": runtime_executable("arm64")}) + json!({"kind": "tool", "tool": "jdtls-runtime"}) ); let arguments = strings(&answer["arguments"]); let package = fixture.package(); - let launcher = package.join(LAUNCHER).to_string_lossy().into_owned(); - let lombok = package.join("language-server/lombok/lombok.jar"); + let launcher = fixture.server().launcher_jar; + let lombok = package.join("jdtls-extensions/lombok/lombok.jar"); assert_eq!( arguments[0], format!("-javaagent:{}", lombok.to_string_lossy()) @@ -891,6 +964,7 @@ mod tests { assert!(configuration.starts_with(fixture.root.join("state"))); assert!(configuration.join("config.ini").is_file()); assert!(!configuration.starts_with(&package)); + assert!(!configuration.starts_with(fixture.root.join("jdtls"))); let data = fixture.root.join("workspace-state").join("data"); assert_eq!( arguments[arguments.len() - 2..].to_vec(), @@ -907,9 +981,9 @@ mod tests { let (answer, _) = resolve_fixture(&fixture, &[]); let package = fixture.package(); let expected: Vec = [ - "language-server/java-debug/com.microsoft.java.debug.plugin-0.53.0.jar", - "language-server/java-test/extensions/a.jar", - "language-server/java-test/extensions/b.jar", + "jdtls-extensions/java-debug/com.microsoft.java.debug.plugin-0.53.0.jar", + "jdtls-extensions/java-test/extensions/a.jar", + "jdtls-extensions/java-test/extensions/b.jar", ] .iter() .map(|bundle| package.join(bundle)) @@ -1006,7 +1080,16 @@ mod tests { }] ); let report = |_: &str, _: u64| {}; - let answer = resolve(&request, &fixture.package(), &[], &[], 1_000_000, &report).unwrap(); + let answer = resolve( + &request, + &fixture.server(), + &fixture.package(), + &[], + &[], + 1_000_000, + &report, + ) + .unwrap(); assert_eq!( answer["initializationOptions"]["settings"]["java"]["configuration"]["runtimes"], expected @@ -1034,35 +1117,60 @@ mod tests { #[test] fn a_damaged_package_names_the_missing_file() { - let runtime = runtime_executable("arm64"); - for (remove, expected) in [ - (runtime.as_str(), "the Java runtime"), - (LAUNCHER, "the JDT LS launcher"), - ("language-server/lombok/lombok.jar", "the Lombok agent"), - ] { - let fixture = Fixture::new(); - fs::remove_file(fixture.package().join(remove)).unwrap(); - let error = locate_launch_files(&fixture.package(), "arm64").unwrap_err(); - assert_eq!(error.code(), LAUNCH_RESOURCE_MISSING, "{remove}"); - assert_eq!(error.message(), missing_resource_message(expected)); - } - - // The package has no runtime for this architecture. let fixture = Fixture::new(); - let error = locate_launch_files(&fixture.package(), "x86_64").unwrap_err(); + fs::remove_file(fixture.package().join("jdtls-extensions/lombok/lombok.jar")).unwrap(); + let error = locate_launch_files(&fixture.package(), &fixture.server()).unwrap_err(); assert_eq!(error.code(), LAUNCH_RESOURCE_MISSING); + assert_eq!( + error.message(), + missing_resource_message("the Lombok agent") + ); + } - // Two launchers leave the choice open. + #[test] + fn a_runtime_older_than_java_21_is_refused_before_anything_is_written() { let fixture = Fixture::new(); - fs::write( - fixture - .package() - .join("language-server/plugins/org.eclipse.equinox.launcher_1.9.0.jar"), - b"", - ) - .unwrap(); - let error = locate_launch_files(&fixture.package(), "arm64").unwrap_err(); - assert_eq!(error.code(), LAUNCH_RESOURCE_MISSING); + let mut params = fixture.params(); + for (version, accepted) in [ + ("17.0.19", false), + ("8.0.392", false), + ("21", true), + ("21.0.9", true), + ("26.0.2", true), + ("unknown", true), + ] { + params["tools"] = json!({ + "jdtls-runtime": {"executable": "/jdk/bin/java", "home": "/jdk", "version": version} + }); + let request = parse_launch_params(¶ms).unwrap(); + assert_eq!( + check_server_runtime(&request).is_ok(), + accepted, + "{version}" + ); + if !accepted { + let report = |_: &str, _: u64| {}; + let error = resolve( + &request, + &fixture.server(), + &fixture.package(), + &[], + &[], + 1_000_000, + &report, + ) + .unwrap_err(); + assert_eq!(error.code(), LAUNCH_RUNTIME_TOO_OLD); + assert_eq!(error.message(), RUNTIME_TOO_OLD_MESSAGE); + } + } + assert!(fs::read_dir(fixture.root.join("state")) + .unwrap() + .next() + .is_none()); + // Without a version the host's own resolution decides. + params["tools"] = json!({}); + assert!(check_server_runtime(&parse_launch_params(¶ms).unwrap()).is_ok()); } #[test] @@ -1143,6 +1251,7 @@ mod tests { let trigger = vec!["file:///w/src/demo/Main.java".to_string()]; let answer = resolve( &fixture.request(), + &fixture.server(), &fixture.package(), &[], &trigger, diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 071af2d..b378783 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -16,7 +16,8 @@ //! The manifest declares the `java` language server with //! `launch.kind: "backend"`, so the host asks [`launch`] for the JDT LS //! command line, initialization options and startup settings before each -//! start. The launch reads the settings the [`settings_session`] knows for +//! start. JDT LS is the user's own installation, which [`jdtls`] finds. +//! The launch reads the settings the [`settings_session`] knows for //! the workspace, so a restart starts with the last pushed settings. //! //! # Cross-plugin settings (API-35) @@ -48,6 +49,7 @@ //! stderr, and a fact carries no path, source or tool output. pub mod class_content; +pub mod jdtls; pub mod launch; pub mod plugin_functions; pub mod project_settings; diff --git a/backend/tests/repository_pins.rs b/backend/tests/repository_pins.rs index 482bf9c..d6042e4 100644 --- a/backend/tests/repository_pins.rs +++ b/backend/tests/repository_pins.rs @@ -6,7 +6,11 @@ //! platform in `cargo test`; the assembled package is checked separately by //! `scripts/verify-package.sh`. -use lithe_java_backend::launch::{LAUNCHER_PREFIX, LAUNCH_FUNCTION_ID, PACKAGE_LAYOUT}; +use lithe_java_backend::jdtls::SERVER_HOME_SETTING; +use lithe_java_backend::launch::{ + EXTENSIONS_DIRECTORY, LAUNCH_FUNCTION_ID, MINIMUM_SERVER_JAVA_VERSION, PACKAGE_LAYOUT, + SERVER_RUNTIME_TOOL, +}; use serde_json::Value; use std::fs; use std::path::{Path, PathBuf}; @@ -168,14 +172,15 @@ fn language_server_launch_is_resolved_by_the_backend() { #[test] fn package_scripts_name_every_path_the_backend_resolves() { - // plugin.json no longer lists the language server files, so the scripts - // that assemble and verify the package are held to the backend's layout. + // plugin.json does not list the packaged JDT LS extensions, so the + // scripts that assemble and verify the package are held to the backend's + // layout. for script in ["scripts/assemble-package.sh", "scripts/verify-package.sh"] { let source = read(script); for path in PACKAGE_LAYOUT { assert!( - path.starts_with("language-server/") || *path == "runtime", - "{path} must stay inside language-server/ or runtime/" + path.starts_with(&format!("{EXTENSIONS_DIRECTORY}/")), + "{path} must stay inside {EXTENSIONS_DIRECTORY}/" ); assert!( !path.split('/').any(|part| part == ".."), @@ -183,31 +188,73 @@ fn package_scripts_name_every_path_the_backend_resolves() { ); assert!(source.contains(path), "{script} does not check {path}"); } - assert!( - source.contains(LAUNCHER_PREFIX), - "{script} does not check for the Equinox launcher JAR" - ); } } +#[test] +fn the_users_jdt_ls_runs_on_the_declared_runtime_tool() { + // JDT LS and its JDK come from the user's machine: the package ships + // neither, the backend answers the runtime tool the manifest defines, and + // the user can choose the JDT LS folder in a setting the backend reads. + let manifest = read_json(&format!("{PLUGIN_ID}/plugin.json")); + let tools: Vec<&str> = manifest["requiresTools"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool.as_str().unwrap()) + .collect(); + assert_eq!(tools, ["java", SERVER_RUNTIME_TOOL]); + let definitions = manifest["toolDefinitions"].as_array().unwrap(); + let runtime = definitions + .iter() + .find(|definition| definition["id"] == SERVER_RUNTIME_TOOL) + .expect("the manifest defines the JDT LS runtime tool"); + let java = definitions + .iter() + .find(|definition| definition["id"] == "java") + .unwrap(); + // The runtime finds JDKs where the project JDK is found. + assert_eq!(runtime["discovery"], java["discovery"]); + assert_eq!(runtime["executableLayouts"], java["executableLayouts"]); + // It exports nothing, so JDT LS keeps the environment the host gives it. + assert!(runtime.get("exports").is_none()); + assert!(runtime.get("pathPrepend").is_none()); + + let setting = manifest["settings"] + .as_array() + .unwrap() + .iter() + .find(|setting| setting["id"] == SERVER_HOME_SETTING) + .expect("the manifest declares the JDT LS folder setting"); + assert_eq!(text(setting, "type"), "directory"); + assert_eq!(text(setting, "default"), ""); + + let pins = read_json("third_party/jdtls/manifest.json"); + assert_eq!( + pins["minimumJavaVersion"].as_u64(), + Some(MINIMUM_SERVER_JAVA_VERSION), + "the tested JDT LS and the backend must agree on its oldest Java" + ); + assert!( + !repository_root().join("third_party/jdk").exists(), + "the package ships no JDK" + ); +} + #[test] fn third_party_inputs_are_pinned_by_https_url_and_sha256() { - for relative in [ - "third_party/jdtls/manifest.json", - "third_party/jdk/manifest.json", - ] { - let mut pins = 0; - visit(&read_json(relative), &mut |key, value| { - let lowered = key.to_ascii_lowercase(); - if lowered.ends_with("sha256") { - assert_sha256(value, &format!("{relative} {key}")); - pins += 1; - } else if lowered.ends_with("url") { - assert!(value.starts_with("https://"), "{relative} {key}: {value}"); - } - }); - assert!(pins >= 4, "{relative} pins only {pins} checksums"); - } + let relative = "third_party/jdtls/manifest.json"; + let mut pins = 0; + visit(&read_json(relative), &mut |key, value| { + let lowered = key.to_ascii_lowercase(); + if lowered.ends_with("sha256") { + assert_sha256(value, &format!("{relative} {key}")); + pins += 1; + } else if lowered.ends_with("url") { + assert!(value.starts_with("https://"), "{relative} {key}: {value}"); + } + }); + assert!(pins >= 4, "{relative} pins only {pins} checksums"); } #[test] diff --git a/crates/java-domain/src/jdt_integration/launch_resources.rs b/crates/java-domain/src/jdt_integration/launch_resources.rs index 23c040e..a0efcc3 100644 --- a/crates/java-domain/src/jdt_integration/launch_resources.rs +++ b/crates/java-domain/src/jdt_integration/launch_resources.rs @@ -2,9 +2,10 @@ //! //! Ported from the Swift `MacJdtLaunchResources`. The package layout itself is //! fixed by `backend/src/launch.rs`, which resolves the launch for the host -//! (`launch.kind: "backend"`); exactly the packaged files are handed over, -//! nothing searches the host application or the machine for JDT LS, so -//! removing the plugin removes Java language support with it. +//! (`launch.kind: "backend"`). The package carries only the extensions the +//! plugin adds to JDT LS (Lombok, Java Debug, Java Test); JDT LS itself is the +//! user's installation, which `backend/src/jdtls.rs` finds. Nothing searches +//! the host application for either. use std::fs; use std::path::{Path, PathBuf}; diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index c89621c..d305437 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -1,5 +1,15 @@ # 功能验证矩阵 +## 语言服务器来源(3.0.0) + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| 使用用户安装的 JDT LS(设置目录、`JDTLS_HOME`、`PATH` 上的 `jdtls`、Homebrew、mason.nvim、Scoop、VS Code Java 扩展) | implemented / verified | implemented / pending | implemented / pending | `backend/src/jdtls.rs` 单元测试;macOS arm64 本机用 Homebrew JDT LS 1.60.0 和固定的 1.61.0 跑 `scripts/compiler/test-live.mjs`(普通与 Eclipse 工程),核对插件包与 JDT LS 安装文件不变 | +| 用 `jdtls-runtime` 工具(JDK 21+)运行 JDT LS,低于 21 时报错 | implemented / verified | implemented / pending | implemented / pending | `backend/src/launch.rs` 单元测试;本机 JDK 21、26 均已验证,JDK 26 运行 JDT LS 时需宿主传入项目 JDK | +| 插件包不含 JDT LS 和 JDK | implemented / verified | implemented / pending | implemented / pending | `scripts/verify-package.sh`、`scripts/package/build-linux.mjs`;macOS arm64 包 11.3 MiB | + +2026-11-16:Windows 与 Linux 的原生结果以 CI 和后续实机验证为准,本机结果不能推断。 + ## Linux 安装包 | 能力 | Linux ARM64 | Linux x64 | 验证入口 | diff --git a/docs/linux-packaging.md b/docs/linux-packaging.md index 4befcab..db78da0 100644 --- a/docs/linux-packaging.md +++ b/docs/linux-packaging.md @@ -1,8 +1,8 @@ # Linux 构建与验证 -`node scripts/package/build-linux.mjs arm64|x64` 在对应 Linux runner 上编译 Rust 后端,校验其 ELF 架构,再从固定 SHA-256 的 Temurin JDK、JDT LS、Lombok、Java Debug 和 Java Test 输入组装包。ARM64 使用 `config_linux_arm`,x64 使用 `config_linux`。JDK 上游符号链接仅在构建时展开,插件 ZIP 不含链接。完整许可证与反编译补丁校验沿用已有流程。归档解压后再次检查清单、JDK/后端/VM 架构、执行权限和配置。 +`node scripts/package/build-linux.mjs arm64|x64` 在对应 Linux runner 上编译 Rust 后端,校验其 ELF 架构,再从固定 SHA-256 的 Lombok、Java Debug 和 Java Test 输入组装包。包里不含 JDT LS 和 JDK:插件运行用户自己安装的 JDT LS 和 JDK 21+,ARM64 读取安装里的 `config_linux_arm`,x64 读取 `config_linux`。插件 ZIP 不含链接。归档解压后再次检查清单、后端架构与执行权限,并确认包里没有 JDT LS 或 JDK。 -`node scripts/package/smoke-linux.mjs ` 在原生 runner 上运行解压后的后端握手与 `java.resolveLaunch`,启动包内 Java 和 JDT LS,执行 initialize/shutdown,并对比整个安装目录的文件内容与权限。状态目录和 Equinox 配置副本在临时用户目录;结束时清理进程组和目录。 +`node scripts/package/smoke-linux.mjs ` 在原生 runner 上运行解压后的后端握手与 `java.resolveLaunch`,把 `scripts/prepare-jdtls.sh` 准备的 JDT LS 1.61.0 当作用户的安装(CI 用 `actions/setup-java` 提供 JDK 21),执行 initialize/shutdown,并对比整个安装目录和 JDT LS 目录的文件内容与权限。状态目录和 Equinox 配置副本在临时用户目录;结束时清理进程组和目录。 Linux 产物面向 GNU/glibc 环境,原生 CI 使用 Ubuntu 24.04;本包不面向 musl/Alpine。 diff --git a/docs/releases/v3.0.0.md b/docs/releases/v3.0.0.md new file mode 100644 index 0000000..1bbf734 --- /dev/null +++ b/docs/releases/v3.0.0.md @@ -0,0 +1,63 @@ +# Java 3.0.0 + +## 中文 + +Java Support 不再随包附带 Eclipse JDT Language Server 和运行它的 JDK,改为使用你电脑上安装的 JDT LS,做法和 Go 插件使用你自己的 `gopls` 一样。插件包从约 250 MB 降到几 MB,安装和更新不再需要下载语言服务器。 + +### 不兼容变更 + +升级后需要先在电脑上准备两样东西,否则打开 Java 文件时语言服务不会启动: + +- **Eclipse JDT Language Server**。插件按以下顺序查找,用第一个找到的: + 1. 设置 → 语言与框架 → Java →「语言服务器目录」(新增)。在这里选了目录,就只用这个目录,目录不对时直接报错,不会再去找别的安装; + 2. 环境变量 `JDTLS_HOME`; + 3. `PATH` 上的 `jdtls` 启动脚本所属的安装; + 4. 包管理器的安装位置:Homebrew(`brew install jdtls`)、Linuxbrew、mason.nvim、Scoop; + 5. VS Code Java 扩展(`redhat.java`)自带的语言服务器,取最新版本。 +- **JDK 21 或更新版本**,用来运行 JDT LS。它是新增的「JDK for JDT LS」工具,在设置 → 构建、执行、部署 → 工具链里显示和选择。不选时自动使用找到的最高版本 JDK。项目自己用的 JDK 仍然是原来的「JDK」工具,可以是 Java 8 等旧版本,两者互不影响。JDK 搜索位置新增 Homebrew 的 `openjdk` 和 `openjdk@N`。 + +找不到 JDT LS 或运行它的 JDK 低于 21 时,语言服务启动失败,错误信息会说明怎么安装或去哪里设置。 + +### 其他变化 + +- 插件包只保留插件自己加给 JDT LS 的内容:Lombok、java-debug 和 vscode-java-test 的扩展包。调试、测试和 Lombok 支持不变。 +- 不再修补 JDT LS 的反编译器。2.0 的包修补了 JDT LS 1.61 遇到缺失内部类时整个外部类反编译为空的问题,现在使用你安装的 JDT LS,这个修补不再生效:缺少内部类的残缺旧库,打开反编译类可能为空。 +- 已测试的 JDT LS 版本:1.61.0(CI 固定版本)和 Homebrew 1.60.0。更旧的版本可能和随包的 java-debug、vscode-java-test 扩展不兼容。 +- JDT 只能为它支持的 Java 版本编译。没有为项目选 JDK 时,JDT 用运行它的 JDK 编译;这个 JDK 比 JDT LS 支持的最新 Java 还新(例如 JDT LS 1.61 跑在 JDK 26 上)时,编译会报错。为项目选择 JDK 即可。 + +### 兼容性 + +宿主要求与 2.0.1 相同,需要支持 `launch.kind: "backend"` 的语言服务器启动和 `{kind: "tool"}` 的启动答复。 +插件声明了 `jdtls-runtime` 工具,宿主需要按 `requiresTools` 把它的解析结果传给启动函数,才能在 JDK 低于 21 时给出明确提示;不传时由宿主的工具解析和 JDT LS 自己报错。 + +--- + +## English + +Java Support no longer bundles the Eclipse JDT Language Server or the JDK that runs it. It uses the JDT LS installed on your computer, the same way the Go plugin uses your own `gopls`. The package shrinks from about 250 MB to a few MB, and installing or updating the plugin no longer downloads a language server. + +### Breaking changes + +Before the language server can start, the computer needs: + +- **Eclipse JDT Language Server.** The plugin uses the first one it finds: + 1. Settings → Languages & Frameworks → Java → **Language server folder** (new). A folder chosen there is the only one used; a folder without JDT LS fails the start instead of falling back to another installation; + 2. the `JDTLS_HOME` environment variable; + 3. the installation of a `jdtls` launcher on `PATH`; + 4. package-manager locations: Homebrew (`brew install jdtls`), Linuxbrew, mason.nvim and Scoop; + 5. the language server inside the VS Code Java extension (`redhat.java`), newest version first. +- **JDK 21 or later** to run JDT LS. It is the new **JDK for JDT LS** tool, listed and chosen under Settings → Build, Execution, Deployment → Toolchains. Without a choice the highest JDK found is used. The project's own JDK is still the **JDK** tool and may be an older release such as Java 8; the two are independent. JDK discovery now also covers Homebrew's `openjdk` and `openjdk@N`. + +When JDT LS is missing, or the JDK for it is older than 21, the language server does not start and the error says how to install or where to choose it. + +### Other changes + +- The package keeps only what the plugin adds to JDT LS: Lombok and the java-debug and vscode-java-test extension bundles. Debugging, tests and Lombok work as before. +- The JDT LS decompiler is no longer patched. The 2.0 package fixed JDT LS 1.61 decompiling an outer class to nothing when an inner class is missing; with your own JDT LS that fix no longer applies, so classes of incomplete legacy libraries may open empty. +- Tested JDT LS versions: 1.61.0 (pinned in CI) and Homebrew 1.60.0. Older versions may not work with the packaged java-debug and vscode-java-test bundles. +- JDT compiles only for the Java releases it supports. Without a JDK chosen for the project, JDT compiles against the JDK that runs it; when that JDK is newer than the latest Java the JDT LS supports (for example JDT LS 1.61 on JDK 26), compilation fails. Choose a JDK for the project. + +### Compatibility + +Host requirements are unchanged from 2.0.1: a backend-resolved language server launch (`launch.kind: "backend"`) answered with `{kind: "tool"}`. +The plugin declares the `jdtls-runtime` tool; a host that passes its resolution to the launch function, as `requiresTools` asks, gets a clear error for a JDK older than 21. Otherwise the host's tool resolution and JDT LS report the problem. diff --git a/io.github.lithe-idea.java-support/l10n/zh-Hans.json b/io.github.lithe-idea.java-support/l10n/zh-Hans.json index fde8cd0..eb99e08 100644 --- a/io.github.lithe-idea.java-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.java-support/l10n/zh-Hans.json @@ -1,4 +1,28 @@ { + "settings": { + "languageServerHome": { + "title": "语言服务器目录", + "description": "Eclipse JDT Language Server 的目录,即包含 plugins 和 config 目录的那一层。留空时自动查找:JDTLS_HOME、PATH 上的 jdtls,以及 Homebrew、mason.nvim、Scoop 或 VS Code Java 扩展安装的 JDT LS。", + "placeholder": "自动查找" + }, + "heapMaxMB": { + "title": "最大内存", + "description": "Java 语言服务器堆内存的上限。大型多模块项目可以调高。" + }, + "logLevel": { + "title": "语言服务器日志级别", + "description": "Java 语言服务器写入自身日志的详细程度。级别越安静,写盘越少。", + "options": { + "ALL": "全部消息", + "INFO": "信息", + "WARNING": "警告", + "SEVERE": "仅错误" + } + } + }, + "sections": { + "Language server": "语言服务器" + }, "settingActions": { "compiler": { "title": "读取编译设置", diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index 2b2785f..9871f81 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -2,10 +2,10 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-support", "displayName": "Java Support", - "version": "2.0.1", + "version": "3.0.0", "pluginAPIVersion": 0, "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0, "sourceSettings": 0}, - "requiresTools": ["java"], + "requiresTools": ["java", "jdtls-runtime"], "vendor": { "id": "io.github.lithe-idea", "displayName": "Lithe Community", @@ -216,6 +216,36 @@ "macos", "linux" ] + }, + { + "root": { + "kind": "absolute", + "path": "/opt/homebrew/opt" + }, + "pattern": "openjdk*/libexec/openjdk.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/local/opt" + }, + "pattern": "openjdk*/libexec/openjdk.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/home/linuxbrew/.linuxbrew/opt" + }, + "pattern": "openjdk*/libexec", + "platforms": [ + "linux" + ] } ], "homeVariable": "JAVA_HOME", @@ -243,6 +273,222 @@ "${entry}", "${arguments}" ] + }, + { + "id": "jdtls-runtime", + "displayName": "JDK for JDT LS", + "icon": { + "host": "plugin" + }, + "executableLayouts": [ + { + "path": "bin/java", + "platforms": [ + "macos", + "linux" + ] + }, + { + "path": "bin/java.exe", + "platforms": [ + "windows" + ] + } + ], + "executables": [ + { + "id": "default", + "kind": "setting", + "settingID": "executable", + "layer": "global" + }, + { + "id": "global-request", + "kind": "toolchain", + "scope": "global" + }, + { + "id": "shell", + "kind": "command", + "command": "java" + }, + { + "id": "detected", + "kind": "toolchain", + "scope": "installed" + } + ], + "version": { + "arguments": [ + "-version" + ], + "pattern": "version \\\"(?:1\\.)?(\\d+(?:\\.\\d+)*)" + }, + "homeLayouts": [ + { + "match": "*.jdk", + "home": "Contents/Home", + "platforms": [ + "macos" + ] + }, + { + "match": "*", + "home": "." + } + ], + "discovery": [ + { + "root": { + "kind": "absolute", + "path": "/Library/Java/JavaVirtualMachines" + }, + "pattern": "*.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "home" + }, + "pattern": "Library/Java/JavaVirtualMachines/*.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\Java" + }, + "pattern": "*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\Eclipse Adoptium" + }, + "pattern": "*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\Microsoft" + }, + "pattern": "jdk-*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\Zulu" + }, + "pattern": "*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\Amazon Corretto" + }, + "pattern": "*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "C:\\Program Files\\BellSoft" + }, + "pattern": "*", + "platforms": [ + "windows" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/lib/jvm" + }, + "pattern": "*", + "platforms": [ + "linux" + ] + }, + { + "root": { + "kind": "home" + }, + "pattern": ".jdks/*", + "platforms": [ + "windows", + "linux" + ] + }, + { + "root": { + "kind": "home" + }, + "pattern": ".sdkman/candidates/java/*", + "platforms": [ + "macos", + "linux" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/opt/homebrew/opt" + }, + "pattern": "openjdk*/libexec/openjdk.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/usr/local/opt" + }, + "pattern": "openjdk*/libexec/openjdk.jdk", + "platforms": [ + "macos" + ] + }, + { + "root": { + "kind": "absolute", + "path": "/home/linuxbrew/.linuxbrew/opt" + }, + "pattern": "openjdk*/libexec", + "platforms": [ + "linux" + ] + } + ], + "commands": [ + "java" + ], + "wrappers": [], + "launch": [ + "${executable}", + "${runtimeArguments}", + "-jar", + "${entry}", + "${arguments}" + ] } ], "languages": [ @@ -283,6 +529,18 @@ } ], "settings": [ + { + "id": "languageServerHome", + "type": "directory", + "title": "Language server folder", + "description": "Folder of the Eclipse JDT Language Server, the one that contains plugins and the config folders. Leave empty to find JDT LS installed with Homebrew, mason.nvim, Scoop or the VS Code Java extension, or through JDTLS_HOME or jdtls on PATH.", + "default": "", + "placeholder": "Automatic", + "page": { + "languageID": "java" + }, + "section": "Language server" + }, { "id": "heapMaxMB", "type": "integer", diff --git a/scripts/assemble-package.sh b/scripts/assemble-package.sh index 1db6497..8bc198d 100755 --- a/scripts/assemble-package.sh +++ b/scripts/assemble-package.sh @@ -2,16 +2,19 @@ set -euo pipefail -# Assembles the resources of the Java Support plugin package: the pinned -# JDT LS distribution with its Lombok, Debug, and Test extensions, the JDK it -# runs on, and the plugin backend (the Rust binary lithe-java-backend, built -# here for the requested architecture and placed where plugin.json's -# backend.launch.path names it). The third-party inputs are fetched and -# checksum-verified by the shared prepare scripts; this script only arranges -# the result in the layout the backend expects (backend/src/launch.rs), plus the icons and template -# directories of the New Project entries (Java, Spring Boot). The assembled -# package is read-only at runtime; projects are generated in the user's chosen -# folder. +# Assembles the resources of the Java Support plugin package: what the plugin +# adds to the user's own JDT LS (the Lombok agent and the Java Debug and Java +# Test extension bundles) and the plugin backend (the Rust binary +# lithe-java-backend, built here for the requested architecture and placed +# where plugin.json's backend.launch.path names it). JDT LS itself and the JDK +# it runs on are not packaged: the backend finds the user's installation +# (backend/src/jdtls.rs). The third-party inputs are fetched and +# checksum-verified by scripts/prepare-jdtls.sh, which also prepares the +# tested JDT LS release the extension set is checked against; this script +# only arranges the extensions in the layout the backend expects +# (backend/src/launch.rs), plus the icons and template directories of the New +# Project entries (Java, Spring Boot). The assembled package is read-only at +# runtime; projects are generated in the user's chosen folder. # Moved from Plugins/mac/Official/JavaSupport/assemble-package.sh in the Lithe # repository; see MIGRATION.md. @@ -29,23 +32,14 @@ while [[ $# -gt 0 ]]; do done [[ -n "$OUTPUT_DIR" ]] || { print -u2 -- "--output is required"; exit 2; } case "$ARCH" in - arm64) - runtime_architectures=("$ARCH") - backend_targets=(aarch64-apple-darwin) - ;; - x86_64) - runtime_architectures=("$ARCH") - backend_targets=(x86_64-apple-darwin) - ;; - universal) - runtime_architectures=(arm64 x86_64) - backend_targets=(aarch64-apple-darwin x86_64-apple-darwin) - ;; + arm64) backend_targets=(aarch64-apple-darwin) ;; + x86_64) backend_targets=(x86_64-apple-darwin) ;; + universal) backend_targets=(aarch64-apple-darwin x86_64-apple-darwin) ;; *) print -u2 -- "Unsupported architecture: $ARCH"; exit 2 ;; esac # plugin.json says where the host starts the backend from. The package keeps -# it in bin/, the one directory (besides runtime/) that may hold an executable. +# it in bin/, the one directory that may hold an executable. backend_path=$(/usr/bin/plutil -extract backend.launch.path raw -o - "$PLUGIN_DIR/plugin.json") [[ "$backend_path" == bin/* && "$backend_path" != *..* ]] || { print -u2 -- "plugin.json backend.launch.path must name a file inside bin/, found: $backend_path" @@ -53,46 +47,21 @@ backend_path=$(/usr/bin/plutil -extract backend.launch.path raw -o - "$PLUGIN_DI } jdtls_root=$(LITHE_ARCH="$ARCH" "$ROOT_DIR/scripts/prepare-jdtls.sh") -language_server="$OUTPUT_DIR/language-server" -rm -rf "$language_server" "$OUTPUT_DIR/runtime" "$OUTPUT_DIR/icons" "$OUTPUT_DIR/templates" "$OUTPUT_DIR/l10n" "$OUTPUT_DIR/bin" +extensions="$OUTPUT_DIR/jdtls-extensions" +rm -rf "$extensions" "$OUTPUT_DIR/icons" "$OUTPUT_DIR/templates" "$OUTPUT_DIR/l10n" "$OUTPUT_DIR/bin" cp -R "$PLUGIN_DIR/icons" "$OUTPUT_DIR/icons" cp -R "$PLUGIN_DIR/templates" "$OUTPUT_DIR/templates" cp -R "$PLUGIN_DIR/l10n" "$OUTPUT_DIR/l10n" -mkdir -p "$language_server/configuration" +mkdir -p "$extensions" -# Only what a macOS launch reads is packaged. The wrapper scripts and the -# configuration areas of other platforms are left out. -for entry in plugins features lombok java-debug java-test manifest.json LICENSE-EPL-2.0.txt; do +# Only the extensions are packaged, with their licenses and the pins they +# were verified against. JDT LS itself (plugins, features, config_*) stays out. +for entry in lombok java-debug java-test manifest.json; do [[ -e "$jdtls_root/$entry" ]] || { - print -u2 -- "JDT LS distribution is missing $entry: $jdtls_root" + print -u2 -- "Prepared JDT LS extensions are missing $entry: $jdtls_root" exit 1 } - cp -R "$jdtls_root/$entry" "$language_server/$entry" -done - -# Equinox reads one configuration per architecture. The packaged copy stays -# read-only; the host gives each launch a writable area in its cache. -for runtime_arch in "${runtime_architectures[@]}"; do - case "$runtime_arch" in - arm64) configuration_name="config_mac_arm" ;; - x86_64) configuration_name="config_mac" ;; - esac - [[ -f "$jdtls_root/$configuration_name/config.ini" ]] || { - print -u2 -- "JDT LS configuration is missing: $jdtls_root/$configuration_name/config.ini" - exit 1 - } - mkdir -p "$language_server/configuration/$runtime_arch" - cp "$jdtls_root/$configuration_name/config.ini" "$language_server/configuration/$runtime_arch/config.ini" - - if [[ "$ARCH" == "universal" ]]; then - override_variable="LITHE_JDK_${runtime_arch:u}_ROOT" - jdk_root=$(LITHE_JDK_ROOT="${(P)override_variable:-}" LITHE_JDK_TARGET_ARCH="$runtime_arch" \ - "$ROOT_DIR/scripts/prepare-jdk.sh") - else - jdk_root=$(LITHE_JDK_TARGET_ARCH="$runtime_arch" "$ROOT_DIR/scripts/prepare-jdk.sh") - fi - mkdir -p "$OUTPUT_DIR/runtime" - cp -R "$jdk_root" "$OUTPUT_DIR/runtime/$runtime_arch" + cp -R "$jdtls_root/$entry" "$extensions/$entry" done # The plugin backend is one Mach-O binary: a single architecture is copied as @@ -119,41 +88,26 @@ else fi chmod 755 "$OUTPUT_DIR/$backend_path" -# The backend resolves the language server launch (plugin.json declares only +# The backend resolves the language server launch (plugin.json declares # the function), so the layout it expects is fixed in backend/src/launch.rs -# and checked here, where a JDT LS upgrade that renames or moves a file fails -# instead of at the user's first Java file. backend/tests/repository_pins.rs -# holds this list to the backend's. -launchers=("$OUTPUT_DIR"/language-server/plugins/org.eclipse.equinox.launcher_*.jar(N)) -(( ${#launchers} == 1 )) || { - print -u2 -- "language-server/plugins must hold exactly one org.eclipse.equinox.launcher_*.jar, found ${#launchers}" - exit 1 -} +# and checked here, where an extension upgrade that renames or moves a file +# fails instead of at the user's first Java file. +# backend/tests/repository_pins.rs holds this list to the backend's. for declared in \ - language-server/lombok/lombok.jar \ - language-server/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar \ + jdtls-extensions/lombok/lombok.jar \ + jdtls-extensions/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar \ "$backend_path"; do [[ -f "$OUTPUT_DIR/$declared" ]] || { - print -u2 -- "The backend expects $declared, which the assembled package does not contain. Update scripts/prepare-jdtls.sh or backend/src/launch.rs for the pinned JDT LS version." + print -u2 -- "The backend expects $declared, which the assembled package does not contain. Update scripts/prepare-jdtls.sh or backend/src/launch.rs for the pinned extensions." exit 1 } done -for directory in language-server/java-debug language-server/java-test/extensions; do +for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions; do [[ -n "$(find "$OUTPUT_DIR/$directory" -maxdepth 1 -name '*.jar' -print -quit 2>/dev/null)" ]] || { print -u2 -- "extension bundle directory $directory holds no bundles" exit 1 } done -for runtime_arch in "${runtime_architectures[@]}"; do - [[ -f "$OUTPUT_DIR/language-server/configuration/$runtime_arch/config.ini" ]] || { - print -u2 -- "missing language-server/configuration/$runtime_arch/config.ini" - exit 1 - } - [[ -x "$OUTPUT_DIR/runtime/$runtime_arch/bin/java" ]] || { - print -u2 -- "missing runtime/$runtime_arch/bin/java" - exit 1 - } -done # The contract forbids symbolic links inside a package. if [[ -n "$(find "$OUTPUT_DIR" -type l -print -quit)" ]]; then @@ -163,6 +117,3 @@ fi # Notices are build inputs, copied alongside the binary from locked sources. node "$ROOT_DIR/scripts/package/collect-notices.mjs" "$OUTPUT_DIR" >&2 - -# Compile the locked upstream decompiler fix only in package staging. -node "$ROOT_DIR/scripts/package/patch-jdt-decompiler.mjs" "$OUTPUT_DIR" >&2 diff --git a/scripts/compiler/test-live.mjs b/scripts/compiler/test-live.mjs index 9b9ca10..5f91f15 100644 --- a/scripts/compiler/test-live.mjs +++ b/scripts/compiler/test-live.mjs @@ -1,4 +1,4 @@ -// Real packaged JDT + SDK backend, with bounded process ownership. This tests +// The user's JDT LS + packaged SDK backend, with bounded process ownership. This tests // native sources reaching the engine rather than only checking RPC invocation. import assert from 'node:assert/strict'; import {createReport} from '../report.mjs'; @@ -8,9 +8,11 @@ import {tmpdir} from 'node:os'; import {join,resolve} from 'node:path'; import {pathToFileURL,fileURLToPath} from 'node:url'; import {runTool} from './process.mjs'; +import {spawnSync} from 'node:child_process'; import {createHash} from 'node:crypto'; import {setTimeout as delay} from 'node:timers/promises'; import {Client} from '../package/lsp-client.mjs'; +import {serverInputs,answeredExecutable} from '../package/jdtls-test-inputs.mjs'; const pkg=resolve(process.argv[2]??'.artifacts/package/arm64/io.github.lithe-idea.java-support'); const manifest=JSON.parse(readFileSync(join(pkg,'plugin.json'))); const stage=realpathSync.native(mkdtempSync(join(tmpdir(),'lithe-java-native-'))); @@ -21,7 +23,11 @@ if(eclipse){mkdirSync(join(root,'src'));writeFileSync(join(root,'.project'),'process.platform==='win32'?resolve(left).toLowerCase()===resolve(right).toLowerCase():resolve(left)===resolve(right); const snapshot=root=>{const items=[];const visit=(path,label)=>{const stat=lstatSync(path);assert.equal(stat.isSymbolicLink(),false);items.push([label,stat.mode,stat.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(stat.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name),`${label}/${name}`);};visit(root,'');return items;}; -const baseline=snapshot(pkg); +const inputs=serverInputs(); +// LITHE_TEST_PROJECT_JAVA_HOME stands for the project JDK the host resolves for +// the java tool; without it JDT compiles against the JDK that runs it. +const projectJava=()=>{const home=process.env.LITHE_TEST_PROJECT_JAVA_HOME;if(!home)return {};const probe=spawnSync(join(home,'bin',process.platform==='win32'?'java.exe':'java'),['-version'],{encoding:'utf8',timeout:15000});const version=/version "(?:1\.)?(\d+(?:\.\d+)*)/.exec(probe.stderr)?.[1];assert.ok(version,`Cannot read the version of ${home}`);return {java:{executable:join(home,'bin','java'),home,version}};}; +const baseline=snapshot(pkg);const serverBaseline=snapshot(inputs.home); const folders=[{rootID:'root',name:'workspace',path:root,uri:pathToFileURL(root).href}]; const execute=(command,args=[])=>server.request('workspace/executeCommand',{command,arguments:args}); const report=createReport(eclipse?'native-jdt-eclipse':'native-jdt-unmanaged'); @@ -40,10 +46,10 @@ try{ }; backend=new Client(join(pkg,manifest.backend.launch.path),[],{hostRequests}); await backend.request('initialize',{processId:process.pid,rootUri:pathToFileURL(root).href,capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}});backend.notify('initialized',{}); - const params={serverID:'java',platform:{os:process.platform==='darwin'?'macos':process.platform,arch:process.env.LITHE_TEST_ARCH??(process.arch==='arm64'?'arm64':'x86_64')},settings:{logLevel:'WARNING'}}; + const params={serverID:'java',platform:{os:{darwin:'macos',win32:'windows'}[process.platform]??process.platform,arch:process.env.LITHE_TEST_ARCH??(process.arch==='arm64'?'arm64':'x86_64')},settings:{logLevel:'WARNING',languageServerHome:inputs.home},tools:{...inputs.tools,...projectJava()}}; for(const[key,name]of Object.entries({stateDirectory:'state',workspaceStateDirectory:'workspace-state',logDirectory:'logs',temporaryDirectory:'tmp'})){params[key]=join(stage,name);mkdirSync(params[key]);} const launch=await backend.request('lithe/function/invoke',{functionID:'java.resolveLaunch',operationID:`native-${++op}`,params,context});configuration=launch.workspaceConfiguration; - server=new Client(join(pkg,launch.executable.path),launch.arguments,{env:{...process.env,...launch.environment},hostRequests:{'workspace/configuration':p=>p.items.map(item=>item.section?item.section.split('.').reduce((value,key)=>value?.[key],configuration)??null:configuration)}}); + server=new Client(answeredExecutable(launch,inputs),launch.arguments,{env:{...process.env,...launch.environment},hostRequests:{'workspace/configuration':p=>p.items.map(item=>item.section?item.section.split('.').reduce((value,key)=>value?.[key],configuration)??null:configuration)}}); await server.request('initialize',{processId:process.pid,rootUri:pathToFileURL(root).href,workspaceFolders:[{uri:pathToFileURL(root).href,name:'workspace'}],capabilities:{workspace:{configuration:true,workspaceFolders:true},textDocument:{publishDiagnostics:{}}},initializationOptions:launch.initializationOptions},120000);server.notify('initialized',{}); backend.notify('lithe/host/languageServer/didChangeState',{context,serverID:'java',state:'running',generation:1}); const invoke=(functionID,params)=>backend.request('lithe/function/invoke',{functionID,operationID:`native-${++op}`,params,context},90000); @@ -60,6 +66,7 @@ try{ }); capture('zh',await invoke('compiler.settings',{context:{language:'zh-CN',builds:[]}}));capture('en',await invoke('compiler.settings',{context:{language:'en',builds:[]}})); assert.deepEqual(snapshot(pkg),baseline,'Native settings and server startup must never mutate the installed package'); + assert.deepEqual(snapshot(inputs.home),serverBaseline,'Server startup must never write into the user\'s JDT LS installation'); await server.request('shutdown',null);server.notify('exit',null); }finally{ try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{report.write();rmSync(stage,{recursive:true,force:true});}} diff --git a/scripts/package/build-linux.mjs b/scripts/package/build-linux.mjs index 2523e68..51b9cce 100644 --- a/scripts/package/build-linux.mjs +++ b/scripts/package/build-linux.mjs @@ -1,12 +1,12 @@ #!/usr/bin/env node -// Linux packages use fixed, verified JDK/JDT inputs and a native backend from -// this source checkout. All writes are build outputs, never installed files. +// Linux packages carry the JDT LS extensions verified from their pins and a +// native backend from this source checkout; JDT LS and its JDK are the user's. +// All writes are build outputs, never installed files. import {execFileSync} from 'node:child_process'; import {chmodSync,cpSync,mkdirSync,readFileSync,rmSync,mkdtempSync,readdirSync,lstatSync,writeFileSync} from 'node:fs'; import {join,resolve} from 'node:path'; -import {architectures,root,prepareJDK,digest,verifyELF,verifyBinary} from './linux-runtime.mjs'; +import {architectures,root,digest,verifyELF,verifyBinary} from './linux-runtime.mjs'; import {collectNotices,verifyNotices} from './collect-notices.mjs'; -import {patch,verifyPatch} from './patch-jdt-decompiler.mjs'; const arch=process.argv[2];const target=architectures[arch]; if(!target)throw Error('Usage: node scripts/package/build-linux.mjs arm64|x64 [native-backend]'); const run=(exe,args,options={})=>execFileSync(exe,args,{cwd:root,timeout:600000,stdio:['ignore','pipe','inherit'],...options}); @@ -17,34 +17,32 @@ if(!backend){ backend=join(root,'target/release/lithe-java-backend'); } backend=resolve(backend);verifyELF(readFileSync(backend),arch); -const runtime=await prepareJDK(arch); const jdt=run(join(root,'scripts/prepare-jdtls.sh'),[],{encoding:'utf8',env:{...process.env,LITHE_ARCH:target.runtime}}).trim(); const id='io.github.lithe-idea.java-support'; const manifest=JSON.parse(readFileSync(join(root,id,'plugin.json'))); const staging=mkdtempSync(join(root,'.artifacts',`linux-${arch}-`)); const pkg=join(staging,id); +const extensions=['lombok','java-debug','java-test','manifest.json']; function verify(directory){ const actual=JSON.parse(readFileSync(join(directory,'plugin.json'))); if(JSON.stringify(actual)!==JSON.stringify(manifest))throw Error('Packaged manifest changed'); for(const name of ['LICENSE','NOTICE'])if(!readFileSync(join(directory,name)).equals(readFileSync(join(root,name))))throw Error(`Missing or modified ${name}`); - for(const path of [manifest.backend.launch.path,`runtime/${target.runtime}/bin/java`,`runtime/${target.runtime}/lib/server/libjvm.so`]){ - verifyBinary(join(directory,path),arch,{executable:!path.endsWith('/libjvm.so')}); - } - if(!readFileSync(join(directory,'language-server/configuration',target.runtime,'config.ini')).equals(readFileSync(join(jdt,target.configuration,'config.ini'))))throw Error('Wrong Equinox platform configuration'); - const walk=path=>{for(const name of readdirSync(path)){const file=join(path,name);const s=lstatSync(file);if(s.isSymbolicLink())throw Error(`Package link: ${file}`);if(s.isDirectory())walk(file);}};walk(directory); - verifyNotices(directory);verifyPatch(directory); + verifyBinary(join(directory,manifest.backend.launch.path),arch,{executable:true}); + if(readdirSync(join(directory,'jdtls-extensions')).sort().join()!==[...extensions].sort().join())throw Error('Unexpected JDT LS extension entries'); + const walk=path=>{for(const name of readdirSync(path)){const file=join(path,name);const s=lstatSync(file);if(s.isSymbolicLink())throw Error(`Package link: ${file}`); + // JDT LS and the JDK are the user's; finding either means a build copied it in. + if((s.isFile()&&/^org\.eclipse\.equinox\.launcher_.*\.jar$|^java$|^libjvm\.so$/.test(name))||(s.isDirectory()&&/^config_/.test(name)))throw Error(`Package must not contain JDT LS or a JDK: ${file}`); + if(s.isDirectory())walk(file);}};walk(directory); + verifyNotices(directory); } try{ mkdirSync(pkg); cpSync(join(root,id,'plugin.json'),join(pkg,'plugin.json')); for(const name of ['icons','templates','l10n'])cpSync(join(root,id,name),join(pkg,name),{recursive:true}); - mkdirSync(join(pkg,'runtime'));cpSync(runtime,join(pkg,'runtime',target.runtime),{recursive:true}); - const language=join(pkg,'language-server');mkdirSync(language); - for(const name of ['plugins','features','lombok','java-debug','java-test','manifest.json','LICENSE-EPL-2.0.txt'])cpSync(join(jdt,name),join(language,name),{recursive:true}); - mkdirSync(join(language,'configuration',target.runtime),{recursive:true}); - cpSync(join(jdt,target.configuration,'config.ini'),join(language,'configuration',target.runtime,'config.ini')); + const destination=join(pkg,'jdtls-extensions');mkdirSync(destination); + for(const name of extensions)cpSync(join(jdt,name),join(destination,name),{recursive:true}); mkdirSync(join(pkg,'bin'));cpSync(backend,join(pkg,manifest.backend.launch.path));chmodSync(join(pkg,manifest.backend.launch.path),0o755); - collectNotices(pkg);patch(pkg);verify(pkg); + collectNotices(pkg);verify(pkg); const dist=join(root,'dist');mkdirSync(dist,{recursive:true}); const asset=join(dist,`Lithe-Java-Support-${manifest.version}-linux-${arch}.zip`);rmSync(asset,{force:true}); run('zip',['-qrXy',asset,id],{cwd:staging,timeout:120000}); diff --git a/scripts/package/build-windows.mjs b/scripts/package/build-windows.mjs index 7ff13cf..f43e5af 100644 --- a/scripts/package/build-windows.mjs +++ b/scripts/package/build-windows.mjs @@ -1,52 +1,27 @@ #!/usr/bin/env node // Assemble on macOS, using the backend built from this checkout on Windows. -// All runtime inputs come from the committed manifests; installed packages are -// never written. Release CI supplies the backend artifact built from the same tag; +// The package carries the JDT LS extensions verified from their pins; JDT LS +// and the JDK it runs on are the user's. Installed packages are never +// written. Release CI supplies the backend artifact built from the same tag; // the resulting unsigned ZIP is also used for native development validation. import { createHash } from 'node:crypto'; -import { createReadStream, createWriteStream } from 'node:fs'; -import { cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { createReadStream } from 'node:fs'; +import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { execFileSync } from 'node:child_process'; -import { Readable } from 'node:stream'; -import { pipeline } from 'node:stream/promises'; import { collectNotices, verifyNotices } from './collect-notices.mjs'; -import {patch,verifyPatch} from './patch-jdt-decompiler.mjs'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); if (process.platform !== 'darwin') throw new Error('Assemble this development package on macOS.'); const backend = process.argv[2]; -if (!backend) throw new Error('Usage: node scripts/package/build-windows.mjs |--prepare-runtime'); +if (!backend) throw new Error('Usage: node scripts/package/build-windows.mjs '); const artifacts = join(root, '.artifacts'); -const jdk = JSON.parse(await readFile(join(root, 'third_party/jdk/manifest.json'), 'utf8')); -const input = jdk.platforms['windows-x86_64']; -const cache = join(artifacts, 'jdk-downloads'); -await mkdir(cache, { recursive: true }); -const archive = join(cache, `jdk-windows-x86_64-${input.sha256}.zip`); async function digest(path) { const hash = createHash('sha256'); for await (const chunk of createReadStream(path)) hash.update(chunk); return hash.digest('hex'); } -async function isVerified(path) { - try { return await digest(path) === input.sha256; } - catch (error) { if (error.code === 'ENOENT') return false; throw error; } -} -if (!await isVerified(archive)) { - const temporary = `${archive}.${process.pid}.download`; - try { - const response = await fetch(input.url, { signal: AbortSignal.timeout(180_000) }); - if (!response.ok) throw new Error(`JDK download failed: ${response.status}`); - await pipeline(Readable.fromWeb(response.body), createWriteStream(temporary, { flags: 'wx' })); - if (!await isVerified(temporary)) throw new Error('Windows JDK SHA-256 mismatch.'); - await rename(temporary, archive); - } finally { await rm(temporary, { force: true }); } -} -if (backend === '--prepare-runtime') { - process.stdout.write(`${archive}\n`); - process.exit(0); -} async function verifyPE(path) { const bytes = await readFile(path); const header = bytes.length >= 64 ? bytes.readUInt32LE(60) : bytes.length; @@ -55,8 +30,8 @@ async function verifyPE(path) { } } await verifyPE(resolve(backend)); -// This existing entry verifies JDT LS, Lombok, java-debug and java-test from -// their locked archives and licenses, including config_win. +// This existing entry verifies Lombok, java-debug and java-test from their +// locked archives and licenses, next to the tested JDT LS release. const jdt = execFileSync(join(root, 'scripts/prepare-jdtls.sh'), { encoding: 'utf8', env: { ...process.env, LITHE_ARCH: 'x86_64' }, stdio: ['ignore', 'pipe', 'inherit'], timeout: 600_000, @@ -66,23 +41,12 @@ const id = 'io.github.lithe-idea.java-support'; const packageRoot = join(staging, id); try { await mkdir(packageRoot, { recursive: true }); - const unpack = join(staging, 'jdk'); - await mkdir(unpack); - execFileSync('/usr/bin/unzip', ['-q', archive, '-d', unpack], { timeout: 120_000 }); - const runtime = join(unpack, input.jdkRoot); - await verifyPE(join(runtime, 'bin/java.exe')); - const release = await readFile(join(runtime, 'release'), 'utf8'); - if (!/^JAVA_VERSION="21\./m.test(release)) throw new Error('The pinned runtime must be Java 21.'); - await mkdir(join(packageRoot, 'runtime'), { recursive: true }); - await cp(runtime, join(packageRoot, 'runtime/x86_64'), { recursive: true }); for (const name of ['icons', 'templates', 'l10n']) await cp(join(root, id, name), join(packageRoot, name), { recursive: true }); - const languageServer = join(packageRoot, 'language-server'); - await mkdir(languageServer); - for (const name of ['plugins', 'features', 'lombok', 'java-debug', 'java-test', 'manifest.json', 'LICENSE-EPL-2.0.txt']) { - await cp(join(jdt, name), join(languageServer, name), { recursive: true }); + const extensions = join(packageRoot, 'jdtls-extensions'); + await mkdir(extensions); + for (const name of ['lombok', 'java-debug', 'java-test', 'manifest.json']) { + await cp(join(jdt, name), join(extensions, name), { recursive: true }); } - await mkdir(join(languageServer, 'configuration/x86_64'), { recursive: true }); - await cp(join(jdt, 'config_win/config.ini'), join(languageServer, 'configuration/x86_64/config.ini')); const manifest = JSON.parse(await readFile(join(root, id, 'plugin.json'), 'utf8')); manifest.backend.launch.path = 'bin/lithe-java-backend.exe'; await writeFile(join(packageRoot, 'plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`); @@ -90,8 +54,6 @@ try { await cp(resolve(backend), join(packageRoot, manifest.backend.launch.path)); collectNotices(packageRoot); verifyNotices(packageRoot); - patch(packageRoot); - verifyPatch(packageRoot); const target = join(artifacts, `Lithe-Java-Support-${manifest.version}-windows-x64.zip`); execFileSync('/usr/bin/ditto', ['-c', '-k', '--keepParent', packageRoot, target], { timeout: 120_000 }); await writeFile(`${target}.sha256`, `${await digest(target)} ${target.split('/').at(-1)}\n`); diff --git a/scripts/package/jdtls-test-inputs.mjs b/scripts/package/jdtls-test-inputs.mjs new file mode 100644 index 0000000..1f9b737 --- /dev/null +++ b/scripts/package/jdtls-test-inputs.mjs @@ -0,0 +1,30 @@ +// What an integration test passes for the user's own JDT LS and the JDK it +// runs on, which the package does not ship. LITHE_TEST_JDTLS_HOME names the +// JDT LS folder (default: the tested release scripts/prepare-jdtls.sh +// prepared in .artifacts/jdtls); LITHE_TEST_JDTLS_JAVA names a Java 21+ +// executable (default: JAVA_HOME's, then java on PATH). The launch answers the +// jdtls-runtime tool, which the host would resolve; tests resolve it here. +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {existsSync} from 'node:fs'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +export const SERVER_RUNTIME_TOOL='jdtls-runtime'; +export function serverInputs(){ + const home=resolve(process.env.LITHE_TEST_JDTLS_HOME??join(root,'.artifacts/jdtls')); + assert.ok(existsSync(join(home,'plugins')),`No JDT LS installation at ${home}; run scripts/prepare-jdtls.sh or set LITHE_TEST_JDTLS_HOME`); + const exe=process.platform==='win32'?'java.exe':'java'; + const java=process.env.LITHE_TEST_JDTLS_JAVA??(process.env.JAVA_HOME?join(process.env.JAVA_HOME,'bin',exe):'java'); + // `java -version` prints to stderr; the pattern is the tool definition's. + const probe=spawnSync(java,['-version'],{encoding:'utf8',timeout:15000,windowsHide:true}); + assert.equal(probe.status,0,`${java} -version failed: ${probe.error?.message??probe.stderr}`); + const version=/version "(?:1\.)?(\d+(?:\.\d+)*)/.exec(probe.stderr)?.[1]; + assert.ok(version && Number(version.split('.')[0])>=21,`JDT LS needs Java 21 or later, ${java} is ${version}`); + return {home,java,tools:{[SERVER_RUNTIME_TOOL]:{executable:java,version}}}; +} +// The program a launch answer runs: the runtime tool resolves to the test JDK. +export function answeredExecutable(launch,inputs){ + assert.deepEqual(launch.executable,{kind:'tool',tool:SERVER_RUNTIME_TOOL}); + return inputs.java; +} diff --git a/scripts/package/linux-runtime.mjs b/scripts/package/linux-runtime.mjs index 6f793cc..ddd126c 100644 --- a/scripts/package/linux-runtime.mjs +++ b/scripts/package/linux-runtime.mjs @@ -1,14 +1,11 @@ -// Build-time Linux runtime preparation. Downloaded inputs are immutable and -// keyed by SHA-256; extracted runtimes belong only to this checkout. +// Build-time Linux platform checks. The package ships no JDK: the backend runs +// the user's JDT LS on the user's JDK, so only the backend binary is native. import {createHash} from 'node:crypto'; -import {createReadStream,createWriteStream,readFileSync,mkdirSync,existsSync,rmSync,mkdtempSync,renameSync,statSync} from 'node:fs'; -import {join,dirname,resolve} from 'node:path'; +import {createReadStream,readFileSync,statSync} from 'node:fs'; +import {dirname,resolve} from 'node:path'; import {fileURLToPath} from 'node:url'; -import {execFileSync} from 'node:child_process'; -import {Readable} from 'node:stream'; -import {pipeline} from 'node:stream/promises'; export const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); -export const architectures={arm64:{runtime:'arm64',jdk:'linux-aarch64',configuration:'config_linux_arm',machine:183},x64:{runtime:'x86_64',jdk:'linux-x86_64',configuration:'config_linux',machine:62}}; +export const architectures={arm64:{runtime:'arm64',configuration:'config_linux_arm',machine:183},x64:{runtime:'x86_64',configuration:'config_linux',machine:62}}; export function verifyELF(bytes,arch){ const target=architectures[arch]; if(!target)throw Error(`Unsupported Linux architecture: ${arch}`); @@ -24,40 +21,3 @@ export function verifyBinary(path,arch,{executable=false}={}){ export async function digest(path){ const hash=createHash('sha256');for await(const bytes of createReadStream(path))hash.update(bytes);return hash.digest('hex'); } -export function copyRuntime(source,destination){ - // Both BSD and GNU cp resolve the JDK's legal/ links with -RL. Node's - // recursive copy can retain links, which become dangling after staging ends. - execFileSync('cp',['-RL',source,destination],{timeout:120000}); -} -export async function prepareJDK(arch){ - const target=architectures[arch];if(!target)throw Error(`Unsupported Linux architecture: ${arch}`); - const manifest=JSON.parse(readFileSync(join(root,'third_party/jdk/manifest.json'))); - const input=manifest.platforms[target.jdk];if(!input)throw Error(`Missing pinned JDK: ${target.jdk}`); - const cache=join(root,'.artifacts/jdk-downloads');mkdirSync(cache,{recursive:true}); - const archive=join(cache,`jdk-${target.jdk}-${input.sha256}.tar.gz`); - if(!existsSync(archive) || await digest(archive)!==input.sha256){ - const temporary=`${archive}.${process.pid}.download`; - try{ - const response=await fetch(input.url,{signal:AbortSignal.timeout(180000)}); - if(!response.ok)throw Error(`JDK download failed: HTTP ${response.status}`); - await pipeline(Readable.fromWeb(response.body),createWriteStream(temporary,{flags:'wx'})); - if(await digest(temporary)!==input.sha256)throw Error('Linux JDK SHA-256 mismatch'); - renameSync(temporary,archive); - }finally{rmSync(temporary,{force:true});} - } - const output=join(root,'.artifacts',`jdk-${target.jdk}-${input.sha256}`); - // Re-extract the checksum-verified input: no mutable runtime tree is trusted. - const staging=mkdtempSync(join(cache,'extract-')); - try{ - execFileSync('tar',['-xzf',archive,'-C',staging],{timeout:120000}); - const runtime=join(staging,input.jdkRoot); - for(const path of ['bin/java','lib/server/libjvm.so'])verifyELF(readFileSync(join(runtime,path)),arch); - if(!/^JAVA_VERSION="21\./m.test(readFileSync(join(runtime,'release'),'utf8')))throw Error('The runtime must be Java 21'); - rmSync(output,{recursive:true,force:true}); - // The plugin contract forbids links. Dereference upstream JDK links only - // during packaging; runtime code never modifies these installed resources. - copyRuntime(runtime,output); - return output; - }finally{rmSync(staging,{recursive:true,force:true});} -} -if(process.argv[1] && resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(await prepareJDK(process.argv[2])); diff --git a/scripts/package/linux.test.mjs b/scripts/package/linux.test.mjs index b469135..6aebf14 100644 --- a/scripts/package/linux.test.mjs +++ b/scripts/package/linux.test.mjs @@ -1,7 +1,7 @@ // Offline checks of the platform boundary; real archives run in Linux CI. import test from 'node:test'; import assert from 'node:assert/strict'; -import {verifyELF,verifyBinary,copyRuntime} from './linux-runtime.mjs'; +import {verifyELF,verifyBinary} from './linux-runtime.mjs'; for (const [arch,machine] of [['arm64',183],['x64',62]]) { test(`accepts only Linux ${arch} ELF64 little-endian executables`,()=>{ const bytes=Buffer.alloc(64);bytes.set([127,69,76,70,2,1]);bytes.writeUInt16LE(2,16);bytes.writeUInt16LE(machine,18); @@ -12,7 +12,7 @@ for (const [arch,machine] of [['arm64',183],['x64',62]]) { }); } -import {mkdtempSync,writeFileSync,chmodSync,rmSync,mkdirSync,symlinkSync,lstatSync,readFileSync,statSync} from 'node:fs'; +import {mkdtempSync,writeFileSync,chmodSync,rmSync} from 'node:fs'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; test('allows read-only ELF shared libraries but requires execute permission on launchers',t=>{ @@ -21,13 +21,3 @@ test('allows read-only ELF shared libraries but requires execute permission on l verifyBinary(file,'arm64');assert.throws(()=>verifyBinary(file,'arm64',{executable:true}),/Executable permission/); chmodSync(file,0o755);verifyBinary(file,'arm64',{executable:true}); }); - -test('runtime copy contains regular license files after extraction staging is removed',t=>{ - const stage=mkdtempSync(join(tmpdir(),'linux-jdk-copy-'));t.after(()=>rmSync(stage,{recursive:true,force:true})); - const source=join(stage,'source');mkdirSync(source);writeFileSync(join(source,'LICENSE'),'pinned license'); - symlinkSync('LICENSE',join(source,'LICENSE-link'));writeFileSync(join(source,'java'),'ELF fixture');chmodSync(join(source,'java'),0o755); - const output=join(stage,'output');copyRuntime(source,output);rmSync(source,{recursive:true,force:true}); - assert.equal(lstatSync(join(output,'LICENSE-link')).isSymbolicLink(),false); - assert.equal(readFileSync(join(output,'LICENSE-link'),'utf8'),'pinned license'); - assert.ok(statSync(join(output,'java')).mode & 0o111); -}); diff --git a/scripts/package/patch-jdt-decompiler.mjs b/scripts/package/patch-jdt-decompiler.mjs deleted file mode 100644 index 377d41b..0000000 --- a/scripts/package/patch-jdt-decompiler.mjs +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env node -// Build-time only: the verified upstream staging tree is read-only input. -// Compile the narrowly patched EPL-2.0 integration against its exact original -// JDT distribution; package the changed source and hashes beside its notices. -import {execFileSync} from 'node:child_process'; -import {createHash} from 'node:crypto'; -import {readFileSync,writeFileSync,readdirSync,mkdtempSync,mkdirSync,rmSync,cpSync} from 'node:fs'; -import {resolve,join,dirname} from 'node:path'; -import {tmpdir} from 'node:os'; -import {fileURLToPath} from 'node:url'; - -const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); -const source=join(root,'third_party/jdtls/patches/FernFlowerDecompiler.java'); -const spec=JSON.parse(readFileSync(join(root,'third_party/jdtls/patches/manifest.json'),'utf8')); -const hash=bytes=>createHash('sha256').update(bytes).digest('hex'); -const run=(exe,args,options={})=>execFileSync(exe,args,{timeout:120000,maxBuffer:8*1024*1024,...options}); -const classPrefix='org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler'; -const signature=name=>/^META-INF\/[^/]+\.(SF|RSA|DSA|EC)$/i.test(name); -function coreJar(packageRoot){ - const plugins=join(packageRoot,'language-server/plugins'); - const jars=readdirSync(plugins).filter(n=>/^org\.eclipse\.jdt\.ls\.core_1\.61\.0\..*\.jar$/.test(n)); - if(jars.length!==1)throw Error('The pinned JDT 1.61 core bundle is required'); - return join(plugins,jars[0]); -} -function entries(jar){return run('/usr/bin/unzip',['-Z1',jar],{encoding:'utf8'}).trim().split('\n');} - -export function verifyPatch(packageRoot,io={}){ - const directory=join(packageRoot,'licenses/jdt-decompiler'); - const meta=JSON.parse(readFileSync(join(directory,'patch.json'),'utf8')); - if(Object.keys(spec).some(key=>JSON.stringify(meta[key])!==JSON.stringify(spec[key])) || hash(readFileSync(source))!==spec.sourceSHA256 || hash(readFileSync(join(directory,'FernFlowerDecompiler.java')))!==spec.sourceSHA256)throw Error('Decompiler patch source identity mismatch'); - const jdk=JSON.parse(readFileSync(join(root,'third_party/jdk/manifest.json'),'utf8')); - if(meta.compiler?.version!==jdk.version || jdk.platforms[meta.compiler?.platform]?.sha256!==meta.compiler?.archiveSHA256)throw Error('Decompiler compiler identity mismatch'); - const jar=coreJar(packageRoot); - if(hash(readFileSync(jar))!==meta.patchedCoreJarSHA256)throw Error('Decompiler patch bundle changed'); - if((io.entries??entries)(jar).some(signature))throw Error('Modified JDT bundle retains upstream signature entries'); - if(meta.upstreamSignaturesRemoved!==true)throw Error('Missing upstream signature removal declaration'); - if(!meta.classes || JSON.stringify(meta.classes.map(item=>item.path).sort())!==JSON.stringify(spec.classEntries))throw Error('Missing patched decompiler classes'); - for(const item of meta.classes){ - if(!item.path.startsWith(classPrefix) || !item.path.endsWith('.class') || item.path.includes('..'))throw Error('Invalid patch class entry'); - if(hash((io.readEntry??((jar,path)=>run('/usr/bin/unzip',['-p',jar,path])))(jar,item.path))!==item.sha256)throw Error('Patched decompiler class changed'); - } -} -export function patch(packageRoot){ - packageRoot=resolve(packageRoot); - const jar=coreJar(packageRoot); - if(hash(readFileSync(source))!==spec.sourceSHA256 || hash(readFileSync(jar))!==spec.originalCoreJarSHA256)throw Error('Decompiler patch inputs do not match the lock'); - // Always use the pinned host-architecture JDK; the output is Java bytecode - // shared by macOS and Windows, even when packaging another architecture. - const jdk=process.platform==='linux' - ? run(process.execPath,[join(root,'scripts/package/linux-runtime.mjs'),process.arch==='arm64'?'arm64':'x64'],{encoding:'utf8',timeout:300000}).trim() - : run(join(root,'scripts/prepare-jdk.sh'),[],{encoding:'utf8',env:{...process.env,LITHE_JDK_TARGET_ARCH:process.arch==='arm64'?'arm64':'x86_64'}}).trim(); - const stage=mkdtempSync(join(tmpdir(),'lithe-jdt-decompiler-')); - try{ - const classes=join(stage,'classes');mkdirSync(classes); - run(join(jdk,'bin/javac'),['--release','21','-g:none','-classpath',join(dirname(jar),'*'),'-d',classes,source]); - const original=entries(jar); - const folder=join(classes,'org/eclipse/jdt/ls/core/internal/decompiler'); - const generated=readdirSync(folder).filter(n=>n.endsWith('.class')).sort().map(n=>classPrefix.substring(0,classPrefix.lastIndexOf('/')+1)+n); - if(JSON.stringify(generated)!==JSON.stringify(spec.classEntries) || generated.some(n=>!original.includes(n)))throw Error('Unexpected decompiler class layout'); - const unpack=join(stage,'bundle');mkdirSync(unpack);run('/usr/bin/unzip',['-q',jar,'-d',unpack]); - for(const name of original.filter(signature))rmSync(join(unpack,name)); - const manifestFile=join(unpack,'META-INF/MANIFEST.MF'); - const sections=readFileSync(manifestFile,'utf8').split(/\r?\n\r?\n/).filter(s=>s.trim()); - for(const section of sections.slice(1)){ - const fields=section.split(/\r?\n/).filter(l=>l&&!l.startsWith(' ')); - if(fields.some(l=>!l.startsWith('Name:')&&!/^SHA-\d+-Digest:/.test(l)))throw Error('Unexpected signed manifest section'); - } - const mainManifest=join(stage,'MANIFEST.MF');writeFileSync(mainManifest,sections[0]+'\r\n\r\n');rmSync(manifestFile); - cpSync(classes,unpack,{recursive:true}); - const target=join(stage,'patched.jar');run(join(jdk,'bin/jar'),['--create','--file',target,'--manifest',mainManifest,'-C',unpack,'.']); - const directory=join(packageRoot,'licenses/jdt-decompiler');mkdirSync(directory,{recursive:true});cpSync(source,join(directory,'FernFlowerDecompiler.java')); - const jdkSpec=JSON.parse(readFileSync(join(root,'third_party/jdk/manifest.json'),'utf8')); - const compilerPlatform=`${process.platform==='linux'?'linux':'macos'}-${process.arch==='arm64'?'aarch64':'x86_64'}`; - const metadata={...spec,compiler:{version:jdkSpec.version,platform:compilerPlatform,archiveSHA256:jdkSpec.platforms[compilerPlatform].sha256},patchedCoreJarSHA256:hash(readFileSync(target)),upstreamSignaturesRemoved:true,classes:generated.map(path=>({path,sha256:hash(readFileSync(join(classes,path)))}))}; - // The package staging directory is writable build output. Never patch an - // installed bundle or the downloaded/cache copy of the upstream distribution. - cpSync(target,jar);writeFileSync(join(directory,'patch.json'),JSON.stringify(metadata,null,2)+'\n'); - verifyPatch(packageRoot); - } finally{rmSync(stage,{recursive:true,force:true});} -} -if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ - if(process.argv[2]==='--verify')verifyPatch(resolve(process.argv[3]));else patch(resolve(process.argv[2])); -} diff --git a/scripts/package/patch-jdt-decompiler.test.mjs b/scripts/package/patch-jdt-decompiler.test.mjs deleted file mode 100644 index b4dcbbe..0000000 --- a/scripts/package/patch-jdt-decompiler.test.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,cpSync,rmSync} from 'node:fs'; -import {tmpdir} from 'node:os'; -import {join,resolve} from 'node:path'; -import {fileURLToPath} from 'node:url'; -import {createHash} from 'node:crypto'; -import {verifyPatch} from './patch-jdt-decompiler.mjs'; -const root=fileURLToPath(new URL('../../',import.meta.url)); -const hash=value=>createHash('sha256').update(value).digest('hex'); -function fixture(t){ - const pkg=mkdtempSync(join(tmpdir(),'jdt-patch-test-'));t.after(()=>rmSync(pkg,{recursive:true,force:true})); - const notices=join(pkg,'licenses/jdt-decompiler');mkdirSync(notices,{recursive:true});mkdirSync(join(pkg,'language-server/plugins'),{recursive:true}); - const spec=JSON.parse(readFileSync(join(root,'third_party/jdtls/patches/manifest.json'),'utf8')); - const jdk=JSON.parse(readFileSync(join(root,'third_party/jdk/manifest.json'),'utf8')); - const jar=join(pkg,'language-server/plugins/org.eclipse.jdt.ls.core_1.61.0.test.jar');writeFileSync(jar,'locked generated jar'); - cpSync(join(root,'third_party/jdtls/patches/FernFlowerDecompiler.java'),join(notices,'FernFlowerDecompiler.java')); - const meta={...spec,compiler:{version:jdk.version,platform:'macos-aarch64',archiveSHA256:jdk.platforms['macos-aarch64'].sha256},patchedCoreJarSHA256:hash(readFileSync(jar)),upstreamSignaturesRemoved:true,classes:spec.classEntries.map(path=>({path,sha256:hash(path)}))}; - const manifest=join(notices,'patch.json');const save=()=>writeFileSync(manifest,JSON.stringify(meta));save(); - return {pkg,jar,meta,manifest,save,notices,io:{entries:()=>spec.classEntries,readEntry:(_,path)=>Buffer.from(path)}}; -} -test('verifies the complete pinned patch and compiler identities without running tools',t=>{const f=fixture(t);verifyPatch(f.pkg,f.io);}); -test('rejects changes to the generated jar or packaged source',t=>{ - const f=fixture(t);writeFileSync(f.jar,'modified');assert.throws(()=>verifyPatch(f.pkg,f.io),/bundle changed/); - const g=fixture(t);writeFileSync(join(g.notices,'FernFlowerDecompiler.java'),'modified');assert.throws(()=>verifyPatch(g.pkg,g.io),/source identity/); -}); -test('rejects missing classes, altered class bytes and stale signing entries',t=>{ - const f=fixture(t);f.meta.classes.pop();f.save();assert.throws(()=>verifyPatch(f.pkg,f.io),/Missing patched/); - const h=fixture(t);h.meta.upstreamSignaturesRemoved=false;h.save();assert.throws(()=>verifyPatch(h.pkg,h.io),/signature removal/); - const g=fixture(t);assert.throws(()=>verifyPatch(g.pkg,{...g.io,readEntry:()=>Buffer.from('modified')}),/class changed/); - assert.throws(()=>verifyPatch(g.pkg,{...g.io,entries:()=>['META-INF/ECLIPSE_.SF']}),/signature entries/); -}); -test('rejects an unpinned upstream revision or compiler',t=>{ - const f=fixture(t);f.meta.upstreamRevision='other';f.save();assert.throws(()=>verifyPatch(f.pkg,f.io),/source identity/); - const g=fixture(t);g.meta.compiler.archiveSHA256='0'.repeat(64);g.save();assert.throws(()=>verifyPatch(g.pkg,g.io),/compiler identity/); -}); diff --git a/scripts/package/smoke-linux.mjs b/scripts/package/smoke-linux.mjs index 866e2f2..c5075bd 100644 --- a/scripts/package/smoke-linux.mjs +++ b/scripts/package/smoke-linux.mjs @@ -7,34 +7,36 @@ import {join,resolve} from 'node:path'; import {pathToFileURL} from 'node:url'; import {createHash} from 'node:crypto'; import {Client} from './lsp-client.mjs'; +import {serverInputs,answeredExecutable} from './jdtls-test-inputs.mjs'; const archive=resolve(process.argv[2]); assert.equal(process.platform,'linux'); +const inputs=serverInputs(); const stage=mkdtempSync(join(tmpdir(),'lithe-java-linux-'));let backend,server; +const serverBefore=()=>inventory(inputs.home); const inventory=root=>{ const entries=[];const walk=(path,relative)=>{const s=lstatSync(path);assert.ok(!s.isSymbolicLink());entries.push([relative,s.mode,s.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(s.isDirectory())for(const name of readdirSync(path).sort())walk(join(path,name),`${relative}/${name}`);};walk(root,'');return entries; }; try{ execFileSync('unzip',['-q',archive,'-d',stage],{timeout:120000}); - const pkg=join(stage,'io.github.lithe-idea.java-support');const before=inventory(pkg); + const pkg=join(stage,'io.github.lithe-idea.java-support');const before=inventory(pkg);const serverBaseline=serverBefore(); const workspace=join(stage,'workspace');mkdirSync(workspace);writeFileSync(join(workspace,'Hello.java'),'class Hello { String value; }\n'); - const params={serverID:'java',platform:{os:'linux',arch:process.arch==='arm64'?'arm64':'x86_64'},settings:{logLevel:'WARNING'}}; + const params={serverID:'java',platform:{os:'linux',arch:process.arch==='arm64'?'arm64':'x86_64'},settings:{logLevel:'WARNING',languageServerHome:inputs.home},tools:inputs.tools}; for(const [key,name] of Object.entries({stateDirectory:'state',workspaceStateDirectory:'workspace-state',logDirectory:'logs',temporaryDirectory:'tmp'})){params[key]=join(stage,name);mkdirSync(params[key]);} backend=new Client(join(pkg,'bin/lithe-java-backend')); const initialized=await backend.request('initialize',{rootUri:pathToFileURL(workspace).href,capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}}); assert.ok(initialized.capabilities.experimental.litheFunctions); backend.notify('initialized',{}); const launch=await backend.request('lithe/function/invoke',{functionID:'java.resolveLaunch',operationID:'linux-smoke',params}); - assert.equal(launch.executable.kind,'packaged'); - assert.ok(launch.writablePaths.every(path=>!path.startsWith(pkg+'/'))); - const runtime=join(pkg,launch.executable.path); - execFileSync(runtime,['-version'],{timeout:15000}); + assert.ok(launch.writablePaths.every(path=>!path.startsWith(pkg+'/')&&!path.startsWith(inputs.home+'/'))); + const runtime=answeredExecutable(launch,inputs); server=new Client(runtime,launch.arguments,{env:{...process.env,...launch.environment}}); const result=await server.request('initialize',{processId:null,rootUri:pathToFileURL(workspace).href,workspaceFolders:[{uri:pathToFileURL(workspace).href,name:'workspace'}],capabilities:{},initializationOptions:launch.initializationOptions},120000); assert.ok(result.capabilities.definitionProvider);server.notify('initialized',{}); await server.request('shutdown',null,30000);server.notify('exit',null);await server.close();server=undefined; await backend.close();backend=undefined; assert.deepEqual(inventory(pkg),before,'LSP startup must not change installed package files or permissions'); - console.log(`Verified Linux ${process.arch}: backend handshake, launch resolution, JDK, JDT LS initialize/shutdown and immutable package`); + assert.deepEqual(serverBefore(),serverBaseline,'LSP startup must not write into the user\'s JDT LS installation'); + console.log(`Verified Linux ${process.arch}: backend handshake, launch resolution of the user's JDT LS, initialize/shutdown, immutable package and installation`); }finally{ try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{rmSync(stage,{recursive:true,force:true});}} } diff --git a/scripts/prepare-jdk.sh b/scripts/prepare-jdk.sh deleted file mode 100755 index 86c0807..0000000 --- a/scripts/prepare-jdk.sh +++ /dev/null @@ -1,135 +0,0 @@ -#!/bin/zsh - -# Stages the bundled JDTLS runtime JDK into an architecture-specific artifact directory. -# This JDK only runs the Java language server. Project SDKs stay user-owned. - -set -euo pipefail - -ROOT_DIR="${0:A:h:h}" -MANIFEST="$ROOT_DIR/third_party/jdk/manifest.json" -CACHE_DIR="$ROOT_DIR/.artifacts/jdk-downloads" -TARGET_ARCH="${LITHE_JDK_TARGET_ARCH:-$(uname -m)}" -OUTPUT_DIR="${LITHE_JDK_ROOT:-$ROOT_DIR/.artifacts/jdk-$TARGET_ARCH}" - -manifest_value() { - /usr/bin/plutil -extract "$1" raw -o - "$MANIFEST" -} - -case "$TARGET_ARCH" in - arm64) platform="macos-aarch64" ;; - x86_64) platform="macos-x86_64" ;; - *) print -u2 -- "Unsupported macOS JDK target architecture: $TARGET_ARCH"; exit 1 ;; -esac - -jdk_version="$(manifest_value version)" -archive_url="$(manifest_value "platforms.$platform.url")" -archive_sha256="$(manifest_value "platforms.$platform.sha256")" -safe_jdk_version="${jdk_version//[^A-Za-z0-9._-]/_}" -archive_path="$CACHE_DIR/jdk-$safe_jdk_version-$platform-$archive_sha256.tar.gz" -identity="$jdk_version|$platform|$archive_sha256" -identity_path="$OUTPUT_DIR/.lithe-jdk" - -file_sha256() { - shasum -a 256 "$1" | awk '{print tolower($1)}' -} - -download_verified_file() { - local url="$1" - local expected_sha256="$2" - local destination="$3" - local description="$4" - local actual_sha256 - local temporary_path="$destination.download.$$" - - if [[ -f "$destination" ]]; then - actual_sha256="$(file_sha256 "$destination")" - if [[ "$actual_sha256" == "$expected_sha256" ]]; then - return 0 - fi - print -u2 -- "$description cache checksum mismatch; removing it before retrying the download" - rm -f -- "$destination" - fi - - rm -f -- "$temporary_path" - print -u2 -- "Downloading $description: $url" - if ! curl \ - --fail \ - --location \ - --retry 3 \ - --retry-all-errors \ - --connect-timeout 15 \ - --max-time 180 \ - --output "$temporary_path" \ - "$url"; then - rm -f -- "$temporary_path" - return 1 - fi - actual_sha256="$(file_sha256 "$temporary_path")" - if [[ "$actual_sha256" != "$expected_sha256" ]]; then - print -u2 -- "$description checksum mismatch: expected $expected_sha256, got $actual_sha256" - rm -f -- "$temporary_path" - return 1 - fi - mv -f -- "$temporary_path" "$destination" -} - -validate_output() { - [[ -x "$OUTPUT_DIR/bin/java" ]] || { print -u2 -- "Bundled JDK java executable is missing: $OUTPUT_DIR/bin/java"; exit 1; } - [[ -d "$OUTPUT_DIR/lib" ]] || { print -u2 -- "Bundled JDK lib directory is missing: $OUTPUT_DIR"; exit 1; } - /usr/bin/lipo "$OUTPUT_DIR/bin/java" -verify_arch "$TARGET_ARCH" >/dev/null 2>&1 || { - print -u2 -- "Bundled JDK java executable does not contain $TARGET_ARCH: $OUTPUT_DIR/bin/java" - exit 1 - } - [[ -f "$OUTPUT_DIR/release" ]] || { print -u2 -- "Bundled JDK release metadata is missing: $OUTPUT_DIR/release"; exit 1; } - grep -Eq '^JAVA_VERSION="21\.' "$OUTPUT_DIR/release" || { - print -u2 -- "Bundled JDK release metadata does not report Java 21: $OUTPUT_DIR/release" - exit 1 - } -} - -output_is_valid() { - [[ -x "$OUTPUT_DIR/bin/java" ]] && - [[ -d "$OUTPUT_DIR/lib" ]] && - [[ -f "$OUTPUT_DIR/release" ]] && - /usr/bin/lipo "$OUTPUT_DIR/bin/java" -verify_arch "$TARGET_ARCH" >/dev/null 2>&1 && - grep -Eq '^JAVA_VERSION="21\.' "$OUTPUT_DIR/release" -} - -if [[ -n "${LITHE_JDK_ROOT:-}" ]]; then - validate_output - print -r -- "$OUTPUT_DIR" - exit 0 -fi - -if [[ -f "$identity_path" && "$(<"$identity_path")" == "$identity" ]]; then - if output_is_valid; then - print -r -- "$OUTPUT_DIR" - exit 0 - fi - print -u2 -- "Prepared bundled JDK is invalid and will be rebuilt: $OUTPUT_DIR" -fi - -mkdir -p "$CACHE_DIR" -download_verified_file "$archive_url" "$archive_sha256" "$archive_path" "Temurin JDK archive" - -rm -rf "$OUTPUT_DIR" -staging="$CACHE_DIR/staging.$$" -rm -rf "$staging" -mkdir -p "$staging" -tar -xzf "$archive_path" -C "$staging" - -# macOS Temurin archives nest the runtime under /Contents/Home. -# Flatten it so both platforms expose the same bin/java layout. -home_directory="$(find "$staging" -maxdepth 3 -type d -name Home -path '*/Contents/Home' -print | head -n 1)" -if [[ -z "$home_directory" ]]; then - print -u2 -- "Could not locate Contents/Home in the Temurin archive" - rm -rf "$staging" - exit 1 -fi -mkdir -p "$(dirname "$OUTPUT_DIR")" -mv "$home_directory" "$OUTPUT_DIR" -print -r -- "$identity" > "$identity_path" -rm -rf "$staging" - -validate_output -print -r -- "$OUTPUT_DIR" diff --git a/scripts/prepare-jdtls.sh b/scripts/prepare-jdtls.sh index f888fef..072bc68 100755 --- a/scripts/prepare-jdtls.sh +++ b/scripts/prepare-jdtls.sh @@ -2,6 +2,12 @@ set -euo pipefail +# Prepares, from the pins in third_party/jdtls/manifest.json, the JDT LS +# extensions the package ships (Lombok, Java Debug, Java Test) next to the +# tested JDT LS release. The package carries only the extensions; the JDT LS +# release is the one the tests run against and the one whose own bundles the +# Java Test set is checked against, standing in for the user's installation. + ROOT_DIR="${0:A:h:h}" MANIFEST="$ROOT_DIR/third_party/jdtls/manifest.json" OUTPUT_DIR="${LITHE_JDTLS_ROOT:-$ROOT_DIR/.artifacts/jdtls}" @@ -36,8 +42,6 @@ java_debug_extension_version="$(manifest_value javaDebugExtensionVersion)" java_debug_server_version="$(manifest_value javaDebugServerVersion)" java_test_extension_version="$(manifest_value javaTestExtensionVersion)" java_test_plugin_version="$(manifest_value javaTestPluginVersion)" -minimum_java_version="$(manifest_value minimumJavaVersion)" -bundled_jdk_version="$(node "$ROOT_DIR/scripts/package/json-value.mjs" "$ROOT_DIR/third_party/jdk/manifest.json" version)" archive_path="${LITHE_JDTLS_ARCHIVE:-$CACHE_DIR/jdtls-$jdtls_version-$archive_sha256.tar.gz}" license_path="$CACHE_DIR/EPL-2.0-$license_sha256.txt" lombok_path="$CACHE_DIR/lombok-$lombok_version-$lombok_sha256.jar" @@ -53,13 +57,6 @@ java_test_runner_name="com.microsoft.java.test.runner-jar-with-dependencies.jar" # checks the exact upstream list instead of a hard-coded count. java_test_bundle_list="java-test/extensions.txt" -# JDT LS refuses to start on a Java runtime older than it requires, and the -# bundled JDK is the runtime Lithe launches it with. -(( ${bundled_jdk_version%%.*} >= minimum_java_version )) || { - print -u2 -- "Bundled JDK $bundled_jdk_version is older than the Java $minimum_java_version that JDTLS $jdtls_version requires" - exit 1 -} - file_sha256() { shasum -a 256 "$1" | awk '{print tolower($1)}' } diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh index 2477b0e..a6689a8 100755 --- a/scripts/verify-package.sh +++ b/scripts/verify-package.sh @@ -6,13 +6,12 @@ set -euo pipefail # - plugin.json is the repository manifest, unchanged, and declares a # plugin without a publisher signature (vendor.signatureRequirement "none"); # - the package holds only the declared top-level entries and no symbolic -# links, and nothing outside runtime/ and bin/ is executable; -# - every language server file the backend resolves (backend/src/launch.rs) -# exists in the layout it expects; +# links, and nothing outside bin/ is executable; +# - every JDT LS extension file the backend resolves (backend/src/launch.rs) +# exists in the layout it expects, and JDT LS itself and a JDK are not +# packaged: the backend uses the user's own (backend/src/jdtls.rs); # - the plugin backend (backend.launch.path in plugin.json) is the only file -# in bin/, is executable, and contains exactly the requested architectures; -# - the packaged JDK is the requested architecture and keeps its upstream -# code signature (macOS only launches the JDK if it does). +# in bin/, is executable, and contains exactly the requested architectures. ROOT_DIR="${0:A:h:h}" PLUGIN_ID="io.github.lithe-idea.java-support" @@ -28,8 +27,8 @@ while [[ $# -gt 0 ]]; do done [[ -d "$PACKAGE" ]] || { print -u2 -- "--package must name an assembled package directory"; exit 2; } case "$ARCH" in - arm64|x86_64) runtime_architectures=("$ARCH") ;; - universal) runtime_architectures=(arm64 x86_64) ;; + arm64|x86_64) backend_architectures=("$ARCH") ;; + universal) backend_architectures=(arm64 x86_64) ;; *) print -u2 -- "Unsupported architecture: $ARCH"; exit 2 ;; esac @@ -53,16 +52,16 @@ for notice in LICENSE NOTICE; do done node "$ROOT_DIR/scripts/package/collect-notices.mjs" --verify "$PACKAGE" -allowed=(plugin.json bin icons templates l10n language-server runtime LICENSE NOTICE licenses) +allowed=(plugin.json bin icons templates l10n jdtls-extensions LICENSE NOTICE licenses) for entry in "$PACKAGE"/*(DN); do (( ${allowed[(Ie)${entry:t}]} )) || fail "undeclared top-level entry ${entry:t}" done symlink=$(find "$PACKAGE" -type l -print -quit) [[ -z "$symlink" ]] || fail "symbolic link $symlink" -# runtime/ holds the JDK and bin/ holds the plugin backend; no other directory -# may carry an executable (the backend itself is pinned down below). -outside_runtime=$(find "$PACKAGE" \( -path "$PACKAGE/runtime" -o -path "$PACKAGE/bin" \) -prune -o -type f -perm -u+x -print -quit) -[[ -z "$outside_runtime" ]] || fail "executable file outside runtime/ and bin/: $outside_runtime" +# bin/ holds the plugin backend; no other directory may carry an executable +# (the backend itself is pinned down below). +outside_bin=$(find "$PACKAGE" -path "$PACKAGE/bin" -prune -o -type f -perm -u+x -print -quit) +[[ -z "$outside_bin" ]] || fail "executable file outside bin/: $outside_bin" backend_path=$(/usr/bin/plutil -extract backend.launch.path raw -o - "$manifest") [[ "$backend_path" == bin/* && "$backend_path" != *..* ]] || @@ -76,8 +75,8 @@ packaged_backend_files=("$PACKAGE"/bin/**/*(.DN)) backend_archs_text=$(/usr/bin/lipo -archs "$backend" 2>/dev/null) || fail "$backend_path is not a Mach-O binary" backend_archs=(${=backend_archs_text}) -[[ "${(j: :)${(o)backend_archs}}" == "${(j: :)${(o)runtime_architectures}}" ]] || - fail "$backend_path contains ${backend_archs[*]:-no architectures}, expected ${runtime_architectures[*]}" +[[ "${(j: :)${(o)backend_archs}}" == "${(j: :)${(o)backend_architectures}}" ]] || + fail "$backend_path contains ${backend_archs[*]:-no architectures}, expected ${backend_architectures[*]}" # The language server launch is resolved by the backend (plugin.json declares # launch.kind "backend" and the function only), so the files are checked @@ -85,39 +84,21 @@ backend_archs=(${=backend_archs_text}) # this script to that list. [[ "$(/usr/bin/plutil -extract languageServers.0.launch.kind raw -o - "$manifest")" == "backend" ]] || fail "plugin.json must declare a backend-resolved language server launch" -launchers=("$PACKAGE"/language-server/plugins/org.eclipse.equinox.launcher_*.jar(N)) -(( ${#launchers} == 1 )) || - fail "language-server/plugins must hold exactly one org.eclipse.equinox.launcher_*.jar, found ${#launchers}" for declared in \ - language-server/lombok/lombok.jar \ - language-server/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar; do + jdtls-extensions/lombok/lombok.jar \ + jdtls-extensions/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar; do [[ -f "$PACKAGE/$declared" ]] || fail "the backend expects $declared, which the package does not contain" done -for directory in language-server/java-debug language-server/java-test/extensions; do +for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions; do [[ -n "$(find "$PACKAGE/$directory" -maxdepth 1 -name '*.jar' -print -quit 2>/dev/null)" ]] || fail "extension bundle directory $directory holds no bundles" done -for license in LICENSE-EPL-2.0.txt lombok/LICENSE-MIT.txt java-debug/LICENSE-EPL-1.0.txt java-test/LICENSE-MIT.txt; do - [[ -f "$PACKAGE/language-server/$license" ]] || fail "missing third-party license language-server/$license" +for license in lombok/LICENSE-MIT.txt java-debug/LICENSE-EPL-1.0.txt java-test/LICENSE-MIT.txt; do + [[ -f "$PACKAGE/jdtls-extensions/$license" ]] || fail "missing third-party license jdtls-extensions/$license" done - -present_runtimes=("$PACKAGE"/runtime/*(/N:t)) -[[ "${(j: :)${(o)present_runtimes}}" == "${(j: :)${(o)runtime_architectures}}" ]] || - fail "runtime/ holds ${present_runtimes[*]:-nothing}, expected ${runtime_architectures[*]}" -for runtime_arch in "${runtime_architectures[@]}"; do - runtime="$PACKAGE/runtime/$runtime_arch" - configuration="$PACKAGE/language-server/configuration/$runtime_arch/config.ini" - [[ -f "$configuration" ]] || fail "missing $configuration" - [[ -x "$runtime/bin/java" ]] || fail "missing $runtime/bin/java" - /usr/bin/lipo "$runtime/bin/java" -verify_arch "$runtime_arch" >/dev/null 2>&1 || - fail "$runtime/bin/java does not contain $runtime_arch" - grep -Eq '^JAVA_VERSION="21\.' "$runtime/release" || fail "$runtime is not a Java 21 runtime" - /usr/bin/codesign --verify --strict "$runtime/bin/java" || - fail "$runtime/bin/java lost its upstream code signature" - /usr/bin/codesign --verify --strict "$runtime/lib/server/libjvm.dylib" || - fail "$runtime/lib/server/libjvm.dylib lost its upstream code signature" -done - -node "$ROOT_DIR/scripts/package/patch-jdt-decompiler.mjs" --verify "$PACKAGE" +# JDT LS and the JDK it runs on are the user's: an Equinox launcher or a Java +# executable in the package means a build copied them in. +bundled=$(find "$PACKAGE" \( \( -type f \( -name 'org.eclipse.equinox.launcher_*.jar' -o -name java -o -name java.exe -o -name 'libjvm.*' \) \) -o \( -type d -name 'config_*' \) \) -print -quit) +[[ -z "$bundled" ]] || fail "the package must not contain JDT LS or a JDK: ${bundled#$PACKAGE/}" print -u2 -- "Verified Java Support package $PACKAGE ($ARCH)" diff --git a/third_party/README.md b/third_party/README.md index 3ba3995..39a7be7 100644 --- a/third_party/README.md +++ b/third_party/README.md @@ -4,8 +4,10 @@ | 清单 | 内容 | 使用者 | | --- | --- | --- | -| `jdtls/manifest.json` | Eclipse JDT Language Server、Lombok、java-debug、vscode-java-test 的版本、下载地址和 SHA-256 | `scripts/prepare-jdtls.sh` | -| `jdk/manifest.json` | 每个平台一份 Temurin JDK 21 的下载地址、SHA-256 和解压后的根目录名 | `scripts/prepare-jdk.sh` | +| `jdtls/manifest.json` | 随包的 Lombok、java-debug、vscode-java-test 扩展,以及测试用 Eclipse JDT Language Server 的版本、下载地址和 SHA-256;`minimumJavaVersion` 是运行 JDT LS 的最低 Java 版本,与后端的 `MINIMUM_SERVER_JAVA_VERSION` 一致 | `scripts/prepare-jdtls.sh` | + +插件包不带 JDT LS 和 JDK:插件运行用户自己安装的 JDT LS 和 JDK 21+(`backend/src/jdtls.rs`)。清单里的 JDT LS +只用于构建和测试:组装时据它的 `plugins/` 剔除 JDT LS 已自带的 Java Test 扩展包,集成测试把它当作用户的安装来启动。 规则: @@ -15,8 +17,8 @@ HTTPS、每个校验和都是小写 SHA-256(`backend/tests/repository_pins.rs`)。 - 插件包里的第三方许可证由组装脚本从上游包复制,`scripts/verify-package.sh` 检查它们存在;仓库根目录的 `NOTICE` 列出全部组件和许可。 -- `jdk/manifest.json` 里的 Windows 条目留给 Windows 版插件包使用,目前的打包脚本只读取 macOS 条目。 -> English: `third_party/` pins every upstream input of the plugin package by version, HTTPS URL and SHA-256. +> English: `third_party/` pins every upstream input of the plugin package, and the JDT LS release the tests run as +> the user's installation, by version, HTTPS URL and SHA-256. > The prepare scripts download into the ignored `.artifacts/` directory and verify the checksum before use; no > upstream binaries are committed. `backend/tests/repository_pins.rs` checks the pins. diff --git a/third_party/jdk/manifest.json b/third_party/jdk/manifest.json deleted file mode 100644 index bf8cf5d..0000000 --- a/third_party/jdk/manifest.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "version": "21.0.12.1+1", - "licenseURL": "https://github.com/adoptium/temurin21-binaries/blob/main/LICENSE", - "platforms": { - "macos-aarch64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_aarch64_mac_hotspot_21.0.12.1_1.tar.gz", - "sha256": "3623232f33a9c3baadf304480b2535f9a3cba8a58d42ecbb438ba267315d9998", - "jdkRoot": "jdk-21.0.12.1+1" - }, - "macos-x86_64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_mac_hotspot_21.0.12.1_1.tar.gz", - "sha256": "44db0f08196daf19a47f90d13388b0c943b67663cb537f998fe29e836fa842ce", - "jdkRoot": "jdk-21.0.12.1+1" - }, - "windows-aarch64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12%2B8/OpenJDK21U-jdk_aarch64_windows_hotspot_21.0.12_8.zip", - "sha256": "e7ddf1cf45885cae2cfb8a018db60b0041ef69e96843b93a92b447d9a4cba676", - "jdkRoot": "jdk-21.0.12+8" - }, - "windows-x86_64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_windows_hotspot_21.0.12.1_1.zip", - "sha256": "f9d6e191ab098c0d416e7d588a24420a8621cd2f4720dab2459b8b7b2d2d8b4e", - "jdkRoot": "jdk-21.0.12.1+1" - }, - "linux-aarch64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_aarch64_linux_hotspot_21.0.12.1_1.tar.gz", - "sha256": "23e37e026f12f3e706f18938ff611db3032d075b09d0879a25d06718c773e223", - "jdkRoot": "jdk-21.0.12.1+1" - }, - "linux-x86_64": { - "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_linux_hotspot_21.0.12.1_1.tar.gz", - "sha256": "ce79869e1307ed8ee1e2baa86a412b1eb5b75d10a01006d788a6f968bcfaee94", - "jdkRoot": "jdk-21.0.12.1+1" - } - } -} diff --git a/third_party/jdtls/patches/FernFlowerDecompiler.java b/third_party/jdtls/patches/FernFlowerDecompiler.java deleted file mode 100644 index 1790f04..0000000 --- a/third_party/jdtls/patches/FernFlowerDecompiler.java +++ /dev/null @@ -1,377 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2023 Microsoft Corporation and others. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License 2.0 -* which accompanies this distribution, and is available at -* https://www.eclipse.org/legal/epl-2.0/ -* -* SPDX-License-Identifier: EPL-2.0 -* -* Contributors: -* Microsoft Corporation - initial API and implementation -*******************************************************************************/ - -package org.eclipse.jdt.ls.core.internal.decompiler; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.jar.Manifest; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jdt.core.IClassFile; -import org.eclipse.jdt.core.IOrdinaryClassFile; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.ls.core.internal.DecompilerResult; -import org.eclipse.jdt.ls.core.internal.JDTUtils; -import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; -import org.eclipse.jdt.ls.core.internal.StatusFactory; -import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler; -import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider; -import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; -import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger.Severity; -import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; -import org.jetbrains.java.decompiler.main.extern.IResultSaver; - -public class FernFlowerDecompiler extends DecompilerImpl { - public static final String DECOMPILER_HEADER = "// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\n"; - - public static boolean isDecompiledContents(String contents) { - return contents != null && contents.startsWith(DECOMPILER_HEADER); - } - - @Override - protected DecompilerResult decompileContent(URI uri, IProgressMonitor monitor) throws CoreException { - try { - return getContent(new BytecodeProvider(uri), monitor); - } catch (IOException e) { - throw new CoreException(StatusFactory.newErrorStatus("Failed to decompile class file: " + uri, e)); - } - } - - @Override - protected DecompilerResult decompileContent(IClassFile classFile, IProgressMonitor monitor) throws CoreException { - try { - return getContent(new BytecodeProvider(classFile), monitor); - } catch (IOException e) { - throw new CoreException(StatusFactory.newErrorStatus("Failed to decompile class file: " + classFile, e)); - } - } - - @Override - protected DecompilerType getDecompilerType() { - return DecompilerType.FERNFLOWER; - } - - private DecompilerResult getContent(BytecodeProvider provider, IProgressMonitor monitor) throws CoreException { - Map decompilerOptions = new HashMap<>(); - decompilerOptions.put(IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR, "0"); - decompilerOptions.put(IFernflowerPreferences.IGNORE_INVALID_BYTECODE, "1"); - decompilerOptions.put(IFernflowerPreferences.REMOVE_SYNTHETIC, "1"); - decompilerOptions.put(IFernflowerPreferences.REMOVE_BRIDGE, "1"); - decompilerOptions.put(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1"); - decompilerOptions.put(IFernflowerPreferences.DECOMPILE_INNER, "1"); - decompilerOptions.put(IFernflowerPreferences.DECOMPILE_ENUM, "1"); - decompilerOptions.put(IFernflowerPreferences.LOG_LEVEL, Severity.ERROR.name()); - decompilerOptions.put(IFernflowerPreferences.ASCII_STRING_CHARACTERS, "0"); - decompilerOptions.put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1"); - if (Boolean.getBoolean("jdt.ls.debug")) { - decompilerOptions.put(IFernflowerPreferences.DUMP_ORIGINAL_LINES, "1"); - } - ResultSaver resultSaver = new ResultSaver(); - BaseDecompiler fernflower = new BaseDecompiler(provider, resultSaver, decompilerOptions, new IFernflowerLogger() { - @Override - public void writeMessage(String message, Severity severity) { - if (severity.ordinal() >= Severity.ERROR.ordinal()) { - JavaLanguageServerPlugin.logError(message); - } - } - - @Override - public void writeMessage(String message, Severity severity, Throwable t) { - if (severity.ordinal() >= Severity.ERROR.ordinal()) { - JavaLanguageServerPlugin.logException(message, t); - } - } - }); - // Add all sources (outer + inner classes) to the decompiler - for (File file : provider.getAllClassFiles()) { - fernflower.addSource(file); - } - fernflower.decompileContext(); - final String decompiledCode = DECOMPILER_HEADER + resultSaver.content; - - final Map> originalLineMappings = new TreeMap<>(); - final Map> decompiledLineMappings = new TreeMap<>(); - if (resultSaver.originalLinesMapping != null) { - for (int i = 0; i + 1 < resultSaver.originalLinesMapping.length; i = i + 2) { - int srcLine = resultSaver.originalLinesMapping[i]; - int decompiledLine = resultSaver.originalLinesMapping[i + 1] + 1; // add one extra line for the header - Set decompiled = originalLineMappings.computeIfAbsent(srcLine, k -> new TreeSet<>()); - decompiled.add(decompiledLine); - Set src = decompiledLineMappings.computeIfAbsent(decompiledLine, k -> new TreeSet<>()); - src.add(srcLine); - } - } else { - JavaLanguageServerPlugin.logInfo("Line mappings not available for decompiled content - decompilation may have failed or line mapping was disabled"); - } - - List originals = new ArrayList<>(originalLineMappings.size() * 2); - for (Entry> entry: originalLineMappings.entrySet()) { - int original = entry.getKey(); - for (int value : entry.getValue()) { - originals.add(original); - originals.add(value); - } - } - - List decompiles = new ArrayList<>(decompiledLineMappings.size() * 2); - for (Entry> entry: decompiledLineMappings.entrySet()) { - int decompiled = entry.getKey(); - for (int value : entry.getValue()) { - decompiles.add(decompiled); - decompiles.add(value); - } - } - - return new DecompilerResult(decompiledCode, - originals.stream().mapToInt(Integer::intValue).toArray(), - decompiles.stream().mapToInt(Integer::intValue).toArray()); - } - - static class ResultSaver implements IResultSaver { - private String content; - private int[] originalLinesMapping; - - @Override - public void closeArchive(String arg0, String arg1) { - } - - @Override - public void copyEntry(String arg0, String arg1, String arg2, String arg3) { - } - - @Override - public void copyFile(String arg0, String arg1, String arg2) { - } - - @Override - public void createArchive(String arg0, String arg1, Manifest arg2) { - } - - @Override - public void saveClassEntry(String arg0, String arg1, String arg2, String arg3, String arg4) { - } - - @Override - public void saveClassFile(String filename, String qualifiedName, String entryName, String content, int[] originalLinesMapping) { - this.content = content; - this.originalLinesMapping = originalLinesMapping; - } - - @Override - public void saveDirEntry(String arg0, String arg1, String arg2) { - } - - @Override - public void saveFolder(String arg0) { - } - } - - static class BytecodeProvider implements IBytecodeProvider { - private Map bytecodeMap = new HashMap<>(); - private List classFiles = new ArrayList<>(); - - public BytecodeProvider(URI uri) throws CoreException, IOException { - collectClassFiles(uri); - } - - public BytecodeProvider(IClassFile classFile) throws CoreException, IOException { - collectClassFiles(classFile); - } - - public List getAllClassFiles() { - return classFiles; - } - - @Override - public byte[] getBytecode(String externalPath, String internalPath) throws IOException { - byte[] bytes = bytecodeMap.get(externalPath); - if (bytes == null) { - throw new IOException("Class file not found: " + externalPath + - " (available: " + bytecodeMap.keySet() + ")"); - } - return bytes; - } - - //----------------------------------------------------------- - // Collect all class files from a URI - File-based detection - //----------------------------------------------------------- - private void collectClassFiles(URI uri) throws CoreException, IOException { - IClassFile classFile = JDTUtils.resolveClassFile(uri); - if (classFile != null) { - collectClassFiles(classFile); - return; - } - - // File-based approach - java.nio.file.Path classPath = Paths.get(uri); - if (!Files.exists(classPath)) { - throw new IOException("Class file does not exist: " + classPath); - } - - File file = classPath.toFile(); - - // 1. Find the top-level class file - File topLevelFile = findTopLevelClassFile(file); - - // 2. Scan all matching classes (top-level + inner classes) - Set allClassFiles = new LinkedHashSet<>(); - scanClassFiles(topLevelFile, allClassFiles); - - // 3. Process all classes found - for (File classFileToProcess : allClassFiles) { - processClassFile(classFileToProcess); - } - } - - private File findTopLevelClassFile(File file) throws IOException { - String fileName = file.getName(); - if (!fileName.endsWith(".class")) { - return file; - } - - String baseName = fileName.substring(0, fileName.length() - 6); - int dollarIndex = baseName.indexOf('$'); - - if (dollarIndex > 0) { - // Check if this might be an inner class - String topLevelBaseName = baseName.substring(0, dollarIndex); - File parentDir = file.getParentFile(); - if (parentDir != null) { - File topLevelFile = new File(parentDir, topLevelBaseName + ".class"); - if (topLevelFile.exists()) { - // Found the parent class, so this is indeed an inner class - return topLevelFile; - } - // Parent class doesn't exist - treat this as a top-level class - // (e.g., a class with $ in its name, though uncommon) - } - } - - return file; - } - - private void scanClassFiles(File topLevelFile, Set result) { - // Add the top-level class - result.add(topLevelFile); - - // Find all inner classes - String fileName = topLevelFile.getName(); - if (fileName.endsWith(".class")) { - String baseName = fileName.substring(0, fileName.length() - 6); - String mask = baseName + "$"; - - File parentDir = topLevelFile.getParentFile(); - if (parentDir != null && parentDir.isDirectory()) { - File[] innerClasses = parentDir.listFiles((dir, name) -> - name.startsWith(mask) && name.endsWith(".class")); - if (innerClasses != null) { - Arrays.stream(innerClasses).forEach(result::add); - } - } - } - } - - private void processClassFile(File file) throws IOException { - String path = file.getPath(); - classFiles.add(file); - bytecodeMap.put(path, Files.readAllBytes(file.toPath())); - } - - //----------------------------------------------------------- - // Collect all class files from an IClassFile - //----------------------------------------------------------- - private void collectClassFiles(IClassFile classFile) throws CoreException { - // 1. Find the top-level class file - IClassFile topLevelClassFile = findTopLevelClassFile(classFile); - - // 2. Scan all matching IClassFile (top-level + inner classes) - Set allClassFiles = new LinkedHashSet<>(); - scanClassFiles(topLevelClassFile, allClassFiles); - - // 3. Process all classes found - for (IClassFile cf : allClassFiles) { - processClassFile(cf); - } - } - - private IClassFile findTopLevelClassFile(IClassFile classFile) throws CoreException { - IClassFile topLevelClassFile = classFile; - if (classFile instanceof IOrdinaryClassFile ordinaryClassFile) { - IType type = ordinaryClassFile.getType(); - // Navigate up to the top-level type - IType topLevelType = type; - while (topLevelType.getDeclaringType() != null) { - topLevelType = topLevelType.getDeclaringType(); - } - // Get the class file for the top-level type - if (topLevelType != type) { - topLevelClassFile = topLevelType.getClassFile(); - } - } - return topLevelClassFile; - } - - private void scanClassFiles(IClassFile classFile, Set result) throws CoreException { - // A standalone outer class may reference a member class that was - // not supplied. Keep decompiling the available bytecode instead of - // abandoning the entire outer type and its source mappings. - if (!classFile.exists()) { - JavaLanguageServerPlugin.log(new Status(IStatus.WARNING, - JavaLanguageServerPlugin.PLUGIN_ID, - "Nested class file is unavailable; showing available class content.")); - return; - } - if (classFile instanceof IOrdinaryClassFile ordinaryClassFile) { - if (!result.add(classFile)) { - return; - } - - // Collect declared member types (inner classes/interfaces) - IType type = ordinaryClassFile.getType(); - IType[] innerTypes = type.getTypes(); - for (IType innerType : innerTypes) { - IClassFile innerClassFile = innerType.getClassFile(); - if (innerClassFile != null) { - // Recursive call to handle nested inner classes - scanClassFiles(innerClassFile, result); - } - } - } - } - - private void processClassFile(IClassFile classFile) throws CoreException { - File file = new File(classFile.getElementName()).getAbsoluteFile(); - byte[] classBytes = classFile.getBytes(); - classFiles.add(file); - bytecodeMap.put(file.getPath(), classBytes); - } - - } -} diff --git a/third_party/jdtls/patches/README.md b/third_party/jdtls/patches/README.md deleted file mode 100644 index b10504f..0000000 --- a/third_party/jdtls/patches/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# JDT LS missing-inner-class patch - -The locked JDT LS 1.61.0 FernFlower integration aborts decompilation of an -available outer class when an entry in its InnerClasses attribute is absent. -This occurs with partial legacy libraries. The patch skips only nonexistent -class files during the integration's recursive collection. FernFlower, JDT's -Java model, source attachments and source/bytecode mappings remain upstream. -Missing class bodies are not reconstructed. - -`manifest.json` fixes the upstream revision, original source and bundle hashes, -modified source hash and complete replacement class set. The original source is -Eclipse EPL-2.0; its copyright header is retained. The modified source is shipped -in `licenses/jdt-decompiler/FernFlowerDecompiler.java` with patch metadata and the -existing EPL license. The upstream source URL is recorded in the manifest. - -`scripts/package/patch-jdt-decompiler.mjs` runs only while building a package. -It uses the manifest-pinned Temurin host JDK, compiles against the original -verified distribution and modifies only fresh package staging. Temporary compiler -output is invocation-owned and removed on success or failure; download caches, -installed plugins and application bundles remain read-only. Neither temporary -output nor assembled packages may be shared between worktrees. - -Because the core JDT bundle's bytes change, its Eclipse JAR signature and signed -entry digests are removed before repacking. OSGi manifest attributes are retained; -unrecognized signed manifest attributes fail packaging. The rebuilt JAR is **not -Eclipse-signed**. This does not change native JVM signatures or claim a plugin -publisher signature. Packaged metadata records compiler identity, original and -patched JAR hashes, modified source hash, signature removal and every replacement -class hash. Package verification checks these identities before distribution. - -Run `node --test --test-timeout=60000 scripts/package/*.test.mjs`, build the -package, and run `scripts/verify-package.sh` for the target architecture. In the -paired Viva client, `TestJavaPluginBinaryNavigation` uses its own generated JAR, -including an outer class whose nested class is deliberately omitted, and verifies -class/method locations and navigation between decompiled views. Private customer -class files are never included in the source or public test artifacts. - -Remove this patch when a pinned upstream release fixes partial inner-class -collection, after the same regression passes with its unmodified distribution. diff --git a/third_party/jdtls/patches/manifest.json b/third_party/jdtls/patches/manifest.json deleted file mode 100644 index e75ecf8..0000000 --- a/third_party/jdtls/patches/manifest.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "jdtls-1.61.0-missing-inner-class-1", - "upstreamRevision": "08eafe6ff60c7159ef88571d47b6a9ef82fef94e", - "upstreamSource": "https://github.com/eclipse-jdtls/eclipse.jdt.ls/blob/08eafe6ff60c7159ef88571d47b6a9ef82fef94e/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler.java", - "upstreamSourceSHA256": "63ceebf6a377b0b1805586d44d6bf13d7ba5ccecaf92879d85d2e4f708730008", - "sourceSHA256": "f188e0f7097c6b87d03fcca472c71b1b09faf44b0b91c51204e8677d493f28ae", - "originalCoreJarSHA256": "b382afc38a89e41959a56aee532ae567c7f804c3e4d4f13444114468789ec032", - "classEntries": [ - "org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler$1.class", - "org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler$BytecodeProvider.class", - "org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler$ResultSaver.class", - "org/eclipse/jdt/ls/core/internal/decompiler/FernFlowerDecompiler.class" - ] -}