From 68e749883af5b545b70b3cebefef0f3249c6a4bd Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Fri, 27 Nov 2026 12:32:50 +0000 Subject: [PATCH 1/4] fix(navigation): use Java 8 runtime declarations when sources are missing Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 9 ++- internal/deps/jars.go | 16 +++-- internal/jdk/find.go | 41 +++++++------ internal/jdk/find_test.go | 36 ++++++++++- internal/jdk/sources.go | 91 ++++++++++++++++++++-------- internal/jdk/sources_test.go | 6 +- internal/workspace/workspace.go | 12 ++-- internal/workspace/workspace_test.go | 43 ++++++++++++- 8 files changed, 194 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 8c52028..6b02503 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ | 跳转到定义 | 类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链、调用参数个数和实参类型解析,支持调用链 `a.b().c` 和 `Foo.bar()` | | 实现 / 父类双向跳转 | 接口/父类向下跳转到实现类与重写方法(`textDocument/implementation`),实现类/重写方法向上跳回接口与父类声明(`javaNavigation/superDeclarations`),并在行首绘制绿色 `I↓`/`I↑` 与蓝色 `O↓`/`O↑` 导航图标 | | Lombok | `@Data`/`@Getter`/`@Setter` 生成的访问器跳到字段,`@Builder`、`@Slf4j`、构造器注解跳到注解本身(与 JDT LS 一致) | -| 跳进 JDK | 项目里找不到的名字到本机 JDK 的 `src.zip` 里找,`String`、`List`、`hashCode()` 等都能跳,并能在 JDK 源码里继续跳 | +| 跳进 JDK | 打开本机 JDK 源码中的类和方法,例如 `String`、`List`、`hashCode()`。JDK 8 缺少源码包时,从它的 `rt.jar` 生成只读声明,支持继续跳转 | | 跳进依赖库 | Maven 和 Gradle 的依赖(含传递依赖)从本地仓库或缓存读取:下载过 `-sources.jar` 的打开源码,否则打开从 `.class` 生成的签名存根(类、成员类、字段、构造器、方法,参数名取自调试信息),并能在里面继续跳;`@Schema(description = ...)`、`log.info(...)`、`StrUtil.isEmpty(...)` 都能跳 | | 老项目的 jar | 读 Eclipse `.classpath`、Ant `build.xml` 的静态类路径,以及 `lib/`、`libs/`、`WEB-INF/lib` 里的 jar | | Eclipse 容器 | `.classpath` 里的服务器运行时容器(Tomcat、Jetty、WildFly 等)和 JUnit 容器换成本机已有的 jar,`HttpServletRequest`、`@WebServlet`、`@Test` 都能跳;没有 pom 的 `WEB-INF/web.xml` Web 项目同样补上 Servlet/JSP API | @@ -63,7 +63,10 @@ 项目按 Servlet 容器处理(web.xml 用 Jakarta EE 命名空间时取 `jakarta.servlet`)。不联网下载,本机都没有就跳过。 - 构建脚本、Gradle 版本目录、`pom.xml`、`.classpath` 或工作区内的 jar 变了、或距上次读取超过 5 分钟,下一次扫描重新读取依赖。 - JDK:按 `JAVA_HOME` → 系统默认 JDK(macOS 的 `/usr/libexec/java_home`,其他系统 `PATH` 上的 `java`)→ 常见安装目录 - (含 IntelliJ 的 `~/.jdks`、SDKMAN!)的顺序找第一个带 `src.zip` 的 JDK。只预先列出 zip 目录,某个类第一次被查到时才解析。 + (含 IntelliJ 的 `~/.jdks`、SDKMAN!)查找可用于导航的 JDK。每套 JDK 优先使用自己的 `src.zip`。 + JDK 8 缺少源码时,用同一套运行时的 `rt.jar` 按需生成类、字段和方法声明,方法体显示为 `/* compiled code */`。 + 例如,`JAVA_HOME` 指向只有 `rt.jar` 的 JDK 8 时,即使 `PATH` 上还有 JDK 17,跳转也会显示 JDK 8 的声明。 + JDK 9 及以上仍需要 `src.zip`。只预先列出归档目录,某个类第一次被查到时才解析。 跳进 JDK 时把那一个源码文件解压成只读副本,放在 Lithe 为插件分配的状态目录(`${stateDir}`)里,卸载插件时一起删除; 不写插件包或应用安装目录。 @@ -160,7 +163,7 @@ go run ./cmd/nav-bench -h # 在真实项目上测命中率、延迟和 `internal/deps/testdata/fixture` 里的 jar 由同目录的 `build.sh` 用 javac 编出(需要 JDK 17+),测试只读提交的 jar; 改了 `internal/deps/stub.go` 的输出时,运行 `go test ./internal/deps -run Golden -update` 更新 -`testdata/stubs`,并把 `stubFormat` 加一,让旧版本解压的副本不再被复用。 +`testdata/stubs`,并把 `StubFormat` 加一,让旧版本解压的副本不再被复用。 `dist/` 里每个平台一个 zip(`darwin-arm64`、`darwin-x64`、`windows-x64`、`windows-arm64`),包内只有 `plugin.json`、`bin/java-navigation`(Windows 是 `bin/java-navigation.exe`,对应平台包的 `plugin.json` 为语言服务器与 `--backend` 后端均写这个路径)、 diff --git a/internal/deps/jars.go b/internal/deps/jars.go index 8ddfc92..95983e4 100644 --- a/internal/deps/jars.go +++ b/internal/deps/jars.go @@ -37,9 +37,9 @@ import ( // MaxEntrySize skips class files and sources too large to read. const MaxEntrySize = 4 << 20 -// stubFormat names the output of the stub writer; change it with the writer, +// StubFormat names the output of the stub writer; change it with the writer, // so copies extracted by an older version are not reused. -const stubFormat = "1" +const StubFormat = "1" // ErrChanged reports a jar that changed since it was listed. var ErrChanged = errors.New("the dependency jar changed on disk") @@ -179,7 +179,7 @@ func (a *archive) list() ([]string, error) { a.size, a.mod = fi.Size(), fi.ModTime() id := a.file + "\x00" + strconv.FormatInt(a.size, 10) + "\x00" + a.mod.UTC().Format(time.RFC3339Nano) if !a.sources { - id += "\x00stub " + stubFormat // a new stub writer never reuses older copies + id += "\x00stub " + StubFormat // a new stub writer never reuses older copies } h := sha256.Sum256([]byte(id)) a.dir = sanitize(strings.ReplaceAll(a.Coord, ":", "_")) + "-" + hex.EncodeToString(h[:6]) @@ -264,6 +264,12 @@ func (s *Set) Read(p string) ([]byte, error) { return read(entry) } stem := strings.TrimSuffix(entry, ".java") + return ClassStub(filepath.Base(a.Path), stem, read, func(name string) bool { return files[name] != nil }) +} + +// ClassStub renders the signatures of a top-level class and its member classes. +// Both the dependency and JDK readers supply archive-relative .class entries. +func ClassStub(origin, stem string, read func(string) ([]byte, error), has func(string) bool) ([]byte, error) { b, err := read(stem + ".class") if err != nil { return nil, err @@ -280,8 +286,8 @@ func (s *Set) Read(p string) ([]byte, error) { c, err := parseClass(b) return c, err == nil } - exists := func(binary string) bool { return files[binary+".class"] != nil } - return writeStub(top, filepath.Base(a.Path), load, exists), nil + exists := func(binary string) bool { return has(binary + ".class") } + return writeStub(top, origin, load, exists), nil } // CacheDir is the directory under state that holds the copies of the sources diff --git a/internal/jdk/find.go b/internal/jdk/find.go index faeb514..4eaf652 100644 --- a/internal/jdk/find.go +++ b/internal/jdk/find.go @@ -13,20 +13,17 @@ import ( "time" ) -// JDK is an installed Java Development Kit that ships its class library's -// sources, which go to declaration reads (ADR 0041). +// JDK describes an installation with navigable standard library declarations. type JDK struct { Home string // the JDK's home directory Version string // JAVA_VERSION from its release file; "" if unknown - Sources string // the src.zip inside Home + Archive string // src.zip, or the Java 8 runtime's rt.jar } -// FindJDK returns the JDK whose sources navigation uses: the one the user -// chose (JAVA_HOME, then the system default: macOS's java_home, or the java -// on PATH elsewhere) when it has sources, otherwise the newest installed JDK -// that has them. It reports false when no JDK with sources is installed; a -// JRE, or a JDK packaged without src.zip (some Linux distributions split it -// into a separate package), does not count. +// FindJDK looks for declarations in JAVA_HOME, then the system default JDK, +// then the newest usable installation. A Java 8 runtime with rt.jar is usable +// even without sources, so its declarations take precedence over a different +// JDK's APIs. // // It reads environment variables, starts at most one short-lived process // (macOS) and lists a few well-known install directories; it does not search @@ -36,8 +33,8 @@ func FindJDK(ctx context.Context) (JDK, bool) { return pickJDK(jdkPreferred(ctx), jdkInstalled(runtime.GOOS, home, os.Getenv)) } -// pickJDK returns the first preferred home with sources, else the installed -// home with sources and the highest version (the lexically first path among +// pickJDK returns the first usable preferred home, else the installed +// usable home with the highest version (the lexically first path among // equals, so the choice is stable). func pickJDK(preferred, installed []string) (JDK, bool) { for _, h := range preferred { @@ -49,10 +46,10 @@ func pickJDK(preferred, installed []string) (JDK, bool) { seen := map[string]bool{} for _, h := range installed { j, ok := jdkAt(h) - if !ok || seen[j.Sources] { + if !ok || seen[j.Archive] { continue } - seen[j.Sources] = true + seen[j.Archive] = true found = append(found, j) } if len(found) == 0 { @@ -67,9 +64,7 @@ func pickJDK(preferred, installed []string) (JDK, bool) { return found[0], true } -// jdkAt describes the JDK at home if it has sources: lib/src.zip since JDK 9, -// src.zip in the home directory before. A JDK 8 java executable lives in -// jre/bin, so a home ending in "jre" is retried one level up. +// jdkAt checks the source archive first, then pre-modular runtime layouts. func jdkAt(home string) (JDK, bool) { if home == "" { return JDK{}, false @@ -80,11 +75,21 @@ func jdkAt(home string) (JDK, bool) { for _, rel := range []string{filepath.Join("lib", "src.zip"), "src.zip"} { p := filepath.Join(home, rel) if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() { - return JDK{Home: home, Version: releaseVersion(home), Sources: p}, true + return JDK{Home: home, Version: releaseVersion(home), Archive: p}, true } } if filepath.Base(home) == "jre" { - return jdkAt(filepath.Dir(home)) + // java may live in /jre/bin. Prefer the enclosing JDK's + // archive (and its release metadata) over the embedded runtime. + if j, ok := jdkAt(filepath.Dir(home)); ok { + return j, true + } + } + for _, rel := range []string{filepath.Join("jre", "lib", "rt.jar"), filepath.Join("lib", "rt.jar")} { + p := filepath.Join(home, rel) + if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() { + return JDK{Home: home, Version: releaseVersion(home), Archive: p}, true + } } return JDK{}, false } diff --git a/internal/jdk/find_test.go b/internal/jdk/find_test.go index fc03256..ba3c6be 100644 --- a/internal/jdk/find_test.go +++ b/internal/jdk/find_test.go @@ -41,13 +41,13 @@ func TestPickJDK(t *testing.T) { // Without a preference: the newest JDK that has sources. j, ok := pickJDK(nil, installed) - if !ok || j.Home != jdk17 || j.Version != "17.0.18" || j.Sources != filepath.Join(jdk17, "lib", "src.zip") { + if !ok || j.Home != jdk17 || j.Version != "17.0.18" || j.Archive != filepath.Join(jdk17, "lib", "src.zip") { t.Errorf("newest = %+v ok=%v, want %s", j, ok, jdk17) } // A preferred JDK with sources wins over a newer one; JDK 8 keeps // src.zip in its home. j, ok = pickJDK([]string{"", jdk8}, installed) - if !ok || j.Home != jdk8 || j.Sources != filepath.Join(jdk8, "src.zip") { + if !ok || j.Home != jdk8 || j.Archive != filepath.Join(jdk8, "src.zip") { t.Errorf("preferred = %+v ok=%v, want %s", j, ok, jdk8) } // A preferred JDK without sources falls through to the others. @@ -77,6 +77,38 @@ func TestPickJDK(t *testing.T) { } } +func TestJava8RuntimeDeclarations(t *testing.T) { + root := t.TempDir() + home := fakeJDK(t, filepath.Join(root, "jdk8"), "1.8.0_512", "") + newer := fakeJDK(t, filepath.Join(root, "jdk17"), "17", "src.zip") + jre := filepath.Join(home, "jre") + rt := filepath.Join(jre, "lib", "rt.jar") + if err := os.MkdirAll(filepath.Dir(rt), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(rt, nil, 0o644); err != nil { + t.Fatal(err) + } + for _, preferred := range []string{home, jre} { + j, ok := pickJDK([]string{preferred, newer}, nil) + if !ok || j.Home != home || j.Archive != rt { + t.Fatalf("preferred %s: got %+v, want %s", preferred, j, rt) + } + } + j, ok := pickJDK(nil, []string{home}) + if !ok || j.Archive != rt { + t.Fatalf("automatic discovery = %+v, want %s", j, rt) + } + src := filepath.Join(home, "src.zip") + if err := os.WriteFile(src, nil, 0o644); err != nil { + t.Fatal(err) + } + j, ok = pickJDK([]string{jre}, nil) + if !ok || j.Archive != src { + t.Fatalf("with matching sources = %+v, want %s", j, src) + } +} + func TestCompareJavaVersions(t *testing.T) { for _, c := range []struct { a, b string diff --git a/internal/jdk/sources.go b/internal/jdk/sources.go index 37db6a0..d830f5f 100644 --- a/internal/jdk/sources.go +++ b/internal/jdk/sources.go @@ -18,13 +18,12 @@ import ( "time" "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/codenav" + "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/deps" ) -// The JDK's class library sources, read from its src.zip (adapted from Viff's -// ADR 0041). Only the archive's directory is read up front; codenav parses a -// class the first time a lookup needs it. The archive is not kept open: each -// read opens it, checks that it is still the file that was listed (a JDK -// update replaces it) and reads one entry. +// JDK archive indexing (adapted from Viff's ADR 0041). Only the directory +// and entry offsets are read up front. Each lookup opens the archive once, +// checks its identity and reads only the source or class entries it needs. // MaxFileSize skips sources too large to have been written by hand. const MaxFileSize = 2 << 20 @@ -32,15 +31,16 @@ const MaxFileSize = 2 << 20 // ErrChanged reports an archive that changed since it was listed. var ErrChanged = errors.New("the JDK sources changed on disk") -// Sources is the listed content of a JDK's src.zip. It never changes after -// Open, so its methods run on any goroutine. +// Sources provides Java text from src.zip or signature stubs from rt.jar. +// It never changes after Open, so its methods run on any goroutine. type Sources struct { version string archive string size int64 mod time.Time - entries map[string]entry // by entry name, .java files only - names []string // the entry names, in archive order + stubs bool + entries map[string]entry // raw archive entries, including member classes for stubs + names []string // navigable .java paths, in archive order } // entry locates one stored or deflated file in the archive. @@ -52,7 +52,7 @@ type entry struct { // Open lists the Java sources of j's archive. func Open(j JDK) (*Sources, error) { - f, err := os.Open(j.Sources) + f, err := os.Open(j.Archive) if err != nil { return nil, fmt.Errorf("open JDK sources: %w", err) } @@ -65,10 +65,21 @@ func Open(j JDK) (*Sources, error) { if err != nil { return nil, fmt.Errorf("read JDK sources: %w", err) } - s := &Sources{version: j.Version, archive: j.Sources, size: fi.Size(), mod: fi.ModTime(), entries: map[string]entry{}} + s := &Sources{version: j.Version, archive: j.Archive, size: fi.Size(), mod: fi.ModTime(), entries: map[string]entry{}, + stubs: filepath.Base(j.Archive) == "rt.jar"} names := make([]string, 0, len(zr.File)) for _, e := range zr.File { - if !codenav.Supports(e.Name) || e.FileInfo().IsDir() || e.Method != zip.Store && e.Method != zip.Deflate { + if e.FileInfo().IsDir() || e.Method != zip.Store && e.Method != zip.Deflate || !validEntry(e.Name) { + continue + } + name := e.Name + if s.stubs { + stem, ok := strings.CutSuffix(name, ".class") + if !ok || strings.HasPrefix(name, "META-INF/") { + continue + } + name = stem + ".java" + } else if !codenav.Supports(name) { continue } off, err := e.DataOffset() @@ -77,10 +88,13 @@ func Open(j JDK) (*Sources, error) { } s.entries[e.Name] = entry{off: off, csize: int64(e.CompressedSize64), size: int64(e.UncompressedSize64), deflate: e.Method == zip.Deflate, crc: e.CRC32} - names = append(names, e.Name) + // A member class is rendered in its top-level class's stub. + if !s.stubs || !strings.Contains(path.Base(name), "$") { + names = append(names, name) + } } if len(names) == 0 { - return nil, fmt.Errorf("read JDK sources: no Java sources in %s", j.Sources) + return nil, fmt.Errorf("read JDK library: no declarations in %s", j.Archive) } s.names = names return s, nil @@ -93,11 +107,21 @@ func (s *Sources) Names() []string { return s.names } // Version is the JDK's JAVA_VERSION, "" when unknown. func (s *Sources) Version() string { return s.version } -// Archive is the absolute path of the listed src.zip. +// Archive is the absolute path of the listed src.zip or rt.jar. func (s *Sources) Archive() string { return s.archive } +// UsesStubs reports whether navigation displays signatures instead of source text. +func (s *Sources) UsesStubs() bool { return s.stubs } + // Has reports whether name is a listed Java source. func (s *Sources) Has(name string) bool { + if s.stubs { + stem, ok := strings.CutSuffix(name, ".java") + if !ok || strings.Contains(path.Base(stem), "$") { + return false + } + name = stem + ".class" + } _, ok := s.entries[name] return ok } @@ -110,13 +134,9 @@ func (s *Sources) Changed() bool { // Read returns the content of one listed entry. func (s *Sources) Read(name string) ([]byte, error) { - e, ok := s.entries[name] - if !ok { + if !s.Has(name) { return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist) } - if e.size > MaxFileSize { - return nil, fmt.Errorf("%s: larger than %d bytes", name, MaxFileSize) - } f, err := os.Open(s.archive) if err != nil { return nil, err @@ -125,6 +145,25 @@ func (s *Sources) Read(name string) ([]byte, error) { if fi, err := f.Stat(); err != nil || fi.Size() != s.size || !fi.ModTime().Equal(s.mod) { return nil, ErrChanged } + if s.stubs { + read := func(name string) ([]byte, error) { return s.readEntry(f, name, deps.MaxEntrySize) } + has := func(name string) bool { + _, ok := s.entries[name] + return ok + } + return deps.ClassStub(filepath.Base(s.archive), strings.TrimSuffix(name, ".java"), read, has) + } + return s.readEntry(f, name, MaxFileSize) +} + +func (s *Sources) readEntry(f *os.File, name string, limit int64) ([]byte, error) { + e, ok := s.entries[name] + if !ok { + return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist) + } + if e.size < 0 || e.size > limit { + return nil, fmt.Errorf("%s: invalid size %d (limit %d)", name, e.size, limit) + } var r io.Reader = io.NewSectionReader(f, e.off, e.csize) if e.deflate { fr := flate.NewReader(r) @@ -145,7 +184,11 @@ func (s *Sources) Read(name string) ([]byte, error) { // these sources. It is named after the archive's identity (path, size and // modification time), so a replaced JDK never reuses copies of the old one. func (s *Sources) CacheDir(state string) string { - h := sha256.Sum256([]byte(s.archive + "\x00" + strconv.FormatInt(s.size, 10) + "\x00" + s.mod.UTC().Format(time.RFC3339Nano))) + id := s.archive + "\x00" + strconv.FormatInt(s.size, 10) + "\x00" + s.mod.UTC().Format(time.RFC3339Nano) + if s.stubs { + id += "\x00stub " + deps.StubFormat + } + h := sha256.Sum256([]byte(id)) name := "jdk" if s.version != "" { name += "-" + sanitize(s.version) @@ -163,7 +206,7 @@ func (s *Sources) Extract(state, name string) (string, error) { return "", fmt.Errorf("%s: %w", name, fs.ErrNotExist) } dst := filepath.Join(s.CacheDir(state), filepath.FromSlash(name)) - if fi, err := os.Stat(dst); err == nil && fi.Mode().IsRegular() && fi.Size() == s.entries[name].size { + if fi, err := os.Stat(dst); err == nil && fi.Mode().IsRegular() && (s.stubs || fi.Size() == s.entries[name].size) { return dst, nil } b, err := s.Read(name) @@ -191,7 +234,7 @@ func (s *Sources) Extract(state, name string) (string, error) { os.Remove(tmp.Name()) // Another request may have extracted the same entry; Windows refuses // to replace a read-only file. - if fi, serr := os.Stat(dst); serr == nil && fi.Size() == s.entries[name].size { + if fi, serr := os.Stat(dst); serr == nil && fi.Mode().IsRegular() && fi.Size() == int64(len(b)) { return dst, nil } return "", fmt.Errorf("extract JDK source: %w", err) @@ -212,7 +255,7 @@ func (s *Sources) EntryOf(state, file string) (string, bool) { // validEntry refuses entry names that would escape the cache directory. func validEntry(name string) bool { - if name == "" || strings.HasPrefix(name, "/") || strings.Contains(name, "\\") || strings.Contains(name, ":") { + if name == "" || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\:"+deps.Sep) { return false } return path.Clean(name) == name && !strings.HasPrefix(name, "../") && name != ".." diff --git a/internal/jdk/sources_test.go b/internal/jdk/sources_test.go index d1b366d..f7e63c1 100644 --- a/internal/jdk/sources_test.go +++ b/internal/jdk/sources_test.go @@ -45,7 +45,7 @@ func TestSourcesExtractAndMapBack(t *testing.T) { "java.base/module-info.java": "module java.base {}\n", "README": "not a source", }) - s, err := Open(JDK{Version: "17.0.18", Sources: archive}) + s, err := Open(JDK{Version: "17.0.18", Archive: archive}) if err != nil { t.Fatal(err) } @@ -82,7 +82,7 @@ func TestSourcesExtractAndMapBack(t *testing.T) { func TestSourcesNoticeAReplacedArchive(t *testing.T) { dir := t.TempDir() archive := writeZip(t, dir, map[string]string{"java/lang/Object.java": "package java.lang;\npublic class Object {}\n"}) - s, err := Open(JDK{Sources: archive}) + s, err := Open(JDK{Archive: archive}) if err != nil { t.Fatal(err) } @@ -101,7 +101,7 @@ func TestSourcesNoticeAReplacedArchive(t *testing.T) { if _, err := s.Read("java/lang/Object.java"); !errors.Is(err, ErrChanged) { t.Errorf("read of a replaced archive = %v, want ErrChanged", err) } - s2, err := Open(JDK{Sources: archive}) + s2, err := Open(JDK{Archive: archive}) if err != nil { t.Fatal(err) } diff --git a/internal/workspace/workspace.go b/internal/workspace/workspace.go index 434819e..f3a8eaf 100644 --- a/internal/workspace/workspace.go +++ b/internal/workspace/workspace.go @@ -13,8 +13,8 @@ // copy on disk, and the document a query comes from is parsed from that // text again. // -// Names the folder does not declare resolve into the JDK's sources when a JDK -// with sources is installed, and into the locally cached jars of the folder's Maven +// Names the folder does not declare resolve into the JDK's sources (or Java 8 +// runtime signatures), and into the locally cached jars of the folder's Maven // and Gradle dependencies (package deps). Their // declarations are extracted, one file at a time, into read-only copies // under the state directory, which the editor opens as ordinary files; a @@ -621,8 +621,12 @@ func (w *Workspace) runScan(run *scanRun) { w.sources = found changed = true } - if w.sources != nil { - w.opt.Logf("JDK sources: %s (%s)", w.sources.Archive(), w.sources.Version()) + if found != nil { + label := "JDK sources" + if found.UsesStubs() { + label = "JDK declaration stubs" + } + w.opt.Logf("%s: %s (%s)", label, found.Archive(), found.Version()) } } if lookDeps { diff --git a/internal/workspace/workspace_test.go b/internal/workspace/workspace_test.go index aa16e3e..86662dd 100644 --- a/internal/workspace/workspace_test.go +++ b/internal/workspace/workspace_test.go @@ -227,7 +227,48 @@ func fakeJDK(t *testing.T, files map[string]string) func(context.Context) (jdk.J t.Fatal(err) } f.Close() - return func(context.Context) (jdk.JDK, bool) { return jdk.JDK{Version: "17.0.18", Sources: p}, true } + return func(context.Context) (jdk.JDK, bool) { return jdk.JDK{Version: "17.0.18", Archive: p}, true } +} + +func TestDefinitionIntoRuntimeJarWithoutSources(t *testing.T) { + // Reuse actual class files, including a member class, without requiring + // javac or redistributing a JDK in the test suite. + b, err := os.ReadFile(filepath.Join("..", "deps", "testdata", "fixture", "lib-1.0.jar")) + if err != nil { + t.Fatal(err) + } + rt := filepath.Join(t.TempDir(), "rt.jar") + if err := os.WriteFile(rt, b, 0o644); err != nil { + t.Fatal(err) + } + root := t.TempDir() + src := "import com.example.lib.Container;\nclass App { int f(Container box) { return box.size(); } }" + write(t, root, map[string]string{"App.java": src}) + w := newTestWorkspace(t, root, func(context.Context) (jdk.JDK, bool) { + return jdk.JDK{Version: "1.8.0_512", Archive: rt}, true + }) + doc := w.DocOf(filepath.Join(root, "App.java")) + for _, tc := range []struct{ use, declaration string }{ + {"Container", "public class Container"}, + {"size()", "public int size()"}, + } { + target, ok, err := w.Definition(ctx(t), doc, []byte(src), at(t, src, tc.use, 0, 1)) + if err != nil || !ok { + t.Fatalf("definition of %s = %+v, %v", tc.use, target, err) + } + if got := w.DocOf(target.File).Library; got != "com/example/lib/Container.java" { + t.Fatalf("DocOf(%s) = %s", target.File, got) + } + body, err := os.ReadFile(target.File) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(string(body), "\n") + if target.Line >= len(lines) || !strings.Contains(lines[target.Line], tc.declaration) || + !strings.Contains(lines[0], "Signatures read from rt.jar") || !strings.Contains(string(body), "class Builder") { + t.Fatalf("incorrect stub or target for %s: %+v\n%s", tc.use, target, body) + } + } } func TestDefinitionIntoTheJDKAndBack(t *testing.T) { From 17ea39098ebcb38456088796ca68bb281d637c05 Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Fri, 27 Nov 2026 13:06:42 +0000 Subject: [PATCH 2/4] fix(navigation): use the workspace Java installation and label JDK tabs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 5 +- cmd/java-navigation/main.go | 14 ++- internal/backend/backend.go | 39 ++++++++ internal/backend/backend_test.go | 20 ++++ internal/deps/deps_test.go | 27 ++++++ internal/deps/maven.go | 95 +++++++++++++++++-- internal/jdk/find.go | 9 +- internal/jdk/find_test.go | 17 ++++ internal/jdk/sources.go | 23 ++++- internal/jdk/sources_test.go | 3 + internal/lsp/server.go | 6 +- internal/workspace/workspace_test.go | 6 +- .../plugin.json | 13 +-- scripts/package.mjs | 5 +- scripts/package/linux.test.mjs | 3 +- 15 files changed, 251 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 6b02503..d59a372 100644 --- a/README.md +++ b/README.md @@ -62,12 +62,13 @@ 项目自己已经带了 Servlet 或 JUnit 的 jar 时不再补。没有 `pom.xml`/Gradle 构建文件、但有 `WEB-INF/web.xml` 的 项目按 Servlet 容器处理(web.xml 用 Jakarta EE 命名空间时取 `jakarta.servlet`)。不联网下载,本机都没有就跳过。 - 构建脚本、Gradle 版本目录、`pom.xml`、`.classpath` 或工作区内的 jar 变了、或距上次读取超过 5 分钟,下一次扫描重新读取依赖。 -- JDK:按 `JAVA_HOME` → 系统默认 JDK(macOS 的 `/usr/libexec/java_home`,其他系统 `PATH` 上的 `java`)→ 常见安装目录 +- JDK:启动时采用 Lithe 为当前工作区解析的 `java` 工具。Maven 根 POM 或其本地父 POM 若显式启用 fork 且指定了绝对路径的 `javac`,使用该编译器所在的 JDK。插件不运行编译器,也不从 `source`、`target`、`release` 推断安装目录。Maven profile、按模块或执行阶段切换的编译器、构建工具内部另行选择的 toolchain 不在此解析范围。 + 选中的安装缺少可导航归档时,项目内导航仍然可用。宿主没有提供 Java 安装(例如没有启用定义 `java` 工具的插件),且 Maven 没有指定编译器时,按 `JAVA_HOME` → 系统默认 JDK(macOS 的 `/usr/libexec/java_home`,其他系统 `PATH` 上的 `java`)→ 常见安装目录 (含 IntelliJ 的 `~/.jdks`、SDKMAN!)查找可用于导航的 JDK。每套 JDK 优先使用自己的 `src.zip`。 JDK 8 缺少源码时,用同一套运行时的 `rt.jar` 按需生成类、字段和方法声明,方法体显示为 `/* compiled code */`。 例如,`JAVA_HOME` 指向只有 `rt.jar` 的 JDK 8 时,即使 `PATH` 上还有 JDK 17,跳转也会显示 JDK 8 的声明。 JDK 9 及以上仍需要 `src.zip`。只预先列出归档目录,某个类第一次被查到时才解析。 - 跳进 JDK 时把那一个源码文件解压成只读副本,放在 Lithe 为插件分配的状态目录(`${stateDir}`)里,卸载插件时一起删除; + 跳转后的编辑器标签标明版本与来源,如 `String [JDK 1.8.0_512 - rt.jar].java`。源码或签名的只读副本放在 Lithe 为插件分配的状态目录(`${stateDir}`)里,卸载插件时一起删除; 不写插件包或应用安装目录。 解析规则来自 [Viff](https://github.com/1lck/viff)(MIT),见 `internal/codenav/UPSTREAM.md` 和 `THIRD_PARTY_NOTICES.md`。 diff --git a/cmd/java-navigation/main.go b/cmd/java-navigation/main.go index fccd3ff..77a0690 100644 --- a/cmd/java-navigation/main.go +++ b/cmd/java-navigation/main.go @@ -5,11 +5,13 @@ package main import ( + "context" "errors" "flag" "fmt" "log" "os" + "path/filepath" "runtime/debug" "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/backend" @@ -36,6 +38,7 @@ func main() { state := flag.String("state-dir", "", "writable directory for extracted JDK sources (the host's ${stateDir})") printVersion := flag.Bool("version", false, "print the version and exit") noJDK := flag.Bool("no-jdk", false, "do not navigate into the JDK's sources") + jdkHome := flag.String("jdk-home", "", "Java installation selected for this workspace") noDeps := flag.Bool("no-dependencies", false, "do not navigate into dependency jars (Maven, Gradle and the jars the project keeps)") runBackend := flag.Bool("backend", false, "run as a Lithe plugin backend over stdio") flag.Bool("stdio", true, "speak LSP over standard input and output (the only transport)") @@ -52,7 +55,16 @@ func main() { logger := log.New(os.Stderr, "java-navigation: ", log.LstdFlags|log.Lmsgprefix) opt := lsp.Options{Name: "java-navigation", Version: version, State: *state, Logf: logger.Printf} if !*noJDK && *state != "" { - opt.FindJDK = jdk.FindJDK + opt.FindJDK = func(ctx context.Context, root string) (jdk.JDK, bool) { + selected := *jdkHome + if exe := deps.MavenCompilerExecutable(ctx, root, logger.Printf); exe != "" { + if real, err := filepath.EvalSymlinks(exe); err == nil { + exe = real + } + selected = filepath.Dir(filepath.Dir(exe)) + } + return jdk.FindJDK(ctx, selected, logger.Printf) + } } if !*noDeps && *state != "" { opt.Dependencies = true diff --git a/internal/backend/backend.go b/internal/backend/backend.go index 8249fc1..8ae281e 100644 --- a/internal/backend/backend.go +++ b/internal/backend/backend.go @@ -9,6 +9,7 @@ import ( "fmt" "net/url" "path" + "path/filepath" "strings" "sync" "time" @@ -96,6 +97,9 @@ func New(version string) (*lithe.Backend, error) { if err := b.Function(CollectFunctionID, svc.collect); err != nil { return nil, err } + if err := b.Function("javaNavigation.resolveLaunch", resolveLaunch); err != nil { + return nil, err + } if err := b.SuppressSuccessDiagnostics(CollectFunctionID); err != nil { return nil, err } @@ -123,6 +127,41 @@ func New(version string) (*lithe.Backend, error) { return b, nil } +// resolveLaunch receives the optional workspace Java tool resolved by Lithe's +// Build/Run resolver. Always launch the Go server shipped for this platform. +func resolveLaunch(params json.RawMessage, _ *lithe.Context) (any, error) { + var p struct { + StateDirectory string + Platform struct{ OS string } + Tools map[string]struct{ Home, Executable string } + } + if json.Unmarshal(params, &p) != nil || p.StateDirectory == "" { + return nil, lithe.NewPluginError(errInvalidParams, "Missing launch directories.") + } + executable := "bin/java-navigation" + if p.Platform.OS == "windows" { + executable += ".exe" + } + args := []string{"--state-dir", p.StateDirectory} + if java, ok := p.Tools["java"]; ok { + home := java.Home + if home == "" && filepath.IsAbs(java.Executable) { + exe := java.Executable + if real, err := filepath.EvalSymlinks(exe); err == nil { + exe = real + } + home = filepath.Dir(filepath.Dir(exe)) + } + if home != "" { + args = append(args, "--jdk-home", home) + } + } + return map[string]any{ + "executable": map[string]string{"kind": "packaged", "path": executable}, + "arguments": args, + }, nil +} + func (s *Service) shutdown() { s.mu.Lock() if !s.closed { diff --git a/internal/backend/backend_test.go b/internal/backend/backend_test.go index 700e1a4..aad348a 100644 --- a/internal/backend/backend_test.go +++ b/internal/backend/backend_test.go @@ -184,6 +184,26 @@ func TestBackendRegistrationCollectAndInvokeWithQuietLogging(t *testing.T) { t.Fatalf("initialize failed: %+v", initResp) } m.notify("initialized", map[string]any{}) + // Start through the same backend function the host uses. Java is only + // an optional navigation input, never the language server executable. + for i, tc := range []struct { + tools any + want []string + }{ + {nil, []string{"--state-dir", "/state"}}, + {map[string]any{"java": map[string]string{"home": "/selected/jdk 8", "version": "1.8"}}, []string{"--state-dir", "/state", "--jdk-home", "/selected/jdk 8"}}, + } { + id := 30 + i + m.request(id, "lithe/function/invoke", map[string]any{ + "functionID": "javaNavigation.resolveLaunch", "operationID": fmt.Sprintf("op-launch-%d", i), "context": ctxRef, + "params": map[string]any{"serverID": "java", "stateDirectory": "/state", "platform": map[string]string{"os": "windows"}, "tools": tc.tools}, + }) + frame, _ := m.runUntil(func(f map[string]any) bool { return f["id"] == float64(id) }, func(string, map[string]any) any { return map[string]any{} }) + launch := mapField(frame, "result") + if mapField(launch, "executable")["path"] != "bin/java-navigation.exe" || fmt.Sprint(launch["arguments"]) != fmt.Sprint(tc.want) { + t.Fatalf("unexpected launch answer: %+v", frame) + } + } m.notify(methodDidChangeState, map[string]any{ "serverID": "java", "state": "running", diff --git a/internal/deps/deps_test.go b/internal/deps/deps_test.go index 16bae31..a4f0697 100644 --- a/internal/deps/deps_test.go +++ b/internal/deps/deps_test.go @@ -365,3 +365,30 @@ func TestLocalRepositoryHonoursSettings(t *testing.T) { t.Errorf("from settings = %s, want %s", got, custom) } } + +// A forked compiler can differ from the Java installation running Maven. +func TestMavenCompilerExecutable(t *testing.T) { + root := t.TempDir() + child := filepath.Join(root, "module") + if err := os.Mkdir(child, 0o755); err != nil { + t.Fatal(err) + } + exe := filepath.Join(root, "jdk 8", "bin", "javac") + t.Setenv("TEST_MAVEN_JAVAC", exe) + parent := `parentmaven-compiler-plugintrue${compiler}` + module := `parent${env.TEST_MAVEN_JAVAC}` + for dir, pom := range map[string]string{root: parent, child: module} { + if err := os.WriteFile(filepath.Join(dir, "pom.xml"), []byte(pom), 0o644); err != nil { + t.Fatal(err) + } + } + if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != exe { + t.Fatalf("got %q, want %q", got, exe) + } + if err := os.WriteFile(filepath.Join(child, "pom.xml"), []byte(`8${env.TEST_MAVEN_JAVAC}`), 0o644); err != nil { + t.Fatal(err) + } + if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != "" { + t.Fatalf("unforked compiler selected %q", got) + } +} diff --git a/internal/deps/maven.go b/internal/deps/maven.go index b4002b2..23a182f 100644 --- a/internal/deps/maven.go +++ b/internal/deps/maven.go @@ -72,6 +72,13 @@ type pomXML struct { Properties properties `xml:"properties"` Managed []pomDep `xml:"dependencyManagement>dependencies>dependency"` Dependencies []pomDep `xml:"dependencies>dependency"` + Plugins []struct { + Group string `xml:"groupId"` + Artifact string `xml:"artifactId"` + Fork string `xml:"configuration>fork"` + Executable string `xml:"configuration>executable"` + Inherited string `xml:"inherited"` + } `xml:"build>plugins>plugin"` } type properties map[string]string @@ -105,6 +112,64 @@ type model struct { deps []pomDep } +// MavenCompilerExecutable reads a workspace root POM's explicit forked javac. +// Compiler release/source/target levels do not identify an installation. +// Walking just the local parent chain avoids resolving dependency BOMs during +// JDK discovery. A non-local parent or a dynamic profile needs a build import. +func MavenCompilerExecutable(ctx context.Context, root string, logf func(string, ...any)) string { + m := newMaven(ctx, nil, logf) + pom := filepath.Join(root, "pom.xml") + props := properties{"project.basedir": root, "basedir": root} + var fork, executable string + for depth := 0; depth < maxParents && ctx.Err() == nil; depth++ { + p := m.readPOM(pom) + if p == nil { + break + } + for k, v := range p.Properties { + if _, exists := props[k]; !exists { + props[k] = v + } + } + for _, plugin := range p.Plugins { + if plugin.Artifact != "maven-compiler-plugin" || (plugin.Group != "" && plugin.Group != "org.apache.maven.plugins") || (depth > 0 && plugin.Inherited == "false") { + continue + } + if fork == "" { + fork = plugin.Fork + } + if executable == "" { + executable = plugin.Executable + } + } + if p.Parent.ArtifactID == "" { + break + } + pom = m.localParent(pom, p) + if pom == "" { + break + } + } + if fork == "" { + fork = props["maven.compiler.fork"] + } + if !strings.EqualFold(m.interpolate(fork, props), "true") { + return "" + } + if executable == "" { + executable = props["maven.compiler.executable"] + } + executable = m.interpolate(executable, props) + if strings.Contains(executable, "${") || !filepath.IsAbs(executable) { + return "" + } + name := filepath.Base(executable) + if name != "javac" && !strings.EqualFold(name, "javac.exe") { + return "" + } + return executable +} + func depKey(d pomDep) string { t := d.Type if t == "" { @@ -408,17 +473,9 @@ func (m *maven) model(path string) *model { // names (../pom.xml by default) when that is the parent, else the working // tree's POM of those coordinates, else the local repository's. func (m *maven) parentOf(path string, p *pomXML) *model { - rel := "../pom.xml" - if p.Parent.RelativePath != nil { - rel = strings.TrimSpace(*p.Parent.RelativePath) - } // Gradle's hash directories never contain a source tree's relative parent. - if rel != "" && !m.repo.gradle { - cand := filepath.Join(filepath.Dir(path), filepath.FromSlash(rel)) - if fi, err := os.Stat(cand); err == nil && fi.IsDir() { - cand = filepath.Join(cand, "pom.xml") - } - if pp := m.readPOM(cand); pp != nil && pp.ArtifactID == p.Parent.ArtifactID { + if !m.repo.gradle { + if cand := m.localParent(path, p); cand != "" { return m.model(cand) } } @@ -432,6 +489,24 @@ func (m *maven) parentOf(path string, p *pomXML) *model { return nil } +func (m *maven) localParent(path string, p *pomXML) string { + rel := "../pom.xml" + if p.Parent.RelativePath != nil { + rel = strings.TrimSpace(*p.Parent.RelativePath) + if rel == "" { + return "" + } + } + cand := filepath.Join(filepath.Dir(path), filepath.FromSlash(rel)) + if fi, err := os.Stat(cand); err == nil && fi.IsDir() { + cand = filepath.Join(cand, "pom.xml") + } + if pp := m.readPOM(cand); pp != nil && pp.ArtifactID == p.Parent.ArtifactID { + return cand + } + return "" +} + func (m *maven) interpolateDep(d pomDep, props map[string]string) pomDep { d.GroupID = m.interpolate(d.GroupID, props) d.ArtifactID = m.interpolate(d.ArtifactID, props) diff --git a/internal/jdk/find.go b/internal/jdk/find.go index 4eaf652..ddd204c 100644 --- a/internal/jdk/find.go +++ b/internal/jdk/find.go @@ -28,7 +28,14 @@ type JDK struct { // It reads environment variables, starts at most one short-lived process // (macOS) and lists a few well-known install directories; it does not search // the disk. -func FindJDK(ctx context.Context) (JDK, bool) { +func FindJDK(ctx context.Context, selected string, logf func(string, ...any)) (JDK, bool) { + if selected != "" { + j, ok := jdkAt(selected) + if !ok { + logf("selected workspace JDK has no navigable archive: %s", selected) + } + return j, ok + } home, _ := os.UserHomeDir() return pickJDK(jdkPreferred(ctx), jdkInstalled(runtime.GOOS, home, os.Getenv)) } diff --git a/internal/jdk/find_test.go b/internal/jdk/find_test.go index ba3c6be..ae4571d 100644 --- a/internal/jdk/find_test.go +++ b/internal/jdk/find_test.go @@ -109,6 +109,23 @@ func TestJava8RuntimeDeclarations(t *testing.T) { } } +func TestSelectedJDKPrecedesEnvironment(t *testing.T) { + root := t.TempDir() + system := fakeJDK(t, filepath.Join(root, "jdk17"), "17", "src.zip") + selected := fakeJDK(t, filepath.Join(root, "jdk8"), "1.8.0_512", "lib/rt.jar") + t.Setenv("JAVA_HOME", system) + j, ok := FindJDK(t.Context(), selected, t.Logf) + if !ok || j.Home != selected { + t.Fatalf("workspace selection = %+v, want %s", j, selected) + } + if _, ok := FindJDK(t.Context(), filepath.Join(root, "missing"), t.Logf); ok { + t.Fatal("unusable selected JDK silently resolved to a different installation") + } + if j, ok := FindJDK(t.Context(), "", t.Logf); !ok || j.Home != system { + t.Fatalf("automatic selection = %+v, want %s", j, system) + } +} + func TestCompareJavaVersions(t *testing.T) { for _, c := range []struct { a, b string diff --git a/internal/jdk/sources.go b/internal/jdk/sources.go index d830f5f..259a223 100644 --- a/internal/jdk/sources.go +++ b/internal/jdk/sources.go @@ -205,7 +205,12 @@ func (s *Sources) Extract(state, name string) (string, error) { if !s.Has(name) || !validEntry(name) { return "", fmt.Errorf("%s: %w", name, fs.ErrNotExist) } - dst := filepath.Join(s.CacheDir(state), filepath.FromSlash(name)) + ext := path.Ext(name) + tabName := strings.TrimSuffix(path.Base(name), ext) + s.tabLabel() + ext + if len(tabName) > 255 { + tabName = path.Base(name) + } + dst := filepath.Join(s.CacheDir(state), filepath.FromSlash(path.Dir(name)), tabName) if fi, err := os.Stat(dst); err == nil && fi.Mode().IsRegular() && (s.stubs || fi.Size() == s.entries[name].size) { return dst, nil } @@ -250,7 +255,21 @@ func (s *Sources) EntryOf(state, file string) (string, bool) { return "", false } name := filepath.ToSlash(rel) - return name, s.Has(name) + ext := path.Ext(name) + if stem, ok := strings.CutSuffix(strings.TrimSuffix(name, ext), s.tabLabel()); ok && s.Has(stem+ext) { + return stem + ext, true + } + return name, s.Has(name) // also recognize copies opened before tabs were labeled +} + +// Put provenance in the tab title, even when opening a method hundreds of +// lines from the top. Keep the archive text and LSP positions byte-for-byte. +func (s *Sources) tabLabel() string { + version := sanitize(s.version) + if version == "" { + version = "unknown" + } + return " [JDK " + version + " - " + filepath.Base(s.archive) + "]" } // validEntry refuses entry names that would escape the cache directory. diff --git a/internal/jdk/sources_test.go b/internal/jdk/sources_test.go index f7e63c1..394a2d5 100644 --- a/internal/jdk/sources_test.go +++ b/internal/jdk/sources_test.go @@ -58,6 +58,9 @@ func TestSourcesExtractAndMapBack(t *testing.T) { t.Fatal(err) } b, err := os.ReadFile(file) + if got := filepath.Base(file); got != "String [JDK 17.0.18 - src.zip].java" { + t.Errorf("tab name = %q", got) + } if err != nil || string(b) != "package java.lang;\npublic final class String {}\n" { t.Fatalf("extracted %q, %v", b, err) } diff --git a/internal/lsp/server.go b/internal/lsp/server.go index 0f7aa01..4d8f985 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -26,7 +26,7 @@ type Options struct { // State is the writable directory for extracted JDK sources. State string // FindJDK locates the JDK whose sources are used; nil disables them. - FindJDK func(context.Context) (jdk.JDK, bool) + FindJDK func(context.Context, string) (jdk.JDK, bool) // Dependencies enables navigation into dependency jars (see // workspace.Options.Dependencies). Dependencies bool @@ -317,7 +317,9 @@ func (s *Server) newWorkspace(root string) *workspace.Workspace { o := s.opt.Workspace o.Root = root o.State = s.opt.State - o.FindJDK = s.opt.FindJDK + if s.opt.FindJDK != nil { + o.FindJDK = func(ctx context.Context) (jdk.JDK, bool) { return s.opt.FindJDK(ctx, root) } + } o.Dependencies = s.opt.Dependencies o.MavenRepo = s.opt.MavenRepo if o.Logf == nil { diff --git a/internal/workspace/workspace_test.go b/internal/workspace/workspace_test.go index 86662dd..cbd3102 100644 --- a/internal/workspace/workspace_test.go +++ b/internal/workspace/workspace_test.go @@ -297,7 +297,7 @@ public final class String implements CharSequence { if err != nil || !ok { t.Fatalf("String = %v %v", ok, err) } - if !strings.Contains(filepath.ToSlash(tgt.File), "/jdk-sources/jdk-17.0.18-") || !strings.HasSuffix(filepath.ToSlash(tgt.File), "java.base/java/lang/String.java") || tgt.Line != 2 { + if !strings.Contains(filepath.ToSlash(tgt.File), "/jdk-sources/jdk-17.0.18-") || !strings.HasSuffix(filepath.ToSlash(tgt.File), "java.base/java/lang/String [JDK 17.0.18 - src.zip].java") || tgt.Line != 2 { t.Fatalf("String target = %+v", tgt) } // The copy is a JDK source, and navigation continues inside it. @@ -307,7 +307,7 @@ public final class String implements CharSequence { } lib, _ := os.ReadFile(tgt.File) next, ok, err := w.Definition(ctx(t), ldoc, lib, at(t, string(lib), "CharSequence", 0, 1)) - if err != nil || !ok || !strings.HasSuffix(filepath.ToSlash(next.File), "java/lang/CharSequence.java") { + if err != nil || !ok || !strings.HasSuffix(filepath.ToSlash(next.File), "java/lang/CharSequence [JDK 17.0.18 - src.zip].java") { t.Errorf("CharSequence from the copy = %+v %v %v", next, ok, err) } // A local in a JDK source has its usages in that file. @@ -319,7 +319,7 @@ public final class String implements CharSequence { src := "package com.acme.service;\nclass H { int f(UserService s) { return s.hashCode(); } }\n" hdoc := w.DocOf(filepath.Join(root, "src/main/java/com/acme/service/H.java")) h, ok, err := w.Definition(ctx(t), hdoc, []byte(src), at(t, src, "hashCode", 0, 1)) - if err != nil || !ok || !strings.HasSuffix(filepath.ToSlash(h.File), "java/lang/Object.java") { + if err != nil || !ok || !strings.HasSuffix(filepath.ToSlash(h.File), "java/lang/Object [JDK 17.0.18 - src.zip].java") { t.Errorf("hashCode = %+v %v %v", h, ok, err) } } diff --git a/io.github.lithe-idea.java-navigation/plugin.json b/io.github.lithe-idea.java-navigation/plugin.json index 7e9b109..a481175 100644 --- a/io.github.lithe-idea.java-navigation/plugin.json +++ b/io.github.lithe-idea.java-navigation/plugin.json @@ -4,6 +4,7 @@ "displayName": "Java Support Lite", "version": "0.2.1", "pluginAPIVersion": 0, + "requiresTools": ["java"], "requires": { "backend": 0, "languageServers": 0, @@ -47,16 +48,10 @@ "languageID": "java", "languageIdentifier": "java", "launch": { - "kind": "packaged", - "path": "bin/java-navigation" + "kind": "backend", + "function": "javaNavigation.resolveLaunch" }, - "arguments": [ - "--state-dir", - "${stateDir}" - ], - "validationArguments": [ - "--version" - ], + "remote": "unsupported", "requestMethods": [ "textDocument/implementation", "javaNavigation/superDeclarations", diff --git a/scripts/package.mjs b/scripts/package.mjs index afd8bb7..e55c0fa 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -38,8 +38,8 @@ if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(manifest.version)) problems.push(`version $ if (manifest.vendor?.signatureRequirement !== "none") problems.push('vendor.signatureRequirement must be "none"'); if (manifest.id === "dev.lithe" || manifest.id.startsWith("dev.lithe.")) problems.push("dev.lithe.* is reserved for official plugins"); const servers = manifest.languageServers ?? []; -if (servers.length !== 1 || servers[0].launch?.kind !== "packaged" || servers[0].launch?.path !== `bin/${BINARY}`) { - problems.push(`plugin.json must declare one packaged language server at bin/${BINARY}`); +if (servers.length !== 1 || servers[0].launch?.kind !== "backend" || servers[0].launch?.function !== "javaNavigation.resolveLaunch") { + problems.push("plugin.json must start the language server with javaNavigation.resolveLaunch"); } const backend = manifest.backend; if (backend?.launch?.kind !== "packaged" || backend?.launch?.path !== `bin/${BINARY}`) { @@ -89,7 +89,6 @@ for (const target of targets) { ); chmodSync(join(pkg, "bin", exe), 0o755); const platformManifest = structuredClone(manifest); - platformManifest.languageServers[0].launch.path = `bin/${exe}`; platformManifest.backend.launch.path = `bin/${exe}`; writeFileSync(join(pkg, "plugin.json"), `${JSON.stringify(platformManifest, null, 2)}\n`); for (const file of INCLUDED) { diff --git a/scripts/package/linux.test.mjs b/scripts/package/linux.test.mjs index 18a39b0..c79557f 100644 --- a/scripts/package/linux.test.mjs +++ b/scripts/package/linux.test.mjs @@ -14,7 +14,8 @@ for (const [arch,machine] of [['arm64',183],['x64',62]]) { const archive=resolve(`dist/java-navigation-${version}-linux-${arch}.zip`); const manifest=JSON.parse(read(archive,'plugin.json')); assert.equal(manifest.version,version); - const path=manifest.languageServers[0].launch.path; + assert.equal(manifest.languageServers[0].launch.function,'javaNavigation.resolveLaunch'); + const path=manifest.backend.launch.path; assert.equal(path,'bin/java-navigation'); const binary=read(archive,path); assert.deepEqual([...binary.subarray(0,6)],[127,69,76,70,2,1]); From bc42f8a03a0918a2b5373af2b7d44f87458d66f2 Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Fri, 27 Nov 2026 13:08:08 +0000 Subject: [PATCH 3/4] test(package): exercise backend-resolved LSP startup from the archive Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 2 +- scripts/package/smoke-linux.mjs | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d59a372..ed2b889 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ JSF 依赖没下载过,这轮 OpenCms 基准早于 Gradle 缓存支持)、 例如 `list.get(0).getName()` 里的 `getName`、`users.stream().map(u -> u.getName())` 里的 `getName`; 按泛型实参才能区分的重载也会取第一个。 - **`.jsp` 文件里不能跳转**:插件只处理 `.java` 文件,JSP 里的 `<% %>` 脚本、``、EL 表达式和标签库都不跳。 -- **只认一个 JDK**:用的是上面顺序找到的 JDK,不一定是项目编译用的版本。 +- **每个工作区使用一套 JDK**:宿主未提供 Java 安装时,插件无法区分“没有选择”和“宿主无法解析选择”,会按上面的规则查找。修改项目 JDK 或补装源码后,重新启动语言服务器以采用新配置。 - **引用不含重写和实现**:查找方法的引用不包括子类重写的方法和通过接口调用到的其他声明。 - **和 Java Support 二选一**:两个插件都为 Java 提供语言服务器,Lithe 同一时间只让一个已启用的插件服务一门语言。 启用或安装其中一个,另一个会被自动停用,Lithe 会提示停用了哪个(需要包含 diff --git a/scripts/package/smoke-linux.mjs b/scripts/package/smoke-linux.mjs index 50e7c6f..3c1a87b 100644 --- a/scripts/package/smoke-linux.mjs +++ b/scripts/package/smoke-linux.mjs @@ -8,13 +8,25 @@ import {join,resolve} from 'node:path'; import {pathToFileURL} from 'node:url'; import {Client} from './lsp-client.mjs'; assert.equal(process.platform,'linux'); -const archive=resolve(process.argv[2]);const stage=mkdtempSync(join(tmpdir(),'lithe-lite-linux-'));let server; +const archive=resolve(process.argv[2]);const stage=mkdtempSync(join(tmpdir(),'lithe-lite-linux-'));let server,backend; const inventory=root=>{const entries=[];const walk=path=>{const stat=statSync(path);entries.push([path,stat.mode,stat.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(stat.isDirectory())for(const name of readdirSync(path).sort())walk(join(path,name));};walk(root);return entries;}; try{ execFileSync('unzip',['-q',archive,'-d',stage],{timeout:15000}); const pkg=join(stage,'io.github.lithe-idea.java-navigation');const before=inventory(pkg); const workspace=join(stage,'workspace');mkdirSync(workspace);const file=join(workspace,'Hello.java');writeFileSync(file,'class Hello { String value; }\n'); - server=new Client(join(pkg,'bin/java-navigation')); + const manifest=JSON.parse(readFileSync(join(pkg,'plugin.json'),'utf8')); + backend=new Client(join(pkg,manifest.backend.launch.path),manifest.backend.arguments); + await backend.request('initialize',{rootUri:pathToFileURL(workspace).href,capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}}); + backend.notify('initialized',{}); + const state=join(stage,'state'); + const launch=await backend.request('lithe/function/invoke',{ + operationID:'package-smoke',functionID:manifest.languageServers[0].launch.function, + context:{contextID:'workspace',generation:1}, + params:{serverID:'java',stateDirectory:state,platform:{os:process.platform}}, + }); + assert.equal(launch.executable.kind,'packaged'); + assert.deepEqual(launch.arguments,['--state-dir',state]); + server=new Client(join(pkg,launch.executable.path),launch.arguments); const initialized=await server.request('initialize',{processId:null,rootUri:pathToFileURL(workspace).href,capabilities:{textDocument:{documentSymbol:{hierarchicalDocumentSymbolSupport:true}}}}); assert.equal(initialized.capabilities.definitionProvider,true);server.notify('initialized',{}); server.notify('textDocument/didOpen',{textDocument:{uri:pathToFileURL(file).href,languageId:'java',version:1,text:readFileSync(file,'utf8')}}); @@ -22,5 +34,5 @@ try{ assert.ok(symbols.some(symbol=>symbol.name==='Hello')); await server.request('shutdown',null);server.notify('exit',null);await server.close();server=undefined; assert.deepEqual(inventory(pkg),before); - console.log(`Verified Linux ${process.arch}: installed LSP initialize, document symbols, shutdown and immutable package`); -}finally{try{if(server)await server.close();}finally{rmSync(stage,{recursive:true,force:true});}} + console.log(`Verified Linux ${process.arch}: backend launch without a Java tool, LSP initialize, document symbols, shutdown and immutable package`); +}finally{try{await Promise.all([server?.close(),backend?.close()]);}finally{rmSync(stage,{recursive:true,force:true});}} From 4acf2ee041e0f4e8e1ac43c9c614c64893d4d6c6 Mon Sep 17 00:00:00 2001 From: Li <2188718831@qq.com> Date: Fri, 27 Nov 2026 13:10:29 +0000 Subject: [PATCH 4/4] fix(maven): ignore a mismatched local parent when selecting javac Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/deps/deps_test.go | 21 +++++++++------------ internal/deps/maven.go | 8 ++++++++ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/internal/deps/deps_test.go b/internal/deps/deps_test.go index a4f0697..bc47a51 100644 --- a/internal/deps/deps_test.go +++ b/internal/deps/deps_test.go @@ -370,24 +370,21 @@ func TestLocalRepositoryHonoursSettings(t *testing.T) { func TestMavenCompilerExecutable(t *testing.T) { root := t.TempDir() child := filepath.Join(root, "module") - if err := os.Mkdir(child, 0o755); err != nil { - t.Fatal(err) - } exe := filepath.Join(root, "jdk 8", "bin", "javac") t.Setenv("TEST_MAVEN_JAVAC", exe) - parent := `parentmaven-compiler-plugintrue${compiler}` - module := `parent${env.TEST_MAVEN_JAVAC}` - for dir, pom := range map[string]string{root: parent, child: module} { - if err := os.WriteFile(filepath.Join(dir, "pom.xml"), []byte(pom), 0o644); err != nil { - t.Fatal(err) - } - } + parent := `exampleparent1maven-compiler-plugintrue${compiler}` + module := `exampleparent1${env.TEST_MAVEN_JAVAC}` + writeFile(t, filepath.Join(root, "pom.xml"), parent) + pom := filepath.Join(child, "pom.xml") + writeFile(t, pom, module) if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != exe { t.Fatalf("got %q, want %q", got, exe) } - if err := os.WriteFile(filepath.Join(child, "pom.xml"), []byte(`8${env.TEST_MAVEN_JAVAC}`), 0o644); err != nil { - t.Fatal(err) + writeFile(t, pom, strings.Replace(module, "1", "2", 1)) + if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != "" { + t.Fatalf("unrelated local parent selected %q", got) } + writeFile(t, pom, `8${env.TEST_MAVEN_JAVAC}`) if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != "" { t.Fatalf("unforked compiler selected %q", got) } diff --git a/internal/deps/maven.go b/internal/deps/maven.go index 23a182f..ea581ee 100644 --- a/internal/deps/maven.go +++ b/internal/deps/maven.go @@ -3,6 +3,7 @@ package deps import ( "bufio" "bytes" + "cmp" "context" "encoding/xml" "fmt" @@ -149,6 +150,13 @@ func MavenCompilerExecutable(ctx context.Context, root string, logf func(string, if pom == "" { break } + // A relative path can point at another version of the parent checked + // out alongside this module. Maven won't inherit its compiler. + parent := m.readPOM(pom) + if cmp.Or(parent.GroupID, parent.Parent.GroupID) != p.Parent.GroupID || + cmp.Or(parent.Version, parent.Parent.Version) != p.Parent.Version { + break + } } if fork == "" { fork = props["maven.compiler.fork"]