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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
| 跳转到定义 | 类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链、调用参数个数和实参类型解析,支持调用链 `a.b().c` 和 `Foo.<T>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 |
Expand Down Expand Up @@ -62,9 +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`)→ 常见安装目录
(含 IntelliJ 的 `~/.jdks`、SDKMAN!)的顺序找第一个带 `src.zip` 的 JDK。只预先列出 zip 目录,某个类第一次被查到时才解析。
跳进 JDK 时把那一个源码文件解压成只读副本,放在 Lithe 为插件分配的状态目录(`${stateDir}`)里,卸载插件时一起删除;
- 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`。只预先列出归档目录,某个类第一次被查到时才解析。
跳转后的编辑器标签标明版本与来源,如 `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`。
Expand Down Expand Up @@ -140,7 +144,7 @@ JSF 依赖没下载过,这轮 OpenCms 基准早于 Gradle 缓存支持)、
例如 `list.get(0).getName()` 里的 `getName`、`users.stream().map(u -> u.getName())` 里的 `getName`;
按泛型实参才能区分的重载也会取第一个。
- **`.jsp` 文件里不能跳转**:插件只处理 `.java` 文件,JSP 里的 `<% %>` 脚本、`<jsp:useBean>`、EL 表达式和标签库都不跳。
- **只认一个 JDK**:用的是上面顺序找到的 JDK,不一定是项目编译用的版本。
- **每个工作区使用一套 JDK**:宿主未提供 Java 安装时,插件无法区分“没有选择”和“宿主无法解析选择”,会按上面的规则查找。修改项目 JDK 或补装源码后,重新启动语言服务器以采用新配置。
- **引用不含重写和实现**:查找方法的引用不包括子类重写的方法和通过接口调用到的其他声明。
- **和 Java Support 二选一**:两个插件都为 Java 提供语言服务器,Lithe 同一时间只让一个已启用的插件服务一门语言。
启用或安装其中一个,另一个会被自动停用,Lithe 会提示停用了哪个(需要包含
Expand All @@ -160,7 +164,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` 后端均写这个路径)、
Expand Down
14 changes: 13 additions & 1 deletion cmd/java-navigation/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)")
Expand All @@ -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
Expand Down
39 changes: 39 additions & 0 deletions internal/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net/url"
"path"
"path/filepath"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions internal/backend/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
24 changes: 24 additions & 0 deletions internal/deps/deps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,3 +365,27 @@ 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")
exe := filepath.Join(root, "jdk 8", "bin", "javac")
t.Setenv("TEST_MAVEN_JAVAC", exe)
parent := `<project><groupId>example</groupId><artifactId>parent</artifactId><version>1</version><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><configuration><fork>true</fork><executable>${compiler}</executable></configuration></plugin></plugins></build></project>`
module := `<project><parent><groupId>example</groupId><artifactId>parent</artifactId><version>1</version></parent><properties><compiler>${env.TEST_MAVEN_JAVAC}</compiler></properties></project>`
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)
}
writeFile(t, pom, strings.Replace(module, "<version>1", "<version>2", 1))
if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != "" {
t.Fatalf("unrelated local parent selected %q", got)
}
writeFile(t, pom, `<project><properties><maven.compiler.release>8</maven.compiler.release><maven.compiler.executable>${env.TEST_MAVEN_JAVAC}</maven.compiler.executable></properties></project>`)
if got := MavenCompilerExecutable(t.Context(), child, t.Logf); got != "" {
t.Fatalf("unforked compiler selected %q", got)
}
}
16 changes: 11 additions & 5 deletions internal/deps/jars.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
103 changes: 93 additions & 10 deletions internal/deps/maven.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package deps
import (
"bufio"
"bytes"
"cmp"
"context"
"encoding/xml"
"fmt"
Expand Down Expand Up @@ -72,6 +73,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
Expand Down Expand Up @@ -105,6 +113,71 @@ 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
}
// 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"]
}
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 == "" {
Expand Down Expand Up @@ -408,17 +481,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)
}
}
Expand All @@ -432,6 +497,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)
Expand Down
Loading
Loading