Skip to content

Commit 7537b2c

Browse files
1lckclaude
andauthored
fix: match JDT LS on same-arity overloads, type arguments and varargs (#2)
Comparing definition targets with JDT LS on Nacos (3 x 1500 positions) found two wrong jumps, both overloads with the same parameter count (new AccessException("...") went to AccessException(int)), and a few positions JDT LS resolves that this index missed. - Overloads with the same arity are scored against what the arguments are known to be: literals, casts, new expressions, declared types of locals and fields, and the expression types the resolver follows. As in Java, a fixed-arity candidate beats one needing varargs. - Explicit type arguments (RestResult.<T>builder()) no longer hide the qualifier. - Qualified annotations (@Outer.Inner(...)) resolve to the nested type. - Varargs parameters (String... keys) are found as locals. Parameter types are stored as one interned string per member; an A/B run on ruoyi-vue-pro shows no memory or latency change. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8e21678 commit 7537b2c

8 files changed

Lines changed: 686 additions & 29 deletions

File tree

‎README.md‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
| 功能 | 说明 |
1818
| --- | --- |
19-
| 跳转到定义 | 类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链和调用参数个数解析,支持调用链 `a.b().c` |
19+
| 跳转到定义 | 类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链、调用参数个数和实参类型解析,支持调用链 `a.b().c` 和 `Foo.<T>bar()` |
2020
| Lombok | `@Data`/`@Getter`/`@Setter` 生成的访问器跳到字段,`@Builder`、`@Slf4j`、构造器注解跳到注解本身(与 JDT LS 一致) |
2121
| 跳进 JDK | 项目里找不到的名字到本机 JDK 的 `src.zip` 里找,`String`、`List`、`hashCode()` 等都能跳,并能在 JDK 源码里继续跳 |
2222
| 查找引用 | 只列出能跳回这个声明的出现,所以列表和在任一行上跳转的结果一致;`package`/`import` 不算引用 |
@@ -47,6 +47,30 @@
4747

4848
查找引用 20 次,p50 约 56 ms,最慢 0.13 s。
4949

50+
### 和 JDT LS 对比跳转目标
51+
52+
在 Nacos 上用同样的取样方式取 3 组、每组 1500 个位置,同时问 JDT LS(Maven 导入完成后)和本插件,比较跳到的文件和行
53+
(跳进 JDK 的按类比较,因为两边的 JDK 版本和源码不一定相同):
54+
55+
| 结果 | 种子 2 | 种子 7 | 种子 11 |
56+
| --- | --- | --- | --- |
57+
| 两边跳到同一处(项目内) | 1099 | 1071 | 1086 |
58+
| 两边跳到 JDK 的同一个类 | 326 | 337 | 327 |
59+
| 两边都没有结果 | 8 | 14 | 17 |
60+
| 只有 JDT LS 能跳:依赖库 | 59 | 72 | 64 |
61+
| 只有 JDT LS 能跳:项目内或 JDK | 8 | 3 | 5 |
62+
| 只有本插件能跳 | 0 | 2 | 0 |
63+
| 两边都跳了但不一样 | 0 | 1 | 1 |
64+
65+
“两边都跳了但不一样”的两处都不是跳错:`org.xml.sax.Attributes` 本身就在 JDK 里(JDT LS 把它当成依赖库),
66+
`Properties.putAll` 是 JDK 9 起才有的重写(这个模块用 JDK 8 编译,JDT LS 跳到 `Hashtable.putAll`,本插件读的是 JDK 17)。
67+
只有 JDT LS 能跳的项目内位置是 `target/generated-sources` 里 protobuf 生成的类、泛型推断(`list.get(i).getName()`)
68+
和依赖库类型继承来的方法(`e.getMessage()`,`e` 的类型来自 Spring)。
69+
70+
对比中发现并已修复的问题:参数个数相同的重载取了第一个(`new AccessException("...")` 跳到了 `AccessException(int)`),
71+
显式类型实参调用 `RestResult.<T>builder()`、限定名注解 `@ExtractorManager.Extractor(...)` 和可变参数参数
72+
`String... keys` 跳不了。
73+
5074
宿主联调:用 Lithe 桌面端固定的 Rust Core(`47c9859`)校验 `plugin.json`、规划 `packaged` 启动、经 Core 启动语言服务器,
5175
会话进入 `ready` 并声明 `definition`、`references`、`documentSymbols`,三种请求都返回正确位置;跳进 JDK 时只在 `${stateDir}`
5276
写入解压副本,插件包文件的 SHA-256 前后一致。ruoyi-vue-pro 跳不了的几乎全是依赖库的注解和它们的属性:
@@ -57,7 +81,8 @@ Swagger 的 `@Schema(description, example, requiredMode)`、Lombok 的 `@Data`
5781

5882
- **不读依赖库**:Spring、MyBatis、Lombok、Swagger 等依赖里的声明找不到(返回“没有定义”,不会跳错)。
5983
计划:从 Maven/Gradle 插件取 classpath,按需读取 `sources.jar`,没有源码时显示只有签名的存根。
60-
- **没有类型推断**:重载只按参数个数选择;lambda 参数的类型和泛型替换后的返回类型推不出来,
84+
- **没有类型推断**:重载先按参数个数选,个数相同时按实参里写得出来的类型挑(字面量、强转、`new` 表达式、
85+
变量和字段声明的类型、能跟下去的调用链),都看不出时取第一个;lambda 参数的类型和泛型替换后的返回类型推不出来,
6186
例如 `list.get(0).getName()` 里的 `getName`、`users.stream().map(u -> u.getName())` 里的 `getName`;
6287
以字面量为限定符的调用(`"".trim()`)也推不出类型。
6388
- **只认一个 JDK**:用的是上面顺序找到的 JDK,不一定是项目编译用的版本。

‎docs/releases/v0.0.1.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
0.0.1 是首个版本:不依赖 JDT LS 的轻量 Java 跳转,按插件契约 v0 编写。
22

33
功能:
4-
- 跳转到定义:类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链和参数个数解析,支持调用链。
4+
- 跳转到定义:类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链、参数个数和实参类型解析,支持调用链和 `Foo.<T>bar()`。
55
- Lombok:访问器跳到字段,`@Builder`、`@Slf4j` 和构造器注解生成的成员跳到注解。
66
- 跳进本机 JDK 的 `src.zip`,并能在 JDK 源码里继续跳;JDK 源码以只读副本打开,放在插件状态目录里。
77
- 查找引用:只列出能跳回该声明的出现。
88
- 文档结构(大纲)。
9+
- 在 Nacos 上和 JDT LS 对比 4500 个位置,两边都有结果时目标一致(两处差异来自 JDK 版本和 JDK 自带的 `org.xml.sax`)。
910
- 打开的文件按编辑器里未保存的内容索引。
1011

1112
平台:macOS(Apple Silicon、Intel)、Windows(x64、ARM64),每个平台一个 ZIP。

‎internal/codenav/UPSTREAM.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,21 @@
99

1010
## 同步规则
1111

12-
- 除下面列出的文件,本目录的 `.go` 文件与上游**逐字节一致**,不要在这里直接改;需要改解析规则时,
12+
- 除下面列出的文件和改动,本目录的 `.go` 文件与上游**逐字节一致**,不要在这里直接改;需要改解析规则时,
1313
先在 Viff 修(先补一条能失败的测试),再整目录拷回来。
1414
- Lithe 新增的代码放在单独的文件里,文件开头注明“This file is a Lithe addition”:
1515
- `symbols.go`:文档结构(`textDocument/documentSymbol`)。
16+
- `overloads.go`:参数个数相同的重载按实参类型挑选。来自和 JDT LS 在 Nacos 上的对比:唯一跳错的
17+
两处都是同参数个数的重载(`new AccessException("...")` 跳到了 `AccessException(int)`)。
18+
- `qualified.go`:显式类型实参调用 `Foo.<T>bar()` 和限定名注解 `@Outer.Inner(...)`。
19+
- `jdtls_cases_test.go`:上面几条以及可变参数参数的测试,都来自同一次对比。
20+
- Viff 还没有发布 codenav,这些只能先在这里改。它们对上游文件的改动只有下面几处,
21+
上游发布后把这些改动连同上面的新文件提给 Viff,再恢复逐字节一致:
22+
- `parse.go`:`Member` 加 `Params` 字段,解析成员时赋值 `m.Params = p.paramTypes(j, pe)`。
23+
- `resolve.go`:`findMethod`、`pickCtor`、`methodInScope` 的参数个数换成 `call`(参数个数加左括号位置),
24+
参数个数相同的候选交给 `bestOverload`;`resolveAt` 和 `typeOfExpr` 的限定符用 `qualifierDot` 找,
25+
跳过显式类型实参;限定名注解在 `resolveAt` 里按嵌套类型解析(`annotationName`);`findLocal` 认出
26+
`String... keys` 这样的可变参数参数(原来类型在 `...` 前面时找不到)。
1627
- 同步后运行 `go test ./...`。
1728

1829
`internal/jdk/find.go` 改编自 Viff 的 `internal/platform/jdk.go`(去掉了 Viff 的进程辅助函数,
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
package codenav
2+
3+
// This file is a Lithe addition: cases found by comparing against JDT LS on
4+
// Nacos where this index answered differently or not at all.
5+
6+
import (
7+
"strings"
8+
"testing"
9+
)
10+
11+
var overloadProject = map[string]string{
12+
"src/o/Error.java": `package o;
13+
14+
public class Error {
15+
public Error() {}
16+
public Error(int code) {}
17+
public Error(String msg) {}
18+
public Error(Error cause) {}
19+
}
20+
`,
21+
"src/o/Cause.java": `package o;
22+
23+
public class Cause extends Error {}
24+
`,
25+
"src/o/Cache.java": `package o;
26+
27+
import java.util.Set;
28+
29+
public class Cache {
30+
public void init(String packageName) {}
31+
public void init(Set<Class<?>> classes) {}
32+
public void init(long ttl, boolean lazy) {}
33+
public void init(Object key, boolean lazy) {}
34+
public void put(char c) {}
35+
public void put(double d) {}
36+
public void put(Cache other) {}
37+
public static <T> Cache builder() { return null; }
38+
public static void check(boolean ok, Object message) {}
39+
public static void check(boolean ok, String template, Object... args) {}
40+
public Cache self() { return this; }
41+
}
42+
`,
43+
"src/o/Use.java": `package o;
44+
45+
import java.util.HashSet;
46+
import java.util.Set;
47+
48+
class Use {
49+
void run(Set<Class<?>> classes, Cache cache) {
50+
Error a = new Error("user not found!");
51+
Error b = new Error(404);
52+
Error c = new Error(new Cause());
53+
Error d = new Error("a" + 1);
54+
cache.init(classes);
55+
cache.init("com.acme");
56+
cache.init(new HashSet<Class<?>>());
57+
cache.init(5L, true);
58+
cache.init(cache, false);
59+
cache.put('x');
60+
cache.put(1.5);
61+
cache.put(-2);
62+
cache.put(cache);
63+
cache.put((Cache) null);
64+
Cache.<String>builder().self();
65+
Cache.check(classes.isEmpty(), "no classes");
66+
Cache.check(true, "%s missing", "x");
67+
}
68+
}
69+
`,
70+
}
71+
72+
func TestOverloadsWithTheSameArity(t *testing.T) {
73+
ix := NewIndex()
74+
for p, src := range overloadProject {
75+
ix.Put(ParseFile(p, []byte(src)))
76+
}
77+
const use = "src/o/Use.java"
78+
at := func(path, needle string) Location {
79+
src := overloadProject[path]
80+
off := strings.Index(src, needle)
81+
if off < 0 {
82+
t.Fatalf("%q not found in %s", needle, path)
83+
}
84+
return Location{Path: path, Line: strings.Count(src[:off], "\n"), Column: off - (strings.LastIndexByte(src[:off], '\n') + 1)}
85+
}
86+
const errT, cache = "src/o/Error.java", "src/o/Cache.java"
87+
cases := []struct {
88+
name, click string
89+
skip int
90+
want Location
91+
}{
92+
{"string literal picks the String constructor", `Error("user`, 0, at(errT, "Error(String msg)")},
93+
{"int literal picks the int constructor", `Error(404)`, 0, at(errT, "Error(int code)")},
94+
{"subtype argument picks the supertype parameter", `Error(new Cause())`, 0, at(errT, "Error(Error cause)")},
95+
{"string concatenation is a String", `Error("a" + 1)`, 0, at(errT, "Error(String msg)")},
96+
{"typed parameter picks the matching overload", `init(classes)`, 0, at(cache, "init(Set")},
97+
{"string literal picks String over Set", `init("com`, 0, at(cache, "init(String")},
98+
{"new expression type", `init(new HashSet`, 0, at(cache, "init(Set")},
99+
{"long literal", `init(5L`, 0, at(cache, "init(long")},
100+
{"reference argument goes to Object", `init(cache, false)`, 0, at(cache, "init(Object")},
101+
{"char literal", `put('x')`, 0, at(cache, "put(char")},
102+
{"double literal", `put(1.5)`, 0, at(cache, "put(double")},
103+
{"negative int widens to double, not char", `put(-2)`, 0, at(cache, "put(double")},
104+
{"project type", `put(cache)`, 0, at(cache, "put(Cache")},
105+
{"cast", `put((Cache)`, 0, at(cache, "put(Cache")},
106+
{"explicit type arguments", `builder()`, 0, at(cache, "builder()")},
107+
{"a fixed-arity overload beats varargs", `check(classes`, 0, at(cache, "check(boolean ok, Object")},
108+
{"varargs when the fixed one cannot take the arguments", `check(true`, 0, at(cache, "check(boolean ok, String")},
109+
{"call after explicit type arguments", `self();`, 0, at(cache, "self()")},
110+
}
111+
src := []byte(overloadProject[use])
112+
for _, c := range cases {
113+
off := strings.Index(string(src), c.click)
114+
if off < 0 {
115+
t.Fatalf("%s: %q not found", c.name, c.click)
116+
}
117+
got, ok := ix.Resolve(use, src, off+c.skip)
118+
if !ok {
119+
t.Errorf("%s: no declaration, want %v", c.name, c.want)
120+
continue
121+
}
122+
if got.Path != c.want.Path || got.Line != c.want.Line || got.Column != c.want.Column {
123+
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
124+
}
125+
}
126+
}
127+
128+
var jdtlsCaseProject = map[string]string{
129+
"src/q/Manager.java": `package q;
130+
131+
public class Manager {
132+
public @interface Extractor {
133+
Class<?> rpc();
134+
}
135+
}
136+
`,
137+
"src/q/Handler.java": `package q;
138+
139+
class Handler {
140+
@Manager.Extractor(rpc = Handler.class)
141+
void handle() {}
142+
143+
static void check(Class<?> raw, final Type... typeArguments) {
144+
if (typeArguments.length != 0) {
145+
return;
146+
}
147+
}
148+
149+
byte[] key(String... keys) { return keys[0].getBytes(); }
150+
}
151+
`,
152+
}
153+
154+
func TestJDTLSCases(t *testing.T) {
155+
ix := NewIndex()
156+
for p, src := range jdtlsCaseProject {
157+
ix.Put(ParseFile(p, []byte(src)))
158+
}
159+
const h = "src/q/Handler.java"
160+
at := func(path, needle string, nth int) Location {
161+
src := jdtlsCaseProject[path]
162+
off := offsetOf(t, src, needle, nth, 0)
163+
return Location{Path: path, Line: strings.Count(src[:off], "\n"), Column: off - (strings.LastIndexByte(src[:off], '\n') + 1)}
164+
}
165+
cases := []struct {
166+
name, click string
167+
nth int
168+
want Location
169+
}{
170+
{"qualified annotation", "Extractor(", 0, at("src/q/Manager.java", "Extractor {", 0)},
171+
{"attribute of a qualified annotation", "rpc =", 0, at("src/q/Manager.java", "rpc()", 0)},
172+
{"varargs parameter declaration", "typeArguments)", 0, at(h, "typeArguments)", 0)},
173+
{"varargs parameter use", "typeArguments.length", 0, at(h, "typeArguments)", 0)},
174+
{"varargs parameter after a plain type", "keys)", 0, at(h, "keys)", 0)},
175+
{"varargs parameter indexed", "keys[0]", 0, at(h, "keys)", 0)},
176+
}
177+
src := []byte(jdtlsCaseProject[h])
178+
for _, c := range cases {
179+
off := offsetOf(t, string(src), c.click, c.nth, 0)
180+
got, ok := ix.Resolve(h, src, off)
181+
if !ok {
182+
t.Errorf("%s: no declaration, want %v", c.name, c.want)
183+
continue
184+
}
185+
if got.Path != c.want.Path || got.Line != c.want.Line || got.Column != c.want.Column {
186+
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
187+
}
188+
}
189+
}

0 commit comments

Comments
 (0)