дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
fix(editor): resolve C declarations without include metadata (#6959)
Without a compilation database clangd leaves nested includes unresolved or answers with the call site itself. For C-family files an empty or self-only answer falls back to syntax and the project index (including identifiers in macro bodies), Go to Implementation from a header finds the source definition, and member access is never guessed by bare name. Co-authored-by: sonnartliao <[email protected]>
Цей коміт міститься в:
1 джерело
08249ca5fd
коміт
4c71299745
13 files changed
+446
-20
No files matched your search
@@ -66,6 +66,8 @@ import {
|
||||
isDeclarationName,
|
||||
isSelfTarget,
|
||||
localHighlights,
|
||||
projectIndexDefinitions,
|
||||
usageRole,
|
||||
type DeclarationTarget,
|
||||
} from "./syntaxFallback";
|
||||
import { showHint, showPendingHint } from "./hint";
|
||||
@@ -112,6 +114,27 @@ export async function navigateTo(loc: Location) {
|
||||
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
|
||||
}
|
||||
|
||||
const CLANGD_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]);
|
||||
const CLANGD_SYNTAX_NOTE = "Based on syntax and the project index";
|
||||
const C_HEADER = /\.(?:h|hh|hpp|hxx|h\+\+)$/i;
|
||||
|
||||
/** `pki_check_bin` for `.../pki_check_bin.h`: the stem a source counterpart shares. */
|
||||
function fileStem(path: string): string {
|
||||
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
const dot = name.lastIndexOf(".");
|
||||
return (dot > 0 ? name.slice(0, dot) : name).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* `pki_check_bin.c` for `pki_check_bin.h`, or every source when no stem matches: the same
|
||||
* declaration can be implemented in another component (a kernel tree holds many copies).
|
||||
*/
|
||||
function counterpartSources(header: string, sources: readonly DeclarationTarget[]): readonly DeclarationTarget[] {
|
||||
const stem = fileStem(header);
|
||||
const own = sources.filter((l) => fileStem(l.path) === stem);
|
||||
return own.length ? own : sources;
|
||||
}
|
||||
|
||||
const NOT_FOUND: Record<GotoKind, string> = {
|
||||
definition: "Cannot find declaration to go to",
|
||||
declaration: "Cannot find declaration to go to",
|
||||
@@ -373,6 +396,18 @@ async function onDeclarationName(view: EditorView, offset: number): Promise<bool
|
||||
return isDeclarationName(at);
|
||||
}
|
||||
|
||||
/** Whether the caret is on a function call, not a declaration whose self-target is legitimate. */
|
||||
async function onCallName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return usageRole(at) === "call";
|
||||
}
|
||||
|
||||
/** A C-family member must come from its receiver's type, not a project-wide bare-name lookup. */
|
||||
async function onMemberName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return at?.node.kind === "field_identifier" || at?.node.kind === "property_identifier";
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Implementation targets for Python from the IDE's inheritance graph: its servers
|
||||
* declare no type hierarchy and analyse one root, so the graph also knows the attached
|
||||
@@ -400,7 +435,20 @@ async function implementationFallbackTargets(
|
||||
pos: Pos,
|
||||
): Promise<readonly DeclarationTarget[]> {
|
||||
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
|
||||
return declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
const targets = declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
if (targets.length) return targets;
|
||||
const doc = docOf(view);
|
||||
if (!doc || !CLANGD_LANGUAGES.has(doc.language)) return targets;
|
||||
// Without a compilation database clangd only sees this header. Look the name up in the
|
||||
// project index for a source definition; never offer another header declaration.
|
||||
const name = nameAt(view, offset) ?? (offset > 0 ? nameAt(view, offset - 1) : null);
|
||||
if (!name) return targets;
|
||||
const indexed = await projectIndexDefinitions(path, name, "call").catch(() => []);
|
||||
const sources = indexed.filter((l) => !isSelfTarget([l], path, pos) && !C_HEADER.test(l.path));
|
||||
if (!sources.length) return targets;
|
||||
// The caret's own header names the source that implements it: its stem picks that source
|
||||
// among same-name definitions elsewhere instead of turning the jump into a chooser.
|
||||
return C_HEADER.test(path) ? counterpartSources(path, sources) : sources;
|
||||
}
|
||||
|
||||
/** Whether `line` (0-based) of `text` is an import statement. */
|
||||
@@ -495,6 +543,7 @@ async function gotoResolved(
|
||||
const pos = offsetToPos(view.state.doc, offset);
|
||||
let locs: DeclarationTarget[];
|
||||
let fromSyntax = false;
|
||||
let syntaxNote = SYNTAX_NOTE;
|
||||
const declaration = kind === "definition" || kind === "declaration";
|
||||
// A segment of an import path names a file — possibly in a dependency project, which
|
||||
// neither the single-root server nor the name index resolves.
|
||||
@@ -580,6 +629,35 @@ async function gotoResolved(
|
||||
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
|
||||
if (superseded()) return;
|
||||
locs = dedupeLocations(declarationTargets);
|
||||
if (declarationTargets.some((target) => target.name && target.kind)) {
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
// Without a compilation database clangd may not resolve nested #include files. Its empty
|
||||
// answer is not authoritative for these languages; the project index still has the local
|
||||
// declarations. An implicit C declaration can also point at the call itself: replace that
|
||||
// pseudo target only when syntax and the index provide a real target elsewhere.
|
||||
if (declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) {
|
||||
const selfTargets = locs.length > 0 && locs.every((l) => isSelfTarget([l], doc.path, pos));
|
||||
if (!locs.length || (selfTargets && (await onCallName(doc, pos)))) {
|
||||
const fallback = await gotoFallback(view, doc, pos, false);
|
||||
if (fallback?.length) {
|
||||
if (!locs.length) {
|
||||
locs = fallback;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
} else {
|
||||
const elsewhere = fallback.filter((l) => !isSelfTarget([l], doc.path, pos));
|
||||
if (elsewhere.length) {
|
||||
locs = elsewhere;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (superseded()) return;
|
||||
}
|
||||
if (!locs.length) {
|
||||
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
|
||||
@@ -600,8 +678,12 @@ async function gotoResolved(
|
||||
}
|
||||
// The server only resolves what it sees: answer from the project index, which also
|
||||
// covers attached dependency projects (an unresolved import into them). Never for a
|
||||
// module path: a segment is not a symbol name.
|
||||
if (declaration && !fromSyntax && !moduleName) {
|
||||
// module path: a segment is not a symbol name. A C-family member needs its receiver's
|
||||
// type, so a bare-name dependency lookup would be a guess here too.
|
||||
const clangMember =
|
||||
declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (superseded()) return;
|
||||
if (declaration && !fromSyntax && !moduleName && !clangMember) {
|
||||
const name = nameAt(view, offset);
|
||||
const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : [];
|
||||
if (targets.length) {
|
||||
@@ -687,7 +769,7 @@ async function gotoResolved(
|
||||
setTimeout(() => {
|
||||
if (superseded()) return;
|
||||
const target = activeEditor()?.view;
|
||||
if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 });
|
||||
if (target) showHint(target, syntaxNote, { timeout: 2500 });
|
||||
}, 150);
|
||||
return;
|
||||
}
|
||||
@@ -775,11 +857,16 @@ async function followReferenceAt(
|
||||
}
|
||||
|
||||
/** Declaration targets from the structure service; null when it cannot answer for this file. */
|
||||
async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): Promise<DeclarationTarget[] | null> {
|
||||
async function gotoFallback(
|
||||
view: EditorView,
|
||||
doc: EditorDocContext,
|
||||
pos: Pos,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationTarget[] | null> {
|
||||
try {
|
||||
await whenSynced(view);
|
||||
const text = view.state.doc;
|
||||
const fb = await declarationFallback(doc, text, pos);
|
||||
const fb = await declarationFallback(doc, text, pos, undefined, allowMember);
|
||||
return fb.kind === "unsupported" ? null : fb.targets;
|
||||
} catch (e) {
|
||||
console.debug("[syntax] declaration fallback", e);
|
||||
@@ -936,11 +1023,14 @@ async function probeNavigation(
|
||||
navigable = !!(await gotoFallback(view, doc, pos))?.length;
|
||||
fromSyntax = true;
|
||||
}
|
||||
if (!navigable && !fromSyntax && CLANGD_LANGUAGES.has(doc.language))
|
||||
navigable = !!(await gotoFallback(view, doc, pos, false))?.length;
|
||||
if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual)
|
||||
navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length;
|
||||
// The index answers across dependency roots too (unresolved imports), but a module path
|
||||
// segment is a file rather than a name.
|
||||
if (!navigable && !fromSyntax) {
|
||||
// segment is a file rather than a name. Keep member probing consistent with the click path.
|
||||
const clangMember = !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (!navigable && !fromSyntax && !clangMember) {
|
||||
const moduleName = importModuleName(view, doc, offset);
|
||||
if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null));
|
||||
else {
|
||||
|
||||
@@ -3,9 +3,11 @@ import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
|
||||
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
|
||||
const { lspGoto, lspGotoImplementation, findSymbols, navIndexDefinitions } = vi.hoisted(() => ({
|
||||
lspGoto: vi.fn<typeof commands.lspGoto>(),
|
||||
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
|
||||
findSymbols: vi.fn<typeof commands.findSymbols>(),
|
||||
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
@@ -17,7 +19,15 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
|
||||
commands: {
|
||||
...real.commands,
|
||||
lspGoto,
|
||||
lspGotoImplementation,
|
||||
findSymbols,
|
||||
navIndexDefinitions,
|
||||
fsReadText,
|
||||
navInheritance,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
@@ -60,6 +70,8 @@ beforeEach(() => {
|
||||
invalidateConfigurationNavigation();
|
||||
lspGoto.mockResolvedValue(ok([]));
|
||||
lspGotoImplementation.mockResolvedValue(ok([]));
|
||||
findSymbols.mockResolvedValue({ status: "ok", data: [] });
|
||||
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] });
|
||||
view = editor(TEXT, "go", "/p/store.go");
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -154,4 +166,94 @@ describe("Go to Implementation on a symbol nothing implements", () => {
|
||||
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
|
||||
});
|
||||
|
||||
it("finds a C source definition from the project index when clangd only returns the header", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [symbol("/p/pki_check_bin.h", 0), symbol("/p/pki_check_bin.c", 190)],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(findSymbols).toHaveBeenCalledWith(name, "all", 500);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/pki_check_bin.c", { selection: { line: 190, col }, focus: true });
|
||||
expect(navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not treat another header declaration as a C implementation", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path: "/p/other.h",
|
||||
relPath: "p/other.h",
|
||||
range,
|
||||
score: 1,
|
||||
indices: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
|
||||
});
|
||||
|
||||
it("prefers the header's own source among same-name definitions elsewhere", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
symbol("/p/pki_check_bin.h", 0),
|
||||
symbol("/p/pki_check_bin.c", 190),
|
||||
symbol("/kernel/5.15/gvt/firmware.c", 149),
|
||||
symbol("/kernel/5.4/gvt/firmware.c", 154),
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/pki_check_bin.c", {
|
||||
selection: { line: 190, col },
|
||||
focus: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,8 @@ const { gotoTargets, navigationExtension, highlightUsages } = await import("./na
|
||||
const { registerNavigationProvider } = await import("@/editor/navigationProviders");
|
||||
const { startRename, renameNamePart } = await import("./rename");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
const { inplaceRenameExtension, inplaceSession } = await import("./inplaceRename");
|
||||
@@ -211,6 +213,36 @@ describe("declarationFallback", () => {
|
||||
expect(res).toMatchObject({ kind: "targets", ambiguous: true });
|
||||
});
|
||||
|
||||
it("can reject a member reported by locals without querying the index", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }, undefined, false);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.syntaxNodeAt).not.toHaveBeenCalled();
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("can reject a C field node when locals are unavailable", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("field_identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(
|
||||
{ ...doc, language: "c-fields" },
|
||||
text,
|
||||
{ line: 1, col: 7 },
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a no-identifier answer empty outside macro replacement bodies", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the node text for languages without locals, and gives up without a grammar", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
@@ -345,6 +377,174 @@ describe("navigation wiring", () => {
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to");
|
||||
});
|
||||
|
||||
function clangCall(language: string, name = "indirect_call") {
|
||||
const text = `#include "direct.h"\nint main(void) { return ${name}(); }\n`;
|
||||
const path = language === "cpp" || language === "objective-cpp" ? "/p/main.cpp" : "/p/main.c";
|
||||
const col = text.split("\n")[1]!.indexOf(name);
|
||||
const range = r(1, col, col + name.length);
|
||||
const at: NodeAt = {
|
||||
node: node("identifier", range, "function"),
|
||||
ancestors: [node("call_expression", r(1, 0, text.split("\n")[1]!.length))],
|
||||
};
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name, range, reason: "topLevel" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
const view = editor(text, language, text.indexOf(name) + 2, path);
|
||||
return { view, path, range, at, name };
|
||||
}
|
||||
|
||||
it.each(["c", "cpp", "objective-c", "objective-cpp"])(
|
||||
"uses the local project index when clangd cannot resolve a nested include in %s",
|
||||
async (language) => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall(language);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/include/indirect.h", { selection: { line: 3, col: 4 }, focus: true });
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves a function name inside a C macro replacement body", async () => {
|
||||
const name = "sys_util_read_content";
|
||||
const text = `#define jy_read_country(buf, len) ${name}(FACTORY_DIR "country_code", buf, len)\n`;
|
||||
const col = text.indexOf(name);
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("preproc_arg", r(0, col, text.length - 1), "value"),
|
||||
ancestors: [node("preproc_function_def", r(0, 0, text.length - 1))],
|
||||
}),
|
||||
);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
const view = editor(text, "c", col + 2, "/p/jy_lib.h");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("underlines a nested-include call when the hover probe uses the same index fallback", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
const offset = view.state.doc.toString().indexOf(name) + 2;
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(offset);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces clangd's implicit-declaration self target with the indexed declaration", async () => {
|
||||
const { view, path, range, at, name } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a legitimate declaration self target instead of replacing it from the index", async () => {
|
||||
const name = "indirect_call";
|
||||
const range = r(0, 4, 4 + name.length);
|
||||
const path = "/p/main.c";
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("identifier", range, "declarator"),
|
||||
ancestors: [node("function_declarator", r(0, 0, 4 + name.length + 8))],
|
||||
}),
|
||||
);
|
||||
const view = editor(`int ${name}(void) { return 0; }\n`, "c", 6, path);
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps clangd's original self target when the local index has no better answer", async () => {
|
||||
const { view, path, range, at } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not guess a C member declaration from unrelated project symbols", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)).mockReturnValueOnce(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
try {
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("does not underline a C member from a bare-name dependency candidate", async () => {
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.lspGoto.mockReturnValue(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(5);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(cmd.syntaxNodeAt).toHaveBeenCalled());
|
||||
expect(view.dom.querySelector(".cm-lsp-link")).toBeNull();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
cmd.lspGoto.mockReturnValue(unavailable());
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(null));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("shows ambiguous nested-include declarations as syntax-based candidates", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/a.c"), sym(name, "function", "/p/include/a.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind).toBe("list");
|
||||
if (popup?.kind !== "list") return;
|
||||
expect(popup.title).toBe(`Choose Declaration of ${name} (2 found, based on syntax)`);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers from the index when the server cannot resolve an import into a dependency project", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")]));
|
||||
|
||||
@@ -154,6 +154,20 @@ export async function indexDefinitions(path: string, name: string): Promise<Decl
|
||||
);
|
||||
}
|
||||
|
||||
/** Exact-name declarations from the whole project index, filtered by use and language family. */
|
||||
export async function projectIndexDefinitions(
|
||||
path: string,
|
||||
name: string,
|
||||
role: UsageRole,
|
||||
): Promise<DeclarationTarget[]> {
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(path, s.path));
|
||||
return rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Declaration without a language server: a certain local definition,
|
||||
* otherwise project index symbols with exactly that name (filtered by the
|
||||
@@ -164,32 +178,43 @@ export async function declarationFallback(
|
||||
text: Text,
|
||||
pos: Pos,
|
||||
signal?: AbortSignal,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationFallback> {
|
||||
const support = await structure.support(doc.language);
|
||||
if (!support.tree) return { kind: "unsupported" };
|
||||
let locals: Locals | null = null;
|
||||
if (support.locals) locals = await structure.locals(doc.doc, pos, { signal });
|
||||
if (locals?.status === "noIdentifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (locals?.status === "local") return { kind: "targets", ...localTargets(doc.path, locals.symbol) };
|
||||
if (!allowMember && locals?.status === "notLocal" && locals.reason === "member")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }, { signal });
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at);
|
||||
if (locals?.status === "noIdentifier" && at?.node.kind !== "preproc_arg")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (!allowMember && at?.node.kind === "field_identifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at, pos);
|
||||
if (!name) return { kind: "targets", targets: [], ambiguous: false };
|
||||
// A member (`obj.name`) can be any member of that name; only a plain name has a syntactic role.
|
||||
const role = locals?.status === "notLocal" && locals.reason === "member" ? "other" : usageRole(at);
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(doc.path, s.path));
|
||||
const targets = rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
doc.path,
|
||||
);
|
||||
const targets = await projectIndexDefinitions(doc.path, name, role);
|
||||
return { kind: "targets", targets, ambiguous: targets.length > 1 };
|
||||
}
|
||||
|
||||
const IDENT = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
||||
const IDENT_PART = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Name of a leaf identifier node (languages without `locals.scm`). */
|
||||
function identifierText(text: Text, at: NodeAt | null): string | null {
|
||||
/** Name of a leaf identifier node, or the identifier at `pos` in a macro replacement body. */
|
||||
function identifierText(text: Text, at: NodeAt | null, pos: Pos): string | null {
|
||||
if (at?.node.kind === "preproc_arg") {
|
||||
if (pos.line >= text.lines) return null;
|
||||
const line = text.line(pos.line + 1).text;
|
||||
let from = Math.min(pos.col, line.length);
|
||||
let to = from;
|
||||
while (from > 0 && IDENT_PART.test(line[from - 1]!)) from--;
|
||||
while (to < line.length && IDENT_PART.test(line[to]!)) to++;
|
||||
const name = line.slice(from, to);
|
||||
return IDENT.test(name) ? name : null;
|
||||
}
|
||||
if (!at || !/identifier|^name$|^constant$|^word$/.test(at.node.kind)) return null;
|
||||
const { from, to } = rangeToOffsets(text, at.node.range);
|
||||
const name = text.sliceString(from, to);
|
||||
|
||||
@@ -299,6 +299,7 @@
|
||||
"Base interpreter": "Intérprete base",
|
||||
"Base interpreter:": "Intérprete base:",
|
||||
"Based on syntax (language server not ready)": "Basado en sintaxis (el servidor de lenguaje no está listo)",
|
||||
"Based on syntax and the project index": "Basado en sintaxis y el índice del proyecto",
|
||||
"Behavior": "Comportamiento",
|
||||
"Benchmark function": "Función de benchmark",
|
||||
"Binary response": "Respuesta binaria",
|
||||
|
||||
@@ -255,6 +255,7 @@
|
||||
"Base interpreter": "Interpréteur de base",
|
||||
"Base interpreter:": "Interpréteur de base :",
|
||||
"Based on syntax (language server not ready)": "D'après la syntaxe (serveur de langage pas encore prêt)",
|
||||
"Based on syntax and the project index": "D'après la syntaxe et l'index du projet",
|
||||
"Behavior": "Comportement",
|
||||
"Benchmark function": "Fonction de benchmark",
|
||||
"Binary response": "Réponse binaire",
|
||||
|
||||
@@ -335,6 +335,7 @@
|
||||
"Base interpreter": "기본 인터프리터",
|
||||
"Base interpreter:": "기본 인터프리터:",
|
||||
"Based on syntax (language server not ready)": "구문 기반(언어 서버가 준비되지 않음)",
|
||||
"Based on syntax and the project index": "구문 및 프로젝트 인덱스 기반",
|
||||
"Behavior": "동작",
|
||||
"Benchmark function": "벤치마크 함수",
|
||||
"Binary response": "바이너리 응답",
|
||||
|
||||
@@ -291,6 +291,7 @@
|
||||
"Base interpreter": "Interpreter bazowy",
|
||||
"Base interpreter:": "Interpreter bazowy:",
|
||||
"Based on syntax (language server not ready)": "Na podstawie składni (serwer językowy nie jest gotowy)",
|
||||
"Based on syntax and the project index": "Na podstawie składni i indeksu projektu",
|
||||
"Behavior": "Zachowanie",
|
||||
"Benchmark function": "Funkcja benchmarku",
|
||||
"Binary response": "Odpowiedź binarna",
|
||||
|
||||
@@ -291,6 +291,7 @@
|
||||
"Base interpreter": "Interpretador base",
|
||||
"Base interpreter:": "Interpretador base:",
|
||||
"Based on syntax (language server not ready)": "Baseado na sintaxe (servidor de linguagem não pronto)",
|
||||
"Based on syntax and the project index": "Baseado na sintaxe e no índice do projeto",
|
||||
"Behavior": "Comportamento",
|
||||
"Benchmark function": "Função de benchmark",
|
||||
"Binary response": "Resposta binária",
|
||||
|
||||
@@ -1248,6 +1248,7 @@
|
||||
"Base interpreter": "Базовый интерпретатор",
|
||||
"Base interpreter:": "Базовый интерпретатор:",
|
||||
"Based on syntax (language server not ready)": "На основе синтаксиса (языковой сервер не готов)",
|
||||
"Based on syntax and the project index": "На основе синтаксиса и индекса проекта",
|
||||
"Behavior": "Поведение",
|
||||
"Benchmark function": "Функция бенчмарка",
|
||||
"Binary response": "Двоичный ответ",
|
||||
|
||||
@@ -3092,6 +3092,7 @@
|
||||
"Base interpreter": "Temel yorumlayıcı",
|
||||
"Base interpreter:": "Temel yorumlayıcı:",
|
||||
"Based on syntax (language server not ready)": "Sözdizimine göre (dil sunucusu hazır değil)",
|
||||
"Based on syntax and the project index": "Sözdizimine ve proje dizinine göre",
|
||||
"Behavior": "Davranış",
|
||||
"Benchmark function": "Performans testi fonksiyonu",
|
||||
"Binary response": "İkili yanıt",
|
||||
|
||||
@@ -936,6 +936,7 @@
|
||||
"Base interpreter": "基礎直譯器",
|
||||
"Base interpreter:": "基礎直譯器:",
|
||||
"Based on syntax (language server not ready)": "基於語法(語言伺服器尚未就緒)",
|
||||
"Based on syntax and the project index": "基於語法和專案索引",
|
||||
"Behavior": "行為",
|
||||
"Benchmark function": "基準測試函式",
|
||||
"Binary response": "二進位制回應",
|
||||
|
||||
@@ -1395,6 +1395,7 @@
|
||||
"Base interpreter": "基础解释器",
|
||||
"Base interpreter:": "基础解释器:",
|
||||
"Based on syntax (language server not ready)": "基于语法(语言服务器尚未就绪)",
|
||||
"Based on syntax and the project index": "基于语法和项目索引",
|
||||
"Behavior": "行为",
|
||||
"Benchmark function": "基准测试函数",
|
||||
"Binary response": "二进制响应",
|
||||
|
||||
Reference in new issue
Заблокувати користувача