Repository navigation
Expand file tree
/
Copy pathFindCursor.java
More file actions
53 lines (41 loc) · 1.56 KB
/
Copy pathFindCursor.java
File metadata and controls
53 lines (41 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package org.javacs;
import com.sun.source.tree.*;
import com.sun.source.util.*;
import java.util.Optional;
class FindCursor {
public static Optional<TreePath> find(
JavacTask task, CompilationUnitTree source, int line, int column) {
SourcePositions sourcePositions = Trees.instance(task).getSourcePositions();
long offset = source.getLineMap().getPosition(line, column);
class Finished extends RuntimeException {
final TreePath found;
Finished(TreePath of) {
found = of;
}
}
class Search extends TreePathScanner<Void, Void> {
@Override
public Void scan(Tree leaf, Void nothing) {
if (containsCursor(leaf)) {
super.scan(leaf, nothing);
throw new Finished(new TreePath(getCurrentPath(), leaf));
} else return null;
}
boolean containsCursor(Tree leaf) {
long start = sourcePositions.getStartPosition(source, leaf);
long end = sourcePositions.getEndPosition(source, leaf);
return start <= offset && offset <= end;
}
@Override
public Void visitErroneous(ErroneousTree node, Void nothing) {
return super.scan(node.getErrorTrees(), nothing);
}
}
try {
new Search().scan(source, null);
return Optional.empty();
} catch (Finished found) {
return Optional.of(found.found);
}
}
}