fix(editor): resolve an imported Python name to its declaration, not the import (#3462)

basedpyright and pyrefly analyse one root, so for a name declared in an attached dependency project they answer the file's own import statement. When the declaration request's only answer is an import line of this Python file, the name's from-import binding (aliases included) names the module; nav_resolve_module finds it, attached projects included, and the project index's declaration there becomes the target (or the module file when the index has none). A caret on the import itself keeps its existing answer.

Co-authored-by: muutot <92625353+muutot@users.noreply.github.com>
This commit is contained in:
Muu
2026-11-15 08:30:14 +08:00
committed by GitHub
co-authored by muutot
parent 396a8d4b26
commit 4a98ce544b
2 changed files with 158 additions and 0 deletions
+46
View File
@@ -86,6 +86,7 @@ import { requestHover, showPhpConstructDocumentation } from "./hover";
import { declarationSummary, renderCode } from "./markdown";
import { enclosingType } from "@/editor/navigation/lineMarkers";
import { projectPythonHierarchy, pythonImplementationTargets } from "@/editor/navigation/pythonHierarchy";
import { importBindings } from "@/editor/navigation/inheritanceGraph";
import { editorPrefs } from "@/platform/editorSettings";
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
import { isAddCaretGesture } from "@/editor/core/cm/multiCaret";
@@ -387,6 +388,48 @@ async function pythonImplementations(doc: EditorDocContext, pos: Pos): Promise<D
return pythonImplementationTargets(hierarchy, doc.path, pos, outline).catch(() => []);
}
/** 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);
}
/**
* The declaration of a name this file imports, from the project index. A server that analyses
* only its own root answers the import statement instead, and an attached dependency project
* is outside that root — the import names the module the declaration lives in.
*/
async function importedDeclarationTargets(
view: EditorView,
doc: EditorDocContext,
name: string,
): Promise<DeclarationTarget[]> {
const binding = importBindings(view.state.doc.toString().split("\n")).get(name);
if (!binding) return [];
const module = await moduleFile(doc, binding.module).catch(() => null);
if (!module) return [];
const found = await indexDefinitions(doc.path, binding.name).catch(() => []);
const inModule = found.filter((t) => t.path === module.path);
return inModule.length ? inModule : [module];
}
/** Replaces a server answer that is only this file's import line with the declaration it binds. */
async function withImportedDeclaration(
view: EditorView,
doc: EditorDocContext,
offset: number,
locs: DeclarationTarget[],
): Promise<DeclarationTarget[]> {
const only = locs[0];
if (locs.length !== 1 || !only || only.path !== doc.path || !isImportLine(view.state.doc, only.range.start.line))
return locs;
// A caret placed on the import itself already has an answer: the module (or the submodule)
// the statement names, handled below.
if (importedModulePath(view, offset)) return locs;
const name = nameAt(view, offset);
const resolved = name ? await importedDeclarationTargets(view, doc, name) : [];
return resolved.length ? resolved : locs;
}
/** `more` after `first`, without a target whose declaration line is already there. */
function mergeTargets(first: readonly DeclarationTarget[], more: readonly DeclarationTarget[]): DeclarationTarget[] {
return dedupeLocations([
@@ -488,6 +531,9 @@ async function gotoResolved(
fromSyntax = true;
}
}
// A server that only sees its own root answers the import statement for a name it cannot
// resolve; the import names the module that declares it, also in an attached project.
if (declaration && doc.language === "python") locs = await withImportedDeclaration(view, doc, offset, locs);
if (graphTargets) locs = mergeTargets(locs, await graphTargets);
if (streamed && (await streamed.opened())) {
await streamed.complete(locs);
@@ -0,0 +1,112 @@
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";
// A name imported from an attached project: the server analyses one root, so it answers the
// import statement instead of the declaration the module holds.
const { lspGoto, navResolveModule, navIndexDefinitions, fsReadText } = vi.hoisted(() => ({
lspGoto: vi.fn<typeof commands.lspGoto>(),
navResolveModule: vi.fn<typeof commands.navResolveModule>(),
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
fsReadText: vi.fn<typeof commands.fsReadText>(async () => ({
status: "error" as const,
error: { kind: "notFound" as const, message: "not found" },
})),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, lspGoto, navResolveModule, navIndexDefinitions, fsReadText },
};
});
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { closePopup } = await import("./popupStore");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
const span = (line: number, col: number) => ({ start: { line, col }, end: { line, col } });
const at = (path: string, line: number): Location => ({ path, range: span(line, 0) });
let view: EditorView;
/** Opens `text` and keeps it; returns the offset of the `occurrence`-th `name` in it. */
const openAt = (text: string, name: string, occurrence = 0) => {
view?.destroy();
view = new EditorView({
state: EditorState.create({
doc: text,
extensions: [lspDoc.of({ doc: 1, path: "/p/x.py", language: "python", uiMode: "Python", readOnly: false })],
}),
parent: document.body,
});
let from = -1;
for (let i = 0; i <= occurrence; i++) from = text.indexOf(name, from + 1);
view.dispatch({ selection: { anchor: from + 1 } });
};
beforeEach(() => {
vi.clearAllMocks();
lspGoto.mockResolvedValue({ status: "ok", data: [at("/p/x.py", 0)] });
navResolveModule.mockResolvedValue({ status: "ok", data: "/dep/base.py" });
navIndexDefinitions.mockResolvedValue({
status: "ok",
data: [{ path: "/dep/base.py", range: span(0, 6), name: "Base", kind: "class", container: null }],
} as never);
});
afterEach(() => {
closePopup();
view?.destroy();
document.body.replaceChildren();
vi.restoreAllMocks();
});
describe("go to declaration on a Python name imported from another project", () => {
it("resolves a class base name to the class, not the import", async () => {
openAt("from dep.base import Base\n\nclass X(Base):\n pass\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a plain usage to the class, not the import", async () => {
openAt("from dep.base import Base\n\n\ndef make():\n return Base()\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a base name written with an import alias", async () => {
openAt("from dep.base import Base as Parent\n\nclass X(Parent):\n pass\n", "Parent", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("resolves a subscripted base to the class it parameterises", async () => {
openAt("from dep.base import Base\n\nclass X(Base[int]):\n pass\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 6 }, focus: true });
});
it("opens the module when the index has no symbol of that name", async () => {
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] } as never);
openAt("from dep.base import Thing\n\nclass X(Thing):\n pass\n", "Thing", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/base.py", { selection: { line: 0, col: 0 }, focus: true });
});
it("keeps a server answer that is not the import statement", async () => {
lspGoto.mockResolvedValue({ status: "ok", data: [at("/dep/other.py", 3)] });
openAt("from dep.base import Base\n\nvalue = Base\n", "Base", 1);
await gotoTargets(view, "definition");
expect(openFile).toHaveBeenCalledWith("/dep/other.py", { selection: { line: 3, col: 0 }, focus: true });
});
});