diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index a61118bc6..5fa7aa83b 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -550,6 +550,24 @@ pub async fn lsp_implementations( result } +/// Refines the implementations `targets` of the method at `pos` to their declarations (Java +/// dependencies' class files point at the start of the class). Cancel with +/// `cancel_request(request)`. +pub async fn lsp_implementation_locations( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, + pos: Pos, + targets: Vec, +) -> IdeResult> { + let lsp = host.project(window)?.lsp.clone(); + let (_, cancel) = begin_position_request(host, window, request, doc, pos).await?; + let result = lsp.implementation_locations(doc, pos, targets, cancel).await; + host.end_request(request); + result +} + /// Go to Implementation of the symbol at `pos`. Implementations found before a slower /// search for the rest (Java: the project's, before the dependencies') arrive on /// `on_partial`; the result has them all. Cancel with `cancel_request(request)`. @@ -1987,6 +2005,17 @@ pub(crate) fn register(d: &mut Dispatcher) { let on_partial = c.sender("onPartial")?; lsp_goto_implementation(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, on_partial).await }); + d.add("lsp_implementation_locations", |c| async move { + lsp_implementation_locations( + &c.host, + &c.window, + c.arg("request")?, + c.arg("doc")?, + c.arg("pos")?, + c.arg("targets")?, + ) + .await + }); d.add( "lsp_resolve_class_file", |c| async move { lsp_resolve_class_file(&c.host, &c.window, c.arg("path")?).await }, diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 0d56a3bcb..bb72e4c5c 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -434,6 +434,11 @@ async fn library_sources(snap: &DocSnap, root: &Path, pos: Pos, locs: Vec>, +} + /// Receives the implementations found so far, before a slower search for the rest. type Partial<'a> = Option<&'a (dyn Fn(Vec) + Send + Sync)>; @@ -1810,6 +1822,84 @@ impl LspManager { out } + /// jdtls: where the implementation methods of the method at `pos` are declared in the + /// dependency classes `locs` point at. Its standard request answers those with `0:0`, the + /// start of the class file's decompiled source; [`JAVA_IMPLEMENTATION_LOCATIONS`] resolves + /// the declaration itself. + async fn java_implementation_locations( + &self, + snap: &DocSnap, + t: &Target, + pos: Pos, + locs: Vec, + cancel: Option<&CancellationToken>, + ) -> Vec { + if t.server.name != "jdtls" || !t.caps().commands().iter().any(|c| c == JAVA_IMPLEMENTATION_LOCATIONS) { + return locs; + } + let targets: Vec<(usize, String)> = locs + .iter() + .enumerate() + .filter_map(|(i, l)| { + let uri = l.uri.as_deref()?; + (virtual_doc::scheme(uri) == "jdt" && l.range.start.line == 0).then(|| (i, uri.to_owned())) + }) + .collect(); + if targets.is_empty() { + return locs; + } + let params = snap.pos_params(t, pos); + let arguments = json!([ + params["textDocument"]["uri"], + params["position"]["line"], + params["position"]["character"], + targets.iter().map(|(_, uri)| uri).collect::>(), + ]); + let result: IdeResult = self + .call( + t, + "workspace/executeCommand", + json!({ "command": JAVA_IMPLEMENTATION_LOCATIONS, "arguments": arguments }), + cancel, + LONG_TIMEOUT, + ) + .await; + let found = match result { + Ok(found) if found.locations.len() == targets.len() => found, + Ok(_) => return locs, + Err(e) => { + tracing::debug!("{JAVA_IMPLEMENTATION_LOCATIONS}: {}", e.message); + return locs; + } + }; + let mut out = locs; + for ((i, _), loc) in targets.into_iter().zip(found.locations) { + if let Some(loc) = loc.as_ref().and_then(|l| self.conv(t.enc()).location(l)) { + out[i] = loc; + } + } + out + } + + /// Refines the implementation `locs` of the method at `pos`: jdtls puts an implementation in + /// a dependency at the start of its decompiled class instead of at the method, which matters + /// when the gutter marker's targets are opened one by one. + pub async fn implementation_locations( + &self, + doc: DocId, + pos: Pos, + locs: Vec, + cancel: CancellationToken, + ) -> IdeResult> { + let (_, cap, feature) = goto_method(GotoKind::Implementation); + let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?; + let mut out = locs; + for t in &targets { + out = self.java_implementation_locations(&snap, t, pos, out, Some(&cancel)).await; + } + Ok(out) + } + async fn goto_in( &self, snap: &DocSnap, @@ -1849,6 +1939,12 @@ impl LspManager { Ok(Some(r)) => { let locs = convert::goto_response(&self.conv(t.enc()), r); let locs = library_sources(snap, &self.project_root, pos, locs).await; + // Only explicit Go to Implementation: gutter markers ask for every line. + let locs = if method == "textDocument/implementation" && partial.is_some() { + self.java_implementation_locations(snap, t, pos, locs, cancel).await + } else { + locs + }; self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref())); self.note_arduino_sources(&t.server, &locs); let locs = self.jdt_library_classes(snap, pos, locs).await; diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 3dd5e7fb8..1a78dcf2e 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3483,6 +3483,52 @@ async fn java_implementations_come_from_sources_first() { assert_eq!(s.requested("textDocument/implementation").len(), 3); } +#[tokio::test(flavor = "multi_thread")] +async fn java_dependency_implementations_point_at_the_method() { + let caps = json!({ + "textDocumentSync": 1, + "implementationProvider": true, + "executeCommandProvider": { "commands": ["openidea.java.implementations", "openidea.java.implementationLocations"] }, + }); + let h = harness_for("java", "java", &[("jdtls", caps)], &[]); + let (doc, _) = h.open("Repo.java", "interface Repo {\n void save(String item);\n}\n"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let s = h.launcher.state("jdtls"); + let class_uri = "jdt://contents/lib.jar/zoo/RepoImpl.java?=p/lib.jar%3Czoo%28RepoImpl.class"; + let method = json!({ + "uri": class_uri, + "range": {"start":{"line":4,"character":4},"end":{"line":6,"character":5}}, + }); + let at_zero = json!({ + "uri": class_uri, + "range": {"start":{"line":0,"character":0},"end":{"line":0,"character":0}}, + }); + let refined = method.clone(); + *s.responder.lock() = Some(Arc::new(move |_, method, params| match method { + "workspace/executeCommand" if params["command"] == "openidea.java.implementations" => { + Some(json!({ "locations": [], "complete": false })) + } + "workspace/executeCommand" if params["command"] == "openidea.java.implementationLocations" => { + assert_eq!(params["arguments"][3], json!([class_uri])); + Some(json!({ "locations": [refined] })) + } + "textDocument/implementation" => Some(json!([at_zero])), + _ => None, + })); + let partial = Mutex::new(Vec::new()); + let found = h + .mgr + .goto_implementation(doc, Pos::new(1, 9), Default::default(), &|locs| partial.lock().push(locs.to_vec())) + .await + .unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].uri.as_deref(), Some(class_uri)); + assert_eq!(found[0].range.start.line, 4); + assert_eq!(s.requested("textDocument/implementation").len(), 1); + let commands = s.requested("workspace/executeCommand"); + assert!(commands.iter().any(|r| r["command"] == "openidea.java.implementationLocations")); +} + #[tokio::test(flavor = "multi_thread")] async fn navigation_rename_format_and_decorations() { let h = harness(&[("mock", incremental_caps())]); diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index c519dd1b9..84f1a6f12 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1588,7 +1588,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.14.0", + "1.15.0", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index 649ffb4df..b4ed35585 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -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, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index b074a12c3..a842d0dcd 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -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 diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index 9adce4c03..98d9c9b08 100644 Binary files a/java/java-usages/openidea-java-usages.jar and b/java/java-usages/openidea-java-usages.jar differ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index cb1138eff..039e41d62 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -20,6 +20,9 @@ + + + diff --git a/java/java-usages/src/ai/openidea/implementations/ImplementationTargetsCommand.java b/java/java-usages/src/ai/openidea/implementations/ImplementationTargetsCommand.java new file mode 100644 index 000000000..70bd8db85 --- /dev/null +++ b/java/java-usages/src/ai/openidea/implementations/ImplementationTargetsCommand.java @@ -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 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 targets = (List) 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 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 decompiled = JDTUtils.searchDecompiledSources(found, classFile, true, true, monitor); + return decompiled.isEmpty() ? null : decompiled.get(0); + } +} diff --git a/java/java-usages/tests/implementations.py b/java/java-usages/tests/implementations.py index 5655fb6a8..425ad2b65 100644 --- a/java/java-usages/tests/implementations.py +++ b/java/java-usages/tests/implementations.py @@ -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('zooorg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature') # `kotlin`: the project's compiled Kotlin classes, as the Kotlin bridge attaches them. -(project / '.classpath').write_text('') +(project / '.classpath').write_text('') 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() diff --git a/src-tauri/src/commands/lsp.rs b/src-tauri/src/commands/lsp.rs index e1c92c3d8..f1130e748 100644 --- a/src-tauri/src/commands/lsp.rs +++ b/src-tauri/src/commands/lsp.rs @@ -97,6 +97,22 @@ pub async fn lsp_goto_implementation( ide_host::ops::lsp::lsp_goto_implementation(&state.host, window.label(), request, doc, pos, on_partial).await } +/// Refines the implementations `targets` of the method at `pos` to their declarations (Java +/// dependencies' class files point at the start of the class). Cancel with +/// `cancel_request(request)`. +#[tauri::command] +#[specta::specta] +pub async fn lsp_implementation_locations( + window: Window, + state: State<'_, AppState>, + request: RequestId, + doc: DocId, + pos: Pos, + targets: Vec, +) -> IdeResult> { + ide_host::ops::lsp::lsp_implementation_locations(&state.host, window.label(), request, doc, pos, targets).await +} + /// Implementations of the symbols at `positions`, one list per position (the /// editor's "is implemented / overridden" gutter markers). Cancel with /// `cancel_request(request)`. diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 14c93de6f..156bb6794 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -287,6 +287,7 @@ pub fn builder() -> tauri_specta::Builder { lsp::lsp_goto, lsp::lsp_implementations, lsp::lsp_goto_implementation, + lsp::lsp_implementation_locations, lsp::lsp_virtual_document, lsp::lsp_can_download_sources, lsp::lsp_library_sources, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 64baa4aeb..3805c4a1a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -314,6 +314,7 @@ lsp_goto_implementation trusted project_host bin lsp_hierarchy_members trusted project_host bindings async lsp_hierarchy_refactor trusted project_host bindings async lsp_hover trusted project_host bindings async +lsp_implementation_locations trusted project_host bindings async lsp_implementations trusted project_host bindings async lsp_inlay_hints trusted project_host bindings async lsp_inline_completion trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 0f883e785..1b156a134 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -597,6 +597,12 @@ export const commands = { * Cancel with `cancel_request(request)`. */ lspGotoImplementation: (request: RequestId, doc: DocId, pos: Pos, onPartial: Channel) => typedError(__TAURI_INVOKE("lsp_goto_implementation", { request, doc, pos, onPartial })), + /** + * Refines the implementations `targets` of the method at `pos` to their declarations (Java + * dependencies' class files point at the start of the class). Cancel with + * `cancel_request(request)`. + */ + lspImplementationLocations: (request: RequestId, doc: DocId, pos: Pos, targets: Location[]) => typedError(__TAURI_INVOKE("lsp_implementation_locations", { request, doc, pos, targets })), /** * Contents of a read-only language-server document, including JDT library * classes and disk class files. Cached per project. diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts index 9faffb7ed..6bd125e0f 100644 --- a/src/editor/navigation/implementationGutter.ts +++ b/src/editor/navigation/implementationGutter.ts @@ -29,6 +29,7 @@ import { nextRequestId, onIdeEvent, type ClassInheritance, + type DocId, type HierarchyItem, type Location, type OutlineItem, @@ -324,6 +325,8 @@ export async function fillMarkers( entry(c).supers = { kind: "overriding", line: c.line, + col: c.col, + method: c.method, name: c.name, targets: [...known.map((s) => s.location), ...extra], tooltip: tx`Overrides method in ${owners.join(", ")}`, @@ -510,18 +513,46 @@ export function cachedMarkers( return out; } +/** + * A dependency's implementation (Java) starts at `0:0` of the class file: the server resolves + * the method's declaration when the marker is opened, not for every marker in the gutter. + */ +async function markerTargets(marker: LineMarker, doc: DocId | null): Promise { + if ( + doc === null || + doc < 0 || + !marker.method || + (marker.kind !== "implemented" && marker.kind !== "overridden") || + !marker.targets.some((t) => t.range.start.line === 0 && t.uri?.startsWith("jdt:")) + ) + return marker.targets; + const request = nextRequestId(); + try { + return await lspRequest(() => + commands.lspImplementationLocations(request, doc, { line: marker.line, col: marker.col }, marker.targets), + ); + } catch { + return marker.targets; + } +} + /** Opens the single target, or the chooser over several. */ -export async function openMarkerTargets(marker: LineMarker, anchor: { x: number; y: number }) { - if (marker.targets.length === 1) { - await navigateTo(marker.targets[0]!); +export async function openMarkerTargets( + marker: LineMarker, + anchor: { x: number; y: number }, + doc: DocId | null = null, +) { + const targets = await markerTargets(marker, doc); + if (targets.length === 1) { + await navigateTo(targets[0]!); return; } openPopup({ kind: "list", anchor, title: marker.chooserTitle, - items: await locationItems(marker.targets), - pin: pinToFind(marker.name, marker.targets), + items: await locationItems(targets), + pin: pinToFind(marker.name, targets), }); } @@ -785,7 +816,7 @@ export function implementationGutter(ctx: EditorDocContext): Extension { if (!marker) return false; e.preventDefault(); const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect(); - void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }); + void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc); return true; }, }), diff --git a/src/editor/navigation/lineMarkers.test.ts b/src/editor/navigation/lineMarkers.test.ts index c7b9e1de3..7b8fab117 100644 --- a/src/editor/navigation/lineMarkers.test.ts +++ b/src/editor/navigation/lineMarkers.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { IpcError, + commands, type ClassInheritance, type HierarchyItem, type Location, @@ -498,13 +499,48 @@ describe("clicking a marker", () => { it("navigates to a single target", async () => { const target = loc("/p/Circle.java", 0, 13); await openMarkerTargets( - { kind: "implemented", line: 0, name: "Shape", targets: [target], tooltip: "", chooserTitle: "" }, + { + kind: "implemented", + line: 0, + col: 17, + method: false, + name: "Shape", + targets: [target], + tooltip: "", + chooserTitle: "", + }, { x: 1, y: 2 }, ); expect(nav.navigateTo).toHaveBeenCalledWith(target); expect(nav.openPopup).not.toHaveBeenCalled(); }); + it("resolves a dependency's implementation at its method", async () => { + vi.stubGlobal("__TAURI_INTERNALS__", {}); + const zero = loc("jdt://contents/lib.jar/zoo/Impl.java?=p/lib.jar", 0, 0); + zero.uri = zero.path; + const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } }; + const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] }); + await openMarkerTargets( + { + kind: "implemented", + line: 1, + col: 9, + method: true, + name: "save", + targets: [zero], + tooltip: "", + chooserTitle: "", + }, + { x: 1, y: 2 }, + 7, + ); + expect(spy).toHaveBeenCalledWith(expect.any(Number), 7, { line: 1, col: 9 }, [zero]); + expect(nav.navigateTo).toHaveBeenCalledWith(method); + spy.mockRestore(); + vi.unstubAllGlobals(); + }); + it("opens the chooser over several targets", async () => { const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)]; expect(candidateKey(candidate())).toBe("0:17:Shape"); @@ -512,6 +548,8 @@ describe("clicking a marker", () => { { kind: "implemented", line: 0, + col: 17, + method: false, name: "Shape", targets, tooltip: "", diff --git a/src/editor/navigation/lineMarkers.ts b/src/editor/navigation/lineMarkers.ts index 8a81c5f4a..a8a66a2f1 100644 --- a/src/editor/navigation/lineMarkers.ts +++ b/src/editor/navigation/lineMarkers.ts @@ -48,6 +48,10 @@ export interface MarkerCandidate { export interface LineMarker { kind: MarkerKind; line: number; + /** UTF-16 column of the declaration's identifier, the position implementation requests use. */ + col: number; + /** A method (not a type): its implementations are methods, not classes. */ + method: boolean; /** Name of the declaration the marker is on. */ name: string; targets: Location[]; @@ -249,7 +253,16 @@ export function inheritorsMarker( ? tx`Choose Implementation of ${c.name} (${n} found)` : tx`Choose Overriding Method of ${c.name} (${n} found)`; } - return { kind, line: c.line, name: c.name, targets: [...targets], tooltip, chooserTitle }; + return { + kind, + line: c.line, + col: c.col, + method: c.method, + name: c.name, + targets: [...targets], + tooltip, + chooserTitle, + }; } /** ↑ marker of a Go type or method from the interfaces (methods) it satisfies; null without any. */ @@ -264,6 +277,8 @@ export function implementsMarker( return { kind: "implementing", line: c.line, + col: c.col, + method: c.method, name: c.name, targets: [...targets], tooltip: c.method ? tx`Implements method in ${names}` : tx`Implements ${names}`, @@ -293,6 +308,8 @@ export function supersMarker( return { kind: implementing ? "implementing" : "overriding", line: c.line, + col: c.col, + method: true, name: c.name, targets: supers.map((s) => s.location), tooltip: implementing ? tx`Implements method in ${owners}` : tx`Overrides method in ${owners}`,