fix(java): go to implementation lands on the method in dependency classes (#3706)

jdtls answers textDocument/implementation for an implementation in a dependency at 0:0 of the decompiled class file (the search match has no source offset), so the gutter and Go to Implementation opened the class instead of the method. java-usages 1.15.0 adds openidea.java.implementationLocations, which finds the overriding method with MethodOverrideTester and returns its decompiled declaration; explicit Go to Implementation refines jdt 0:0 targets, and gutter markers resolve them lazily when opened (lsp_implementation_locations).

Co-authored-by: misswell <28730815+misswell@users.noreply.github.com>
This commit is contained in:
misswell
2026-11-16 16:11:59 +08:00
committed by GitHub
co-authored by misswell
parent c6bd809d08
commit 610d68ee41
17 changed files with 427 additions and 12 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.14.0
Bundle-Version: 1.15.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+4 -1
View File
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.13.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.15.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -133,6 +133,9 @@ its reproducible SHA-256 is
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
implementation in a dependency declares (the standard request starts at its class file); its
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Binary file not shown.
+3
View File
@@ -20,6 +20,9 @@
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
<command id="openidea.java.refreshArchives"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
<command id="openidea.java.implementationLocations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
@@ -0,0 +1,63 @@
package ai.openidea.implementations;
import ai.openidea.Documents;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.corext.util.MethodOverrideTester;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.lsp4j.Location;
/**
* Where the implementations of the method at a position declare it, in the classes named by the
* caller: one location per target URI, or null when the target has no such method. The standard
* implementation request answers with the start of a class file's decompiled source for an
* implementation in a dependency; this resolves the method's own declaration there.
*/
public final class ImplementationTargetsCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
Documents.awaitChanges(monitor);
String uri = (String) arguments.get(0);
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
@SuppressWarnings("unchecked")
List<String> targets = (List<String>) arguments.get(3);
ITypeRoot root = JDTUtils.resolveTypeRoot(uri, true, monitor);
if (root == null) return Map.of("locations", List.of());
try {
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
IJavaElement element = JDTUtils.findElementAtSelection(root, line, column, preferences, monitor);
if (!(element instanceof IMethod method)) return Map.of("locations", List.of());
List<Location> locations = new ArrayList<>(targets.size());
for (String targetUri : targets) {
if (monitor.isCanceled()) throw new OperationCanceledException();
locations.add(find(method, targetUri, monitor));
}
return Map.of("locations", locations);
} finally {
JDTUtils.discardClassFileWorkingCopy(root);
}
}
/** The declaration of {@code method}'s implementation in the class {@code targetUri}, or null. */
private static Location find(IMethod method, String targetUri, IProgressMonitor monitor) throws JavaModelException {
ITypeRoot targetRoot = JDTUtils.resolveTypeRoot(targetUri);
if (targetRoot == null) return null;
IType target = targetRoot.findPrimaryType();
if (target == null) return null;
ITypeHierarchy hierarchy = target.newSupertypeHierarchy(monitor);
// Seen from the subtype, so its type arguments substitute the method's type variables.
IMethod found = new MethodOverrideTester(target, hierarchy).findOverridingMethodInType(target, method);
if (found == null || Flags.isAbstract(found.getFlags())) return null;
IClassFile classFile = found.getClassFile();
if (classFile == null) return JDTUtils.toLocation(found);
List<Location> decompiled = JDTUtils.searchDecompiledSources(found, classFile, true, true, monitor);
return decompiled.isEmpty() ? null : decompiled.get(0);
}
}
+66 -1
View File
@@ -23,9 +23,30 @@ config_source = next(home / name / 'config.ini' for name in config_names if (hom
(config / 'config.ini').write_bytes(config_source.read_bytes())
project = work / 'project'
(project / 'src/zoo').mkdir(parents=True)
(project / 'lib').mkdir()
libs = work / 'libsrc/zoo'
libs.mkdir(parents=True)
(libs / 'ExternalRepo.java').write_text('''package zoo;
public interface ExternalRepo {
String find(String id, int limit);
}
''')
(libs / 'ExternalImpl.java').write_text('''package zoo;
public class ExternalImpl implements ExternalRepo {
public String find(String id, int limit) {
return id + limit;
}
}
''')
lib_classes = work / 'libclasses'
lib_classes.mkdir()
subprocess.run(['javac', '--release', '8', '-d', str(lib_classes)] + [str(p) for p in libs.glob('*.java')], check=True)
subprocess.run(['jar', 'cf', str(project / 'lib/external-api.jar'), '-C', str(lib_classes), '.'], check=True)
(project / '.project').write_text('<projectDescription><name>zoo</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
# `kotlin`: the project's compiled Kotlin classes, as the Kotlin bridge attaches them.
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/external-api.jar"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
sources = {
'Repo.java': '''package zoo;
@@ -87,6 +108,14 @@ public class Anon {
};
}
}
''',
'UseExternal.java': '''package zoo;
public class UseExternal {
void use(ExternalRepo repo) {
repo.find("x", 1);
}
}
''',
'Use.java': '''package zoo;
@@ -180,6 +209,28 @@ def implementations(file, needle):
return sorted(names), found['complete']
def definition(file, needle):
line, col = position(file, needle)
return request('textDocument/definition', {'textDocument': {'uri': uri(file)}, 'position': {'line': line, 'character': col}})
def class_contents(class_uri):
return request('java/classFileContents', {'uri': class_uri})
def standard_implementations(class_uri, line, col):
found = request('textDocument/implementation', {'textDocument': {'uri': class_uri}, 'position': {'line': line, 'character': col}})
return found or []
def implementation_locations(class_uri, line, col, targets):
found = command('openidea.java.implementationLocations', class_uri, line, col, targets)
return [
(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(loc['uri']).path)).name, loc['range']['start']['line'])
for loc in found['locations'] if loc is not None
]
try:
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'zoo'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'extendedClientCapabilities': {'classFileContentsSupport': True}, 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
assert 'openidea.java.implementations' in init['capabilities']['executeCommandProvider']['commands']
@@ -207,6 +258,20 @@ try:
if actual != expected:
failures.append((file, needle, expected, actual))
assert not failures, failures
# An interface in a dependency: the standard request starts at the class file, and the
# extension resolves the implementing method's declaration in the dependency.
defs = definition('UseExternal.java', 'ExternalRepo repo')
class_uri = defs[0]['uri']
text = class_contents(class_uri)
method_line = next(i for i, line in enumerate(text.splitlines()) if 'find(' in line)
method_col = text.splitlines()[method_line].index('find')
std = standard_implementations(class_uri, method_line, method_col)
targets = [loc['uri'] for loc in std]
resolved = implementation_locations(class_uri, method_line, method_col, targets)
print('dependency implementation:', resolved)
expected = [(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(targets[0]).path)).name, 7)]
assert resolved == expected, (resolved, expected)
print('ok')
finally:
proc.kill()