/** * "N usages" code lenses above declarations (IDEA's usages inlay). Cheap by * construction: only declarations in (and near) the viewport are counted, one * debounced pass after edits / scrolling, results cached per document text * and symbol until the project's documents change, and at most a few reference * requests in flight. Dart is the exception: inherited Flutter lifecycle methods * (`@override build`, `initState`, …) resolve to the framework and a single * isolate cannot cancel `textDocument/references` promptly, so those methods are * skipped and remaining Dart counts run one at a time, never overlapping a * request that has not finished. Counts run the same references query the Find Usages * panel runs (including the plugin indexers' anchors), scoped to what the * server analyses: opening candidate files or the libraries for every count * would trigger expensive server analysis, so only an explicit Find Usages * widens the server's scope, and a widened search can find more. Library * sources get no counts (`isLibrarySource`). Beside each count, the declaration's last author from VCS blame (`authorLens`). */ import { Channel } from "@tauri-apps/api/core"; import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { codeLenses, isLibrarySource, onEditorEvent, shownAgain, type CodeLens } from "@/editor/api"; import { onNavigationProvidersChanged } from "@/editor/navigationProviders"; import { executeAction } from "@/platform/actions"; import { commands, nextRequestId, onIdeEvent, type OutlineItem, type Pos, type RequestId, type SymbolKind, } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { debounce, docOf, isUnavailable, lspRequest } from "./lsp"; import { dedupeLocations } from "./navigation"; import { overriddenMethods, overriddenReferences, type OutlineCache } from "./overriddenReferences"; import { posToOffset } from "./positions"; import { featureBackoff, onLspRefresh, onServerSettled } from "./availability"; import { inForeground, onForeground } from "./foreground"; import { editorPrefs } from "@/platform/editorSettings"; import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens"; import { tx } from "@/platform/i18n"; import { languageInfo, languagesForPath } from "@/editor/core/cm/languages"; import { overrideKey, userFileType, validateFileTypeOverrides, validateFileTypes } from "@/platform/fileTypes"; import { showFileUsages } from "@/editor/refactor"; const LENS_KINDS = new Set([ "class", "interface", "struct", "enum", "trait", "function", "method", "constructor", "typeAlias", "macro", ]); const MAX_PER_PASS = 40; const CONCURRENCY = 4; /** The Dart analyzer is a single isolate; overlapping references stall completion. */ const DART_CONCURRENCY = 1; /** Lines above/below the viewport that are counted too, so scrolling feels instant. */ const MARGIN_LINES = 10; /** * Passes that ask again for a count that came back incomplete. Servers call an empty answer * incomplete while any of their progress runs, and jdtls reports progress for a few * milliseconds around many requests without settling afterwards. */ const INCOMPLETE_RETRIES = 3; const usagesBackoff = featureBackoff(); /** * Whether a change on disk can alter a reference count: some changed path is a file a language * server analyses. A path no language claims counts too when it has no extension (a folder, or a * script told by its first line), and so does any path while the languages are not loaded: a * missed recount leaves a stale number, an extra one only repeats a pass. */ function touchesSource(e: { created: string[]; modified: string[]; removed: string[] }): boolean { const { settings, project } = useProject.getState(); const assoc = validateFileTypes(settings?.files?.fileTypes); const overrides = validateFileTypeOverrides(settings?.files?.fileTypeOverrides); const root = project?.root ?? null; const served = (l: { languageServers?: string[] }) => !!l.languageServers?.length; const isSource = (path: string) => { const name = path.slice(path.lastIndexOf("/") + 1); const assigned = overrides[overrideKey(path, root)] ?? userFileType(assoc, name); if (assigned) { const info = languageInfo(assigned); return !info || served(info); } const languages = languagesForPath(path); if (!languages) return true; return languages.length ? languages.some(served) : name.lastIndexOf(".") <= 0; }; return e.created.some(isSource) || e.modified.some(isSource) || e.removed.some(isSource); } export interface LensTarget { name: string; /** 0-based line / UTF-16 col of the identifier. */ line: number; col: number; /** 0-based lines of the whole declaration. */ startLine: number; endLine: number; } /** Servers name callbacks and anonymous functions (``, `map() callback`); they have no usages. */ const anonymous = (name: string) => /^<.*>$/.test(name) || / callback$/.test(name); /** Declarations worth a usages lens, in document order. Exported for tests. */ export function lensTargets(items: readonly OutlineItem[]): LensTarget[] { const out: LensTarget[] = []; const walk = (list: readonly OutlineItem[]) => { for (const it of list) { if (LENS_KINDS.has(it.kind) && !anonymous(it.name)) out.push({ name: it.name, line: it.selection_range.start.line, // A CSS selector (`.button`): the name past `.` / `#`, where CSS Modules Kit maps the class. col: it.selection_range.start.col + (/^[.#][\w-]/.test(it.name) ? 1 : 0), startLine: it.range.start.line, endLine: it.range.end.line, }); if (it.children.length) walk(it.children); } }; walk(items); const seen = new Set(); return out .sort((a, b) => a.line - b.line || a.col - b.col) .filter((t) => (seen.has(t.line) ? false : (seen.add(t.line), true))); } export function usagesLabel(n: number): string { if (n === 0) return tx("no usages"); return n === 1 ? tx("1 usage") : tx`${n} usages`; } /** * Flutter / Dart `@override` lifecycle and Object methods. A references query * for any of them walks the framework (and the project) from the superclass. */ const DART_INHERITED_LIFECYCLE = new Set([ "build", "createState", "initState", "dispose", "didUpdateWidget", "didChangeDependencies", "deactivate", "activate", "reassemble", "toString", "hashCode", "==", ]); /** Outline names for `operator ==` (`==`, `operator ==`). */ function dartMethodName(name: string): string { return name.replace(/^operator\s+/, "").trim(); } /** * Whether Code Vision should skip a usages query for this declaration: a Dart * method whose name is a framework lifecycle / Object member, with `@override` * on or just above the name. Exported for tests. */ export function skipInheritedLifecycleUsages(language: string, name: string, text: Text, line: number): boolean { if (language !== "dart") return false; if (!DART_INHERITED_LIFECYCLE.has(dartMethodName(name))) return false; const from = Math.max(1, line + 1 - 4); const to = Math.min(text.lines, line + 1); for (let n = from; n <= to; n++) { if (/@override\b/.test(text.line(n).text)) return true; } return false; } const setLenses = StateEffect.define(); const lensField = StateField.define({ create: () => [], update(lenses, tr) { for (const e of tr.effects) if (e.is(setLenses)) return e.value; if (!tr.docChanged || !lenses.length) return lenses; // Keep lenses on their lines while typing; drop ones whose line was deleted. const out: CodeLens[] = []; for (const l of lenses) { const pos = tr.changes.mapPos(l.pos, -1, MapMode.TrackDel); if (pos !== null) out.push({ ...l, pos }); } return out; }, provide: (f) => codeLenses.from(f), }); const usagesEnabled = () => editorPrefs().inlay.codeVision && editorPrefs().inlay.codeVisionUsages; const authorEnabled = () => editorPrefs().inlay.codeVision && editorPrefs().inlay.codeVisionAuthor; /** The author hint runs Annotate with Git Blame: it shows the file's annotations, or closes them when shown. */ function toggleAnnotations(view: EditorView) { view.focus(); void executeAction("vcs.annotate"); } function openUsages(view: EditorView, offset: number) { view.dispatch({ selection: EditorSelection.cursor(offset), userEvent: "select.lens" }); view.focus(); void executeAction("find.showUsages"); } class UsagesLensPlugin { private schedule = debounce(() => void this.run(), 900); /** `${line}:${col}:${name}` → count, valid for `cacheDoc`. */ private cache = new Map(); private cacheDoc: Text | null = null; private outline: { doc: Text; items: OutlineItem[]; targets: LensTarget[] } | null = null; private generation = 0; private pending = new Set(); /** Keys whose count came back incomplete (the server was indexing): not shown, asked again once it settles. */ private incomplete = new Set(); /** Times each key's count came back incomplete, for the passes that ask again before it settles. */ private retries = new Map(); private unsubscribe: () => void; private offReady: () => void; private offSettled: () => void; private offBlame: () => void; private offChanges: () => void; private offNavigation: () => void; private skipped = false; /** A pass was cut short or held back by a foreground request, and runs once it is done. */ private yielded = false; /** Reference requests still running on the server, including ones already cancelled. */ private inflight = 0; /** A Dart pass is waiting for `inflight` to reach 0 before asking again. */ private drain = false; private closed = false; constructor(private view: EditorView) { this.refresh(); this.unsubscribe = useProject.subscribe((s, prev) => { if (s.settings !== prev.settings) this.refresh(); }); // Counts computed while the server was indexing may be incomplete. this.offReady = onLspRefresh("codeLens", () => this.invalidate()); this.offSettled = onServerSettled(() => { if (!this.incomplete.size) return; this.incomplete.clear(); this.retries.clear(); this.refresh(); }); this.offBlame = onBlameInvalidated(() => this.refresh()); // Requests the user waits for go first (Go to Declaration, ⌥↵, a refactoring): counts search // the whole project on the same server, so in-flight ones are cancelled and asked again once // the user's request is done. this.offNavigation = onForeground((foreground) => { if (foreground) { if (!this.pending.size) return; this.cancel(); this.yielded = true; } else if (this.yielded) { this.yielded = false; this.schedule(); } }); // Counts cover the whole project, so a change anywhere can outdate them // while this view is hidden and skips its passes: another document's edit // (the call sites) or a closed unsaved buffer, a backend patch (a // refactoring), a file changed on disk, or a plugin index batch (an XML // statement is indexed after its Java declaration). This view's own edits // already refresh through `update`. const offDocs = onEditorEvent((e) => { if (e.type === "docChanged" && e.doc !== docOf(this.view)?.doc) this.invalidate(); else if (e.type === "docClosed") this.invalidate(); }); const offPatches = onIdeEvent("docPatched", (e) => { if (e.doc !== docOf(this.view)?.doc) this.invalidate(); }); const offBackend = [ onIdeEvent("workspaceEditApplied", () => this.invalidate()), onIdeEvent("fsChanged", (e) => { if (touchesSource(e)) this.invalidate(); }), onNavigationProvidersChanged(() => this.invalidate()), ]; this.offChanges = () => { offDocs(); offPatches(); offBackend.forEach((off) => off()); }; } /** Counts are cached until anything in the project may have changed them. */ private invalidate() { this.cache.clear(); this.incomplete.clear(); this.retries.clear(); this.refresh(); } update(u: ViewUpdate) { // A re-shown tab ran nothing while hidden, and its counts may have been // invalidated meanwhile; when they are cached the pass only redraws. if (u.docChanged || u.viewportChanged || shownAgain(u)) this.refresh(); } private cancel() { this.generation++; for (const id of this.pending) void commands.cancelRequest(id).catch(() => {}); this.pending.clear(); } private refresh() { this.cancel(); this.schedule(); } private async run() { const view = this.view; this.skipped = !view.dom.isConnected; if (this.skipped) return; const doc = docOf(view); if (!doc) return; if (inForeground()) { this.yielded = true; return; } // Dart's analyzer does not cancel promptly; a new wave on top of a cancelled one stalls it. if (doc.language === "dart" && this.inflight > 0) { this.drain = true; return; } const gen = this.generation; const usagesWanted = usagesEnabled() && !isLibrarySource(doc); const usages = usagesWanted && !usagesBackoff.active(doc.doc); const authors = authorEnabled() && !doc.virtual; if (!usagesWanted && !authors) { if (view.state.field(lensField).length) view.dispatch({ effects: setLenses.of([]) }); return; } const text = view.state.doc; const wanted = () => gen === this.generation && view.state.doc === text; // Blame runs beside the reference requests; it never holds up the counts. const blame = authors ? blameFor(doc.path, text) : Promise.resolve(null); if (this.cacheDoc !== text) { this.cache = new Map(); this.incomplete = new Set(); this.retries = new Map(); this.cacheDoc = text; } try { if (this.outline?.doc !== text) { const items = await lspRequest(() => commands.docOutline(doc.doc), wanted); if (!wanted()) return; this.outline = { doc: text, items, targets: lensTargets(items) }; } const { from, to } = view.viewport; const firstLine = Math.max(0, text.lineAt(from).number - 1 - MARGIN_LINES); const lastLine = text.lineAt(to).number - 1 + MARGIN_LINES; const visible = this.outline.targets .filter((t) => t.line >= firstLine && t.line <= lastLine) .slice(0, MAX_PER_PASS); const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`; const todo = usages ? visible.filter( (t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t)) && !skipInheritedLifecycleUsages(doc.language, t.name, text, t.line), ) : []; let unavailable = false; let retry = false; // A base file is outlined once per pass, however many of its methods are overridden here. const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]); const concurrency = doc.language === "dart" ? DART_CONCURRENCY : CONCURRENCY; for (let i = 0; i < todo.length && !unavailable; i += concurrency) { if (inForeground()) { this.yielded = true; return; } if (!wanted()) return; // oxlint-disable-next-line no-await-in-loop -- batched in groups of CONCURRENCY; a batch's flags decide whether the next batch runs await Promise.all( todo.slice(i, i + concurrency).map(async (t) => { const request = nextRequestId(); this.inflight++; try { // Opening candidate files for each count triggers expensive server analysis. // Only an explicit Find Usages should widen the server's scope. const references = (target: number, at: Pos) => lspRequest(() => { this.pending.add(request); return commands.lspReferences(request, target, at, false, false, false, new Channel()); }, wanted); const at = { line: t.line, col: t.col }; const own = await references(doc.doc, at); if (!wanted()) return; const methods = await overriddenMethods(doc.path, doc.doc, at, outlines); const inherited = await overriddenReferences(methods, references); const refs = inherited.length ? dedupeLocations([own, ...inherited].flatMap((r) => r.locations)) : own.locations; const incomplete = [own, ...inherited].some((r) => r.incomplete); if (wanted()) { if (!incomplete) this.cache.set(key(t), refs.length); else { const tries = (this.retries.get(key(t)) ?? 0) + 1; this.retries.set(key(t), tries); if (tries > INCOMPLETE_RETRIES) this.incomplete.add(key(t)); else retry = true; } } } catch (e) { if (wanted() && isUnavailable(e)) unavailable = true; } finally { this.pending.delete(request); this.inflight--; if (this.inflight === 0 && this.drain && !this.closed) { this.drain = false; this.schedule(); } } }), ); if (!wanted()) return; } if (unavailable) usagesBackoff.mark(doc.doc); if (retry) this.schedule(); const lines = await blame; if (!wanted()) return; // Usages lenses already shown (the field keeps them on their lines through // edits): reused when a target's count is still computing or came back // incomplete while the server was busy, so the row doesn't blink away and // shift the layout below it. const shown = new Map(); for (const l of view.state.facet(codeLenses)) { if (l.kind === "usages") shown.set(view.state.doc.lineAt(l.pos).number - 1, l); } const allowNoUsages = editorPrefs().inlay.codeVisionNoUsages; const lenses: CodeLens[] = []; // WebStorm's Code Vision on a Vue single-file component: its usages from other files, on request. if (usagesWanted && doc.language === "vue" && !doc.virtual) { const path = doc.path; lenses.push({ pos: 0, title: tx("Show component usages"), tooltip: tx("Find where this component is imported and used"), order: 5, kind: "usages", run: () => void showFileUsages(path), }); } for (const t of visible) { const offset = posToOffset(text, { line: t.line, col: t.col }); const who = lines && authorSummary(lines, t.startLine, t.endLine); if (who) lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20, kind: "author", run: toggleAnnotations, }); const n = usages ? this.cache.get(key(t)) : undefined; if (n !== undefined) { if (n === 0 && !allowNoUsages) continue; const run: NonNullable = (v) => { const current = v.state.facet(codeLenses).find((l) => l.run === run); if (current) openUsages(v, Math.min(current.pos, v.state.doc.length)); }; lenses.push({ pos: offset, title: usagesLabel(n), tooltip: tx`Show usages of ${t.name}`, order: 10, kind: "usages", run, }); continue; } // No fresh count: keep the lens already shown (with its mapped position) // until a complete answer replaces it. if (!usagesWanted) continue; const stale = shown.get(t.line); if (stale && (allowNoUsages || stale.title !== usagesLabel(0))) lenses.push(stale); } if (!sameLenses(view.state.field(lensField), lenses)) view.dispatch({ effects: setLenses.of(lenses) }); } catch (e) { if (wanted() && isUnavailable(e)) usagesBackoff.mark(doc.doc); } } destroy() { this.closed = true; this.schedule.cancel(); this.unsubscribe(); this.offReady(); this.offSettled(); this.offBlame(); this.offChanges(); this.offNavigation(); this.cancel(); } } function sameLenses(a: readonly CodeLens[], b: readonly CodeLens[]) { return ( a.length === b.length && a.every((l, i) => l.pos === b[i]!.pos && l.title === b[i]!.title && l.tooltip === b[i]!.tooltip) ); } export function usagesLensExtension(): Extension { return [lensField, ViewPlugin.fromClass(UsagesLensPlugin)]; }