Файли
openidea/src/editor/lsp/codeLens.test.ts
T
koeriaтаkoeria 92bf9354fe fix(lsp): skip Dart Code Vision references for inherited Flutter lifecycle methods (#7216)
Code Vision asked the Dart server for references of every @override Flutter lifecycle method (build, initState, dispose…), which on a large app floods the single-isolate server and stalls completions. Usages counts are no longer requested for those inherited overrides.

Fixes #7206

Co-authored-by: koeria <[email protected]>
2026-12-01 18:57:07 +08:00

843 рядки
34 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { OutlineItem, References } from "@/platform/ipc";
import {
_addEditor,
_emitEditorEvent,
_removeEditor,
codeLenses,
documentSynced,
setLibraryRoots,
viewShown,
type EditorDocContext,
} from "@/editor/api";
const ipc = vi.hoisted(() => ({
docOutline: vi.fn(),
docOpen: vi.fn(),
docClose: vi.fn(async () => ({ status: "ok" as const, data: null })),
lspReferences: vi.fn(),
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
vcsBlame: vi.fn(),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const python = vi.hoisted(() => ({ hierarchy: null as unknown }));
vi.mock("@/editor/navigation/pythonHierarchy", async (orig) => ({
...(await orig<object>()),
projectPythonHierarchy: async () => python.hierarchy ?? Promise.reject(new Error("no graph")),
}));
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = () => {};
},
}));
const { lensTargets, skipInheritedLifecycleUsages, usagesLensExtension } = await import("./codeLens");
const { foregroundStarted } = await import("./foreground");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useProjectRoots } = await import("@/platform/projectRoots");
const { _resetLanguages, loadLanguageInfos } = await import("@/editor/core/cm/languages");
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
const views: EditorView[] = [];
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const refs = (n: number, incomplete: References["incomplete"] = null) =>
ok({
locations: Array.from({ length: n }, () => ({ path: "/p/b.rs", range: item("x", "function", 0).range })),
incomplete,
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
function editor(count = 1, sync?: () => Promise<void>, docCtx: EditorDocContext = ctx) {
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: count }, (_, i) => `fn f${i}() {}`).join("\n"),
extensions: [lspDoc.of(docCtx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])],
}),
parent: document.body,
});
views.push(view);
return view;
}
const titles = (view: EditorView) => view.state.facet(codeLenses).map((l) => l.title);
const settle = () => vi.advanceTimersByTimeAsync(1000);
beforeEach(() => {
vi.useFakeTimers();
ipc.docOutline.mockReset().mockResolvedValue(ok([item("f0", "function", 0)]));
ipc.lspReferences.mockReset().mockResolvedValue(refs(2));
ipc.cancelRequest.mockClear();
executeAction.mockClear();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } } } as never,
});
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
_resetLanguages();
useProject.setState({ settings: null });
vi.useRealTimers();
});
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
const r = { start: { line, col: 0 }, end: { line, col: 1 } };
return { name, kind, detail: null, range: r, selection_range: r, children };
};
describe("usages label", () => {
it("is translated", async () => {
const { usagesLabel } = await import("./codeLens");
const { setLocale } = await import("@/platform/i18n");
expect([0, 1, 3].map(usagesLabel)).toEqual(["no usages", "1 usage", "3 usages"]);
await setLocale("zh");
expect([0, 1, 3].map(usagesLabel)).toEqual(["无用法", "1 个用法", "3 个用法"]);
await setLocale("en");
});
});
describe("usages lens targets", () => {
it("skips callbacks and anonymous functions", () => {
const items = [
item("Cart", "class", 0, [
item("count", "method", 1, [item("reduce() callback", "function", 2)]),
item("<function>", "function", 3),
]),
];
expect(lensTargets(items).map((t) => t.name)).toEqual(["Cart", "count"]);
});
it("counts a CSS selector's usages from its name, past the `.`", () => {
const targets = lensTargets([item(".button", "class", 0), item("button", "class", 1)]);
expect(targets.map((t) => t.col)).toEqual([1, 0]);
});
});
describe("author hint", () => {
it("toggles the blame annotations on every click", async () => {
ipc.vcsBlame.mockResolvedValue(ok([{ commit: "c1", author: "Ann", timeMs: 1, summary: "init" }]));
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: true } } } as never,
});
const view = editor();
await settle();
const author = view.state.facet(codeLenses).find((l) => l.kind === "author")!;
expect(author.title).toContain("Ann");
author.run!(view, new MouseEvent("click"));
author.run!(view, new MouseEvent("click"));
expect(executeAction.mock.calls).toEqual([["vcs.annotate"], ["vcs.annotate"]]);
});
});
describe("Python usages through a base", () => {
const impl = { doc: 9, path: "/p/impl.py", language: "python", uiMode: "Python", readOnly: false };
const BASE_DOC = 10;
const span = (line: number, col: number, len: number) => ({
start: { line, col },
end: { line, col: col + len },
});
const py = (name: string, kind: OutlineItem["kind"], line: number, end: number, children: OutlineItem[] = []) => ({
name,
kind,
detail: null,
range: { start: { line, col: 0 }, end: { line: end, col: 1 } },
selection_range: span(line, kind === "class" ? 6 : 8, name.length),
children,
});
afterEach(() => {
python.hierarchy = null;
});
it("counts the calls bound to the method it overrides", async () => {
const { pythonHierarchy } = await import("@/editor/navigation/pythonHierarchy");
python.hierarchy = pythonHierarchy(
[
{ path: "/p/base.py", line: 0, col: 6, name: "Repository", bases: [] },
{ path: "/p/impl.py", line: 0, col: 6, name: "MysqlRepository", bases: ["Repository"] },
],
{ readFiles: async (paths) => new Map(paths.map((p) => [p, null])) },
);
const outlines: Record<number, OutlineItem[]> = {
[impl.doc]: [py("MysqlRepository", "class", 0, 2, [py("save", "method", 1, 2)])],
[BASE_DOC]: [py("Repository", "class", 0, 2, [py("save", "method", 1, 2)])],
};
ipc.docOutline.mockImplementation(async (doc: number) => ok(outlines[doc] ?? []));
ipc.docOpen.mockImplementation(async (path: string) => ok({ id: path === "/p/base.py" ? BASE_DOC : 0 }));
// `repo.save()` with `repo: Repository` binds to the base's declaration only.
const call = { path: "/p/service.py", range: span(4, 13, 4) };
ipc.lspReferences.mockImplementation(async (_request: number, doc: number) =>
ok({ locations: doc === BASE_DOC ? [call] : [], incomplete: null }),
);
const view = editor(3, undefined, impl);
await settle();
expect(titles(view)).toEqual(["no usages", "1 usage"]);
expect(ipc.lspReferences.mock.calls.map((c) => [c[1], c[2]])).toEqual([
[impl.doc, { line: 0, col: 6 }],
[impl.doc, { line: 1, col: 8 }],
[BASE_DOC, { line: 1, col: 8 }],
]);
});
});
describe("Vue component usages", () => {
const vue = { doc: 8, path: "/p/Hello.vue", language: "vue", uiMode: "Vue", readOnly: false };
it("offers Show component usages above a .vue file, and nothing extra elsewhere", async () => {
ipc.docOutline.mockResolvedValue(ok([]));
const view = editor(1, undefined, vue);
await settle();
const lens = view.state.facet(codeLenses).find((l) => l.title === "Show component usages");
expect(lens).toMatchObject({ pos: 0, kind: "usages" });
const rust = editor();
await settle();
expect(titles(rust)).not.toContain("Show component usages");
});
it("is hidden with the usages hints", async () => {
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: false } } } as never,
});
const view = editor(1, undefined, vue);
await settle();
expect(titles(view)).toEqual([]);
});
});
describe("Code Vision switch", () => {
it("hides usages and author while off and brings back the kinds still chosen", async () => {
ipc.vcsBlame.mockResolvedValue(ok([{ commit: "c1", author: "Ann", timeMs: 1, summary: "init" }]));
const inlay = (codeVision: boolean) =>
useProject.setState({
settings: { editor: { inlay: { codeVision, codeVisionUsages: true, codeVisionAuthor: true } } } as never,
});
inlay(true);
const view = editor();
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
inlay(false);
await settle();
expect(titles(view)).toEqual([]);
inlay(true);
await settle();
expect(view.state.facet(codeLenses).map((l) => l.kind)).toEqual(["author", "usages"]);
});
});
describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(
expect.any(Number),
7,
{ line: 0, col: 0 },
false,
false,
false,
expect.anything(),
);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("counts nothing in library sources, where every count searches the whole project", async () => {
const off = setLibraryRoots("test", ["/venv/lib/site-packages"]);
try {
const library = editor(1, undefined, { ...ctx, path: "/venv/lib/site-packages/m/a.rs" });
const virtual = editor(1, undefined, { ...ctx, doc: 8, path: "jdt://contents/A.class", virtual: true });
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect([titles(library), titles(virtual)]).toEqual([[], []]);
} finally {
off();
}
});
it("counts nothing outside the project's own code: a server's stubs, a node_modules package", async () => {
useProject.setState({ project: { root: "/p" } as never });
try {
const stub = editor(1, undefined, { ...ctx, doc: 9, path: "/opt/server/typeshed/stdlib/typing.pyi" });
// A transitive dependency in the package manager's store, inside the project folder.
const store = editor(1, undefined, {
...ctx,
doc: 10,
path: "/p/node_modules/.pnpm/[email protected]/node_modules/react/index.d.ts",
});
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect([titles(stub), titles(store)]).toEqual([[], []]);
const own = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(own)).toEqual(["2 usages"]);
} finally {
useProject.setState({ project: null });
}
});
it("counts nothing in a folder marked Excluded, unless a source folder inside it holds the file", async () => {
useProject.setState({ project: { root: "/p" } as never });
useProjectRoots.setState({
root: "/p",
detected: [
{ path: "vendor", kind: "excluded", detectedFrom: null },
{ path: "vendor/own/src", kind: "source", detectedFrom: null },
],
});
try {
const vendored = editor(1, undefined, { ...ctx, doc: 11, path: "/p/vendor/lib/a.rs" });
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(titles(vendored)).toEqual([]);
const own = editor(1, undefined, { ...ctx, doc: 12, path: "/p/vendor/own/src/a.rs" });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(own)).toEqual(["2 usages"]);
} finally {
useProject.setState({ project: null });
useProjectRoots.setState({ root: null, detected: [] });
}
});
it("allows a full search even when the server's current scope has no usages", async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
const view = editor();
await settle();
expect(titles(view)).toEqual(["no usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it('leaves out "no usages" when Show “no usages” is off', async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
useProject.setState({
settings: {
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false, codeVisionNoUsages: false } },
} as never,
});
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
});
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("asks again for a count that came back incomplete during a short busy spell", async () => {
// jdtls reports progress for a few milliseconds around many requests: no settle follows it.
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("stops asking again while the server keeps saying it is indexing, until it settles", async () => {
ipc.lspReferences.mockResolvedValue(refs(0, "indexing"));
const view = editor();
for (let i = 0; i < 10; i++) {
// oxlint-disable-next-line no-await-in-loop -- each settle advances fake timers one retry step at a time
await settle();
}
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
expect(titles(view)).toEqual([]);
ipc.lspReferences.mockResolvedValue(refs(2));
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("keeps the shown lens while the server is busy and corrects the count once it settles", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
// Editing while the server is indexing: the re-computed count comes back incomplete.
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
ipc.lspReferences.mockResolvedValue(refs(0, "indexing"));
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
await settle();
await settle();
await settle();
await settle();
// The lens stays on its (mapped) line instead of blinking away and shifting the layout.
expect(titles(view)).toEqual(["2 usages"]);
// Once it settles, a complete answer replaces the stale count.
ipc.lspReferences.mockResolvedValue(refs(0));
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(titles(view)).toEqual(["no usages"]);
});
it("opens usages at the lens's current position after edits above it", async () => {
// The lens anchors on the identifier (`f0` at column 3), as in a real outline.
const decl = item("f0", "function", 0);
decl.selection_range = { start: { line: 0, col: 3 }, end: { line: 0, col: 5 } };
ipc.docOutline.mockResolvedValue(ok([decl]));
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
// Insert a line above the declaration. The lens maps down with its line, and a
// pass with an identical count is suppressed by `sameLenses` — the click must
// still land on the identifier, not where it was when the lens was created.
view.dispatch({ changes: { from: 0, insert: "\n" } });
const declAfter = item("f0", "function", 1);
declAfter.selection_range = { start: { line: 1, col: 3 }, end: { line: 1, col: 5 } };
ipc.docOutline.mockResolvedValue(ok([declAfter]));
await settle();
const lens = view.state.facet(codeLenses).find((l) => l.kind === "usages")!;
expect(lens.pos).toBe(4);
lens.run!(view, new MouseEvent("click"));
expect(view.state.selection.main.head).toBe(4);
});
it("cancels obsolete requests immediately on edits and ignores their late replies", async () => {
const old = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(old.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
await settle();
expect(titles(view)).toEqual(["2 usages"]);
old.resolve(refs(99));
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("retries incomplete counts when indexing ends without a code-lens refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
expect(titles(view)).toEqual([]);
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("does not repeat complete counts when the server finishes other work", async () => {
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels all in-flight requests on destroy without starting the next batch", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor(8);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
const requests = ipc.lspReferences.mock.calls.map(([id]) => id);
view.destroy();
views.splice(views.indexOf(view), 1);
expect(ipc.cancelRequest.mock.calls.map(([id]) => id)).toEqual(requests);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
});
it("gives way to a request the user waits for: cancels in-flight counts and asks again once it is done", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(pending.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
const done = foregroundStarted();
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
pending.resolve(refs(99));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
done();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("starts no counts while a request the user waits for runs", async () => {
const done = foregroundStarted();
const view = editor();
await settle();
expect(ipc.lspReferences).not.toHaveBeenCalled();
done();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels pending counts when the feature is disabled", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor();
await settle();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: false } } } as never,
});
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.lspReferences.mock.calls[0]![0]);
pending.resolve(refs(2));
await settle();
expect(titles(view)).toEqual([]);
});
it("does not send obsolete requests after waiting for document synchronization", async () => {
const synced = deferred<void>();
const view = editor(1, () => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
view.destroy();
views.splice(views.indexOf(view), 1);
synced.resolve();
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(ipc.cancelRequest).not.toHaveBeenCalled();
} finally {
_removeEditor(handle);
}
});
});
describe("recounting when the project's documents change", () => {
it("recounts when another document is edited (the call sites)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
ipc.lspReferences.mockResolvedValue(refs(5));
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 2, version: 3, changes: [] });
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when a kept tab is shown again after another document changed while hidden", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(5));
// A recently used tab keeps its view, detached from the document, while hidden.
view.dom.remove();
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.rs", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
document.body.append(view.dom);
view.dispatch({ effects: viewShown.of(null) });
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when the backend patches another document (a refactoring)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(3));
emitLocalIdeEvent({ type: "docPatched", doc: 9, baseVersion: 1, version: 2, changes: [] });
await settle();
expect(titles(view)).toEqual(["3 usages"]);
});
it("leaves a backend patch of this document to the document change itself", async () => {
editor();
await settle();
const calls = ipc.lspReferences.mock.calls.length;
emitLocalIdeEvent({ type: "docPatched", doc: 7, baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(calls);
});
it("recounts when the plugin document indexes change (an XML statement indexed after its declaration)", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(5));
const { invalidateNavigationProviders } = await import("@/editor/navigationProviders");
invalidateNavigationProviders();
await settle();
expect(titles(view)).toEqual(["5 usages"]);
});
it("recounts when files change on disk or another document closes", async () => {
const view = editor();
await settle();
expect(titles(view)).toEqual(["2 usages"]);
ipc.lspReferences.mockResolvedValue(refs(3));
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: ["/p/b.rs"], removed: [] });
await settle();
expect(titles(view)).toEqual(["3 usages"]);
ipc.lspReferences.mockResolvedValue(refs(4));
_emitEditorEvent({ type: "docClosed", doc: 9, path: "/p/b.rs" });
await settle();
expect(titles(view)).toEqual(["4 usages"]);
});
});
describe("file changes on disk", () => {
const language = (id: string, extensions: string[], languageServers: string[], filenames: string[] = []) =>
({ id, name: id, extensions, filenames, languageServers, uiMode: null }) as never;
const fsChanged = (modified: string[], ignoreRules: string[] = []) =>
emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [], ignoreRules });
async function settledEditors(views: number) {
await loadLanguageInfos({
languages: async () => [
language("rust", ["rs"], ["rust-analyzer"]),
language("log", ["log"], []),
language("dockerfile", [], ["docker-langserver"], ["Dockerfile.*"]),
],
} as never);
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
for (let i = 0; i < views; i++) editor(60);
await settle();
const first = ipc.lspReferences.mock.calls.length;
expect(first).toBe(40 * views);
return first;
}
it.each([1, 4])("asks no new counts for events that no source file caused (%i views)", async (n) => {
const first = await settledEditors(n);
for (let i = 0; i < 10; i++) {
fsChanged(["/p/logo.png"]);
// oxlint-disable-next-line no-await-in-loop -- fake timers must advance one debounce window per file event
await vi.advanceTimersByTimeAsync(1000);
}
fsChanged([], ["/p"]);
fsChanged(["/p/debug.log", "/p/Cargo.lock"]);
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(first);
});
it("recounts once when a source file is among the changed paths", async () => {
const first = await settledEditors(1);
for (let i = 0; i < 5; i++) fsChanged(["/p/logo.png", "/p/b.rs", "/p/debug.log"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
});
it.each([
["a created source file", { created: ["/p/new.rs"], modified: [], removed: [] }],
["a removed source file", { created: [], modified: [], removed: ["/p/old.RS"] }],
["a file the registry matches by name", { created: [], modified: ["/p/Dockerfile.dev"], removed: [] }],
[
"a path without an extension (a folder, or a script found by its first line)",
{ created: [], modified: [], removed: ["/p/src/gen"] },
],
])("recounts for %s", async (_, paths) => {
const first = await settledEditors(1);
emitLocalIdeEvent({ type: "fsChanged", ...paths });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
});
it("recounts for a file Settings › File Types assigns to a language with a server", async () => {
useProject.setState({
settings: {
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } },
files: { fileTypes: { rust: { patterns: ["*.tpl"] } }, fileTypeOverrides: { "/p/x.log": "rust" } },
} as never,
});
const first = await settledEditors(1);
fsChanged(["/p/page.tpl"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
fsChanged(["/p/x.log"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(3 * first);
});
it("recounts for any path while the languages are not loaded", async () => {
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
editor(60);
await settle();
fsChanged(["/p/logo.png"]);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
});
});
describe("inherited Dart lifecycle usages", () => {
const textOf = (src: string) => EditorState.create({ doc: src }).doc;
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() { super.initState(); }",
"",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
"",
" @override",
" void dispose() { super.dispose(); }",
"",
" @override",
" void didUpdateWidget(Page oldWidget) { super.didUpdateWidget(oldWidget); }",
"",
" @override",
" void didChangeDependencies() { super.didChangeDependencies(); }",
"",
" Future<void> loadData() async {}",
"",
" Widget buildHelper() { return const SizedBox(); }",
"",
" @override Widget createState() => this;",
"",
" @override",
" String toString() => 'page';",
"",
" @override",
" int get hashCode => 1;",
"",
" @override",
" bool operator ==(Object other) => other is _PageState;",
"}",
].join("\n");
const doc = textOf(src);
const lineOf = (snippet: string) => src.split("\n").findIndex((l) => l.includes(snippet));
it("skips Flutter @override lifecycle methods, not other Dart names", () => {
expect(skipInheritedLifecycleUsages("dart", "initState", doc, lineOf("void initState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "build", doc, lineOf("Widget build(BuildContext"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "dispose", doc, lineOf("void dispose"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "didUpdateWidget", doc, lineOf("void didUpdateWidget"))).toBe(true);
expect(
skipInheritedLifecycleUsages("dart", "didChangeDependencies", doc, lineOf("void didChangeDependencies")),
).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "createState", doc, lineOf("@override Widget createState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "toString", doc, lineOf("String toString"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "hashCode", doc, lineOf("int get hashCode"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "operator ==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "loadData", doc, lineOf("Future<void> loadData"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "buildHelper", doc, lineOf("Widget buildHelper"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "_PageState", doc, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("rust", "build", doc, lineOf("Widget build(BuildContext"))).toBe(false);
});
it("does not skip a lifecycle name that is not an override", () => {
const plain = textOf("void dispose() {}\nWidget build() { return const SizedBox(); }");
expect(skipInheritedLifecycleUsages("dart", "dispose", plain, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "build", plain, 1)).toBe(false);
});
});
describe("Dart Code Vision references", () => {
const dart = { doc: 11, path: "/p/page.dart", language: "dart", uiMode: "Dart", readOnly: false };
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() {}",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
" Future<void> loadData() async {}",
" void refresh() {}",
"}",
].join("\n");
it("does not query references for @override lifecycle methods", async () => {
ipc.docOutline.mockResolvedValue(
ok([
item("_PageState", "class", 0, [
item("initState", "method", 2),
item("build", "method", 4),
item("loadData", "method", 5),
item("refresh", "method", 6),
]),
]),
);
const view = new EditorView({
state: EditorState.create({
doc: src,
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences.mock.calls.map((c) => c[2])).toEqual([
{ line: 0, col: 0 },
{ line: 5, col: 0 },
{ line: 6, col: 0 },
]);
expect(titles(view)).toEqual(["2 usages", "2 usages", "2 usages"]);
});
it("asks Dart references one at a time", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: 8 }, (_, i) => `void f${i}() {}`).join("\n"),
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(8);
});
it("does not start a new Dart references wave until a cancelled request has finished", async () => {
const first = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(first.promise).mockResolvedValue(refs(2));
ipc.docOutline.mockResolvedValue(ok([item("loadData", "function", 0)]));
const view = new EditorView({
state: EditorState.create({
doc: "void loadData() {}",
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.dart", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
first.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
});