diff --git a/docs/en/guide/code-intelligence.mdx b/docs/en/guide/code-intelligence.mdx index 853cd5afa..1da0da40f 100644 --- a/docs/en/guide/code-intelligence.mdx +++ b/docs/en/guide/code-intelligence.mdx @@ -57,6 +57,7 @@ Language servers that support LSP inline completion show a grey suggestion at th | **Next Method** / **Previous Method** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` | - **Go to Declaration or Usages** on a declaration shows its usages instead. +- **Go to Implementation(s)** navigates to the symbol's own declaration when it has no implementations, as in IntelliJ IDEA. - Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it. - Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there. - **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none. diff --git a/docs/zh/guide/code-intelligence.mdx b/docs/zh/guide/code-intelligence.mdx index 7ea4939c0..0da1605ab 100644 --- a/docs/zh/guide/code-intelligence.mdx +++ b/docs/zh/guide/code-intelligence.mdx @@ -57,6 +57,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文 | **下一个方法** / **上一个方法** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` | - 在声明本身上执行 **转到声明或用法**,会改为显示它的用法。 +- 没有任何实现时,**转到实现** 会跳转到符号自身的声明,与 IntelliJ IDEA 一致。 - 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。 - 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。 - **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。 diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index 11c783efe..7c3ecad7d 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -386,6 +386,20 @@ async function pythonImplementations(doc: EditorDocContext, pos: Pos): Promise []); } +/** + * Asks for the declaration at `offset`, dropping the target under the caret. Called when Go to + * Implementation finds nothing: the jump then ends on the declaration, as in IDEA. + */ +async function implementationFallbackTargets( + view: EditorView, + offset: number, + path: string, + pos: Pos, +): Promise { + const declaration = await requestNavigation(view, offset, "definition").catch(() => []); + return declaration.filter((l) => !isSelfTarget([l], path, pos)); +} + /** Whether `line` (0-based) of `text` is an import statement. */ function isImportLine(text: Text, line: number): boolean { return line < text.lines && /^\s*(from|import)\s/.test(text.line(line + 1).text); @@ -510,7 +524,17 @@ async function gotoResolved( const graph = graphTargets ? await graphTargets : []; if (superseded()) return; if (graph.length) locs = graph; - else if (isCancelled(e) || !declaration) { + else if (kind === "implementation" && !isCancelled(e) && !isUnavailable(e)) { + // Some servers fail the request instead of answering empty (gopls: "no interfaces + // implemented by this method"). Treat that as a search that found nothing, not a broken server. + const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos); + if (superseded()) return; + if (!declarationTargets.length) { + reportLspError(view, e, true); + return; + } + locs = dedupeLocations(declarationTargets); + } else if (isCancelled(e) || !declaration) { reportLspError(view, e, true); return; } else { @@ -542,6 +566,12 @@ async function gotoResolved( return; } if (superseded()) return; + // Outside `gotoAfterEdits`, whose retries would repeat the extra request. + if (!locs.length && kind === "implementation" && !serverDown) { + const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos); + if (superseded()) return; + locs = dedupeLocations(declarationTargets); + } if (!locs.length) { // The server has no definition here: a link (`href`, `#include`, Markdown) or a file path. if ( diff --git a/src/editor/lsp/navigationImplementation.test.ts b/src/editor/lsp/navigationImplementation.test.ts new file mode 100644 index 000000000..b195bd190 --- /dev/null +++ b/src/editor/lsp/navigationImplementation.test.ts @@ -0,0 +1,157 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import type { commands, Location } from "@/platform/ipc"; + +const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({ + lspGoto: vi.fn(), + lspGotoImplementation: vi.fn(), +})); +vi.mock("@/platform/ipc", async (orig) => { + const real = await orig(); + const fsReadText: typeof commands.fsReadText = async () => ({ + status: "error", + error: { kind: "notFound", message: "not found" }, + }); + const navInheritance: typeof commands.navInheritance = async () => ({ status: "ok", data: [] }); + return { + ...real, + isTauri: () => true, + commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance }, + }; +}); +vi.mock("@tauri-apps/api/core", async (orig) => ({ + ...(await orig()), + Channel: class { + onmessage = () => {}; + }, +})); + +const { gotoTargets } = await import("./navigation"); +const { lspDoc } = await import("./lsp"); +const { closePopup } = await import("./popupStore"); +const { invalidateConfigurationNavigation } = await import("./configurationNavigation"); +const { provideEditorService } = await import("@/workbench/contributions"); +const openFile = vi.fn(async (_path: string, _opts: unknown) => {}); +provideEditorService({ openFile } as never); + +const loc = (path: string, line = 1, col = 2): Location => ({ + path, + uri: null, + range: { start: { line, col }, end: { line, col: col + 3 } }, +}); +const ok = (data: Location[]) => ({ status: "ok" as const, data }); +const declared = loc("/p/store.go"); +const implementation = loc("/p/iface.go"); + +const TEXT = "package p\n\nfunc (s *Store) Search() {}\n"; +const editor = (text: string, language: string, path: string) => + new EditorView({ + state: EditorState.create({ + doc: text, + extensions: [lspDoc.of({ doc: 1, path, language, uiMode: language, readOnly: false })], + }), + parent: document.body, + }); + +let view: EditorView; +beforeEach(() => { + vi.clearAllMocks(); + invalidateConfigurationNavigation(); + lspGoto.mockResolvedValue(ok([])); + lspGotoImplementation.mockResolvedValue(ok([])); + view = editor(TEXT, "go", "/p/store.go"); +}); +afterEach(() => { + view.destroy(); + closePopup(); + document.body.replaceChildren(); + vi.restoreAllMocks(); +}); + +/** Go to Implementation on `Search`, at the method's name. */ +const gotoSearch = () => gotoTargets(view, "implementation", TEXT.indexOf("Search") + 2); + +describe("Go to Implementation on a symbol nothing implements", () => { + it("navigates to the declaration, like IDEA", async () => { + lspGoto.mockResolvedValue(ok([declared])); + await gotoSearch(); + expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]); + expect(lspGotoImplementation).toHaveBeenCalledOnce(); + expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["definition"]); + }); + + it("navigates when the server reports its failed search as an error", async () => { + lspGotoImplementation.mockResolvedValue({ + status: "error", + error: { kind: "protocol", message: "no interfaces implemented by this method" }, + }); + lspGoto.mockResolvedValue(ok([declared])); + await gotoSearch(); + expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]); + }); + + it("still navigates to the implementations when there are some", async () => { + lspGotoImplementation.mockResolvedValue(ok([implementation])); + await gotoSearch(); + expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/iface.go"]); + expect(lspGoto).not.toHaveBeenCalled(); + }); + + it("does not navigate onto the declaration the caret is already on", async () => { + const at = TEXT.indexOf("Search"); + const col = at - (TEXT.lastIndexOf("\n", at) + 1); + lspGoto.mockResolvedValue( + ok([{ ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } }]), + ); + await gotoSearch(); + expect(openFile).not.toHaveBeenCalled(); + expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"); + }); + + it("keeps the not-found hint when the declaration request fails", async () => { + lspGoto.mockRejectedValue(new Error("timeout")); + await gotoSearch(); + expect(openFile).not.toHaveBeenCalled(); + expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"); + }); + + it("ignores the caret's own declaration among several targets", async () => { + const at = TEXT.indexOf("Search"); + const col = at - (TEXT.lastIndexOf("\n", at) + 1); + const self = { ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } }; + lspGoto.mockResolvedValue(ok([self, loc("/p/other.go")])); + await gotoSearch(); + expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/other.go"]); + }); + + it("keeps an unavailable server's error instead of inventing a target", async () => { + lspGotoImplementation.mockResolvedValue({ + status: "error", + error: { kind: "unavailable", message: "no implementation provider" }, + }); + lspGoto.mockResolvedValue(ok([declared])); + await gotoSearch(); + expect(lspGoto).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + expect(document.querySelector(".cm-lsp-hint")).not.toBeNull(); + }); + + it("navigates to a type's declaration from a usage", async () => { + const text = "package p\n\nvar s Store\n"; + view.destroy(); + view = editor(text, "go", "/p/store.go"); + lspGoto.mockResolvedValue(ok([loc("/p/store.go", 0, 5)])); + await gotoTargets(view, "implementation", text.indexOf("Store") + 2); + expect(openFile).toHaveBeenCalledWith("/p/store.go", { selection: { line: 0, col: 5 }, focus: true }); + }); + + it("covers Python, whose servers have no type hierarchy", async () => { + const text = "class Order:\n pass\n\nuse = Order\n"; + view.destroy(); + view = editor(text, "python", "/p/order.py"); + lspGoto.mockResolvedValue(ok([loc("/p/order.py", 0, 6)])); + await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2); + expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true }); + }); +}); diff --git a/src/editor/lsp/navigationMouse.test.ts b/src/editor/lsp/navigationMouse.test.ts index 263de04b4..841155793 100644 --- a/src/editor/lsp/navigationMouse.test.ts +++ b/src/editor/lsp/navigationMouse.test.ts @@ -300,13 +300,14 @@ describe("mouse navigation", () => { expect(lspGoto).not.toHaveBeenCalled(); }); - it("reports missing implementations without navigating to the declaration", async () => { + it("asks for the declaration before reporting missing implementations", async () => { lspGoto.mockResolvedValue({ status: "ok", data: [] }); click({ metaKey: true, altKey: true }); await vi.waitFor(() => expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"), ); - expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "implementation"); + // IDEA falls back to the declaration when nothing implements the name. + expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["implementation", "definition"]); expect(openFile).not.toHaveBeenCalled(); });