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
4 changes: 4 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Test data is compared byte for byte (golden stubs) or is binary (jars):
# never convert its line endings on checkout.
internal/deps/testdata/** -text

# Keep vendored SDK files byte-identical to the checksums in sdk.lock.json.
internal/lithesdk/lithe/*.go text eol=lf
vendor/LICENSE text eol=lf
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
| Lombok | `@Data`/`@Getter`/`@Setter` 生成的访问器跳到字段,`@Builder`、`@Slf4j`、构造器注解跳到注解本身(与 JDT LS 一致) |
| 跳进 JDK | 项目里找不到的名字到本机 JDK 的 `src.zip` 里找,`String`、`List`、`hashCode()` 等都能跳,并能在 JDK 源码里继续跳 |
| 跳进依赖库 | Maven 项目的依赖(含传递依赖)从本地仓库读:下载过 `-sources.jar` 的打开源码,否则打开从 `.class` 生成的签名存根(类、成员类、字段、构造器、方法,参数名取自调试信息),并能在里面继续跳;`@Schema(description = ...)`、`log.info(...)`、`StrUtil.isEmpty(...)` 都能跳 |
| 老项目的 jar | 没有 Maven 的 Ant、Eclipse、MyEclipse 项目,读 `.classpath` 里列出的 jar(含 `M2_REPO` 变量和 `sourcepath`),以及 `lib/`、`libs/`、`WEB-INF/lib` 里的 jar |
| 老项目的 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 |
| 生成代码 | 模块的 `target/generated-sources`(protobuf、注解处理器)和 Gradle 的 `build/generated` 也进索引,即使被 `.gitignore` 忽略 |
| 查找引用 | 只列出能跳回这个声明的出现,所以列表和在任一行上跳转的结果一致;`package`/`import` 不算引用 |
Expand All @@ -49,6 +49,9 @@
`WEB-INF/lib`、`WebContent/WEB-INF/lib`、`WebRoot/WEB-INF/lib` 等即使被 `.gitignore` 忽略也会读。源码取
`.classpath` 的 `sourcepath`,或旁边的 `-sources.jar`、`-src.zip`;源码包不是按包名放的(比如整个源码树打的 zip)就不用,改用存根。
这些 jar 只读,不会被修改。
- Ant 的 `<path>` 和 `<classpath>` 还可以通过 `<pathelement location="ext/x.jar"/>` 单独列出 jar,或通过
`<fileset dir="${thirdparty.dir}" includes="**/*.jar"/>` 选择工作区内的 jar。支持 include/exclude 模式、
项目顶层的 `<property name="…" value="…"/>` 和 `location`,以及显式加载的同目录 `build.properties` 中的简单键值对。
- Eclipse 容器(`kind="con"`):服务器运行时容器按运行时名字判断包名(Tomcat 10+、Jetty 11+、WildFly 27+、
GlassFish/Payara 6+、TomEE 9+ 用 `jakarta.servlet`,更早的用 `javax.servlet`),先找本机装的服务器
(`CATALINA_HOME`/`CATALINA_BASE`、Homebrew、`/opt`、`/usr/share`、Windows 的 `Program Files`、`~/apache-tomcat-*`)
Expand Down Expand Up @@ -115,8 +118,8 @@ JSF 依赖没下载过,OpenCms 的 Gradle 依赖读不了)、数组的 `.len

## 限制

- **依赖库只读 Maven 和工作区里的 jar**:Gradle 项目的依赖还读不了(Gradle 的生成代码可以);Ant 的
`build.xml` 里写在 `lib` 之外目录的 classpath 也读不了。只用本地仓库里已有的 jar,
- **依赖库只读 Maven 和工作区里的 jar**:Gradle 项目的依赖还读不了(Gradle 的生成代码可以);Ant 目标执行时
才能得到的类路径也会跳过。只用本地仓库里已有的 jar,
从没构建过、依赖还没下载的项目跳不进依赖库。没有 `-sources.jar` 时打开签名存根,没有方法体和注释;
编译时没带调试信息的接口和抽象方法,参数名是 `arg0`、`arg1`。
- **没有泛型推断**:重载先按参数个数选,个数相同时按实参里写得出来的类型挑(字面量、强转、`new` 表达式、
Expand Down
8 changes: 4 additions & 4 deletions internal/codenav/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,10 @@ func (p *parser) skipAnnotation(i int) (int, string) {
}

type annos struct {
lombok uint8
builder, logAt pos
logType string
noArgs, allArgs, reqArgs pos
lombok uint8
builder, logAt pos
logType string
noArgs, allArgs, reqArgs pos
private, static, final, abstract bool
}

Expand Down
275 changes: 275 additions & 0 deletions internal/deps/ant.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
package deps

import (
"bytes"
"encoding/xml"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"unicode"
)

// Read only Ant's declarative path entries. Running a target to compute a
// classpath would execute project code on the first navigation request.
func (t *treeJars) antPath(root, build string) {
project := filepath.Join(root, filepath.FromSlash(build))
data, err := readLimited(project, maxPOMSize)
if err != nil {
return
}
dec := xml.NewDecoder(bytes.NewReader(data))
dec.CharsetReader = charsetReader
base := filepath.Dir(project)
props := antProperties{}
var entries []antEntry
var parents []string
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return
}
switch e := tok.(type) {
case xml.StartElement:
name := e.Name.Local
switch {
case len(parents) == 0:
if name != "project" {
return
}
if dir := antAttr(e, "basedir"); dir != "" {
base = antAbsolute(base, dir)
}
props["basedir"] = base
case len(parents) == 1 && name == "property":
props.define(e, root, base, filepath.Dir(project))
case parents[len(parents)-1] == "path" || parents[len(parents)-1] == "classpath":
if name == "pathelement" || name == "fileset" {
var entry antEntry
if dec.DecodeElement(&entry, &e) != nil {
return
}
entries = append(entries, entry)
continue
}
}
parents = append(parents, name)
case xml.EndElement:
parents = parents[:len(parents)-1]
}
}
for _, e := range entries {
if len(e.Other) != 0 || len(e.Attrs) != 0 {
continue // Don't widen an entry that uses an unsupported selector.
}
if e.XMLName.Local == "pathelement" {
if p := antLocalPath(root, base, props.expand(e.Location)); p != "" {
t.add(p, "")
}
} else if dir := antLocalPath(root, base, props.expand(e.Dir)); dir != "" {
t.antFileSet(dir, e, props)
}
}
}

func antAttr(e xml.StartElement, name string) string {
for _, a := range e.Attr {
if a.Name.Local == name {
return a.Value
}
}
return ""
}

func antAbsolute(base, p string) string {
p = filepath.FromSlash(strings.ReplaceAll(p, `\`, "/"))
if filepath.IsAbs(p) {
return filepath.Clean(p)
}
return filepath.Join(base, p)
}

// Only inspect archives inside the workspace, including ignored files.
func antLocalPath(root, base, p string) string {
if p == "" {
return ""
}
full := antAbsolute(base, p)
rel, err := filepath.Rel(root, full)
if err != nil || !filepath.IsLocal(rel) {
return ""
}
real, err := filepath.EvalSymlinks(full)
if err != nil {
return ""
}
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return ""
}
rel, err = filepath.Rel(realRoot, real)
if err != nil || !filepath.IsLocal(rel) {
return ""
}
return full
}

type antProperties map[string]string

// Ant properties are immutable. Recognize simple name=value entries of a
// declared sibling build.properties and top-level value/location properties.
func (p antProperties) define(e xml.StartElement, root, base, project string) {
if file := p.expand(antAttr(e, "file")); file != "" {
f := antLocalPath(root, base, file)
if f != filepath.Join(project, "build.properties") {
return
}
data, _ := readLimited(f, maxPOMSize)
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' || line[0] == '!' {
continue
}
if i := strings.IndexAny(line, "=:"); i >= 0 {
name := strings.TrimSpace(line[:i])
if _, set := p[name]; !set {
p[name] = strings.TrimSpace(line[i+1:])
}
}
}
return
}
name := antAttr(e, "name")
if _, set := p[name]; name == "" || set {
return
}
if loc := antAttr(e, "location"); loc != "" {
if value := p.expand(loc); value != "" {
p[name] = antAbsolute(base, value)
}
} else if value := antAttr(e, "value"); value != "" {
p[name] = value
}
}

// Bound expansion for cyclic or repeated references. Unknown properties
// leave the whole entry unresolved.
func (p antProperties) expand(value string) string {
for i := 0; i < 64; i++ {
start := strings.Index(value, "${")
if start < 0 {
return value
}
name, after, ok := strings.Cut(value[start+2:], "}")
v, known := p[name]
if !ok || !known || len(value)+len(v) > 64*1024 {
return ""
}
value = value[:start] + v + after
}
return ""
}

type antEntry struct {
XMLName xml.Name
ID string `xml:"id,attr"`
Location string `xml:"location,attr"`
Dir string `xml:"dir,attr"`
Includes string `xml:"includes,attr"`
Excludes string `xml:"excludes,attr"`
Include []antPattern `xml:"include"`
Exclude []antPattern `xml:"exclude"`
Other []struct{} `xml:",any"`
Attrs []xml.Attr `xml:",any,attr"`
}

var antWildcards = strings.NewReplacer(`\*`, "[^/]*", `\?`, "[^/]")

type antGlob struct {
re *regexp.Regexp
flat bool // all patterns match direct children only
}

type antPattern struct {
Name string `xml:"name,attr"`
Attrs []xml.Attr `xml:",any,attr"`
}

// Compile Ant's segment wildcards. A ** segment spans zero or more
// directories; a trailing slash is shorthand for a trailing **.
func antPatterns(list string, nested []antPattern, props antProperties) (antGlob, bool) {
patterns := strings.FieldsFunc(props.expand(list), func(r rune) bool { return r == ',' || unicode.IsSpace(r) })
if list != "" && len(patterns) == 0 {
return antGlob{}, false
}
for _, p := range nested {
name := props.expand(p.Name)
if name == "" || len(p.Attrs) != 0 {
return antGlob{}, false
}
patterns = append(patterns, name)
}
if len(patterns) == 0 {
return antGlob{}, true
}
var alternatives []string
flat := true
for _, pat := range patterns {
pat = strings.ReplaceAll(pat, `\`, "/")
if strings.Contains(pat, "/") || pat == "**" {
flat = false
}
if strings.HasSuffix(pat, "/") {
pat += "**"
}
var b strings.Builder
for seg := range strings.SplitSeq(pat, "/") {
if seg == "**" {
b.WriteString("([^/]+/)*")
} else {
quoted := regexp.QuoteMeta(seg)
b.WriteString(antWildcards.Replace(quoted))
b.WriteByte('/')
}
}
alternatives = append(alternatives, b.String())
}
re, err := regexp.Compile("^(" + strings.Join(alternatives, "|") + ")$")
return antGlob{re: re, flat: flat}, err == nil
}

func (t *treeJars) antFileSet(dir string, e antEntry, props antProperties) {
include, ok := antPatterns(e.Includes, e.Include, props)
if !ok {
return
}
exclude, ok := antPatterns(e.Excludes, e.Exclude, props)
if !ok {
return
}
// The dependency limit alone doesn't bound a directory full of non-jars.
visited := 0
fs.WalkDir(os.DirFS(dir), ".", func(rel string, d fs.DirEntry, err error) error {
visited++
if visited > 50000 || len(t.out) >= maxTreeJars {
return fs.SkipAll
}
if err != nil {
return nil
}
if d.IsDir() && rel != "." && (include.flat || d.Name() == ".git" || d.Name() == ".svn" || d.Name() == "CVS") {
return fs.SkipDir
}
if d.Type().IsRegular() && isLibraryJar(d.Name()) {
if (include.re == nil || include.re.MatchString(rel+"/")) && (exclude.re == nil || !exclude.re.MatchString(rel+"/")) {
t.add(filepath.Join(dir, filepath.FromSlash(rel)), "")
}
}
return nil
})
}
11 changes: 8 additions & 3 deletions internal/deps/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ var libProbes = []string{"lib", "libs", "WEB-INF/lib", "WebContent/WEB-INF/lib",
var projectMarkers = map[string]bool{"build.xml": true, ".classpath": true, ".project": true}

// TreeJars lists the jars root keeps in its working tree: the library
// entries of its Eclipse .classpath files, in their order, then the jars in
// entries of its Eclipse .classpath files, then Ant paths, then the jars in
// lib directories (see libDirs and libProbes). files are root's files as
// slash-separated relative paths; repo resolves Eclipse's M2_REPO variable
// and may be "". Jars that do not exist are left out. A jar's sources are the
Expand All @@ -47,17 +47,22 @@ var projectMarkers = map[string]bool{"build.xml": true, ".classpath": true, ".pr
func TreeJars(root string, files []string, repo string) []Jar {
t := treeJars{seen: map[string]bool{}}
var markerDirs []string
listed := map[string]bool{}
var builds []string
for _, f := range files {
listed[f] = true
dir, base := path.Split(f)
if base == ".classpath" {
t.classpath(root, f, repo)
}
if base == "build.xml" {
builds = append(builds, f)
}
if projectMarkers[base] {
markerDirs = append(markerDirs, strings.TrimSuffix(dir, "/"))
}
}
for _, build := range builds {
t.antPath(root, build)
}
for _, f := range files {
if inLibDir(f) {
t.add(filepath.Join(root, filepath.FromSlash(f)), "")
Expand Down
33 changes: 33 additions & 0 deletions internal/deps/tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,36 @@ func TestSourcesNotRootedAtThePackagesAreIgnored(t *testing.T) {
t.Errorf("Point read from the sources %v:\n%s", err, b)
}
}

// Neither the fileset's directory nor its jars need to be listed by Git.
func TestAntPathsOutsideLib(t *testing.T) {
root := t.TempDir()
for _, jar := range []string{"ext/one.jar", "vendor/a.jar", "vendor/a-sources.jar",
"vendor/deep/b.jar", "vendor/deep/c-skip.jar", "vendor/unrelated.jar", "other/ignored.jar"} {
treeJar(t, root, jar)
}
writeFile(t, filepath.Join(root, "module", "build.properties"), "thirdparty.dir=${prefix}\n")
writeFile(t, filepath.Join(root, "module", "build.xml"), `<project basedir="..">
<property name="prefix" value="vendor"/>
<property name="prefix" value="other"/>
<property file="module/build.properties"/>
<property name="first" location="ext/one.jar"/>
<path id="compile">
<pathelement location="${first}"/>
<pathelement location="ext/missing.jar"/>
<pathelement location="${unresolved}/ignored.jar"/>
</path>
<target name="compile"><javac><classpath>
<fileset dir="${thirdparty.dir}" excludes="**/*-skip.jar">
<include name="**/?.jar"/>
</fileset>
<pathelement location="ext/one.jar"/>
<fileset dir="other" includes="${unknown}"/>
</classpath></javac></target>
<copy><fileset dir="other"/></copy>
</project>`)
got := relJars(t, root, TreeJars(root, []string{"module/build.xml"}, ""))
if want := "ext/one.jar vendor/a.jar+vendor/a-sources.jar vendor/deep/b.jar"; got != want {
t.Errorf("Ant classpath = %q, want %q", got, want)
}
}
Loading
Loading