Skip to content

Commit 853fee2

Browse files
authored
Fix IndexOutOfBoundException on finding references (#298)
It is possible that the matching type does not appear directly in the AST, e.g. when a type is referenced with "var". This patch fixes the issue by skipping such matches. Fixes #297.
1 parent 6c82d0a commit 853fee2

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

src/main/java/org/javacs/navigation/FindReferences.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.sun.source.util.*;
55
import java.util.List;
66
import javax.lang.model.element.Element;
7+
import javax.tools.Diagnostic;
78

89
class FindReferences extends TreePathScanner<Void, List<TreePath>> {
910
final JavacTask task;
@@ -47,7 +48,18 @@ public Void visitMemberReference(MemberReferenceTree t, List<TreePath> list) {
4748
}
4849

4950
private boolean check() {
50-
var candidate = Trees.instance(task).getElement(getCurrentPath());
51-
return find.equals(candidate);
51+
var path = getCurrentPath();
52+
var trees = Trees.instance(task);
53+
var candidate = trees.getElement(path);
54+
if (!find.equals(candidate)) {
55+
return false;
56+
}
57+
var pos = trees.getSourcePositions();
58+
// Skip elements without positions. This can happen, e.g. for var types.
59+
if (pos.getStartPosition(path.getCompilationUnit(), path.getLeaf()) == Diagnostic.NOPOS ||
60+
pos.getEndPosition(path.getCompilationUnit(), path.getLeaf()) == Diagnostic.NOPOS) {
61+
return false;
62+
}
63+
return true;
5264
}
5365
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package org.javacs.example;
2+
3+
public class VarTypeReferences {
4+
private static class Foo {
5+
public void foo() {}
6+
}
7+
8+
public void run() {
9+
var foo = new Foo();
10+
foo.foo();
11+
}
12+
}

src/test/java/org/javacs/FindReferencesTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,9 @@ public void findStackedFieldReferences() {
5656
assertThat(items(file, 4, 12), contains("StackedFieldReferences.java(8)"));
5757
assertThat(items(file, 4, 15), contains("StackedFieldReferences.java(9)"));
5858
}
59+
60+
@Test
61+
public void varTypeReferences() {
62+
assertThat(items("/org/javacs/example/VarTypeReferences.java", 4, 27), contains("VarTypeReferences.java(9)"));
63+
}
5964
}

0 commit comments

Comments
 (0)