From ed8a3779d365a93e68658e30e31fc8aec1300d70 Mon Sep 17 00:00:00 2001 From: kagami Date: Tue, 27 Feb 2024 16:14:01 +0800 Subject: [PATCH] Implement /find_def_locations in IDE Service --- src/ide_services/endpoints/findDefs.ts | 65 ++++++++++++++++++++++++++ src/ide_services/services.ts | 5 ++ 2 files changed, 70 insertions(+) create mode 100644 src/ide_services/endpoints/findDefs.ts diff --git a/src/ide_services/endpoints/findDefs.ts b/src/ide_services/endpoints/findDefs.ts new file mode 100644 index 0000000..ace2a51 --- /dev/null +++ b/src/ide_services/endpoints/findDefs.ts @@ -0,0 +1,65 @@ +import * as vscode from "vscode"; + +import { IDEService } from "../types"; +import { assert } from "console"; + +/** + * Find definition locations for a symbol + * + * @param abspath: absolute path of the file + * @param line: line number of the symbol, 0-based + * @param character: character number, 0-based + */ +export async function findDefinitionLocations( + abspath: string, + line: string, + character: string +): Promise { + const ln = Number(line); + const col = Number(character); + assert(!isNaN(ln) && !isNaN(col), "line and character must be numbers"); + + const position = new vscode.Position(ln, col); + const uri = vscode.Uri.file(abspath); + + const defs = await vscode.commands.executeCommand< + vscode.Location[] | vscode.LocationLink[] + >("vscode.executeDefinitionProvider", uri, position); + + const locations: IDEService.Location[] = []; + defs.forEach((def) => { + locations.push(toLocation(def)); + }); + + return locations; +} + +/** + * + * @param location + * @returns + */ +function toLocation( + location: vscode.Location | vscode.LocationLink +): IDEService.Location { + const range = "range" in location ? location.range : location.targetRange; + const uri = "uri" in location ? location.uri : location.targetUri; + const start = range.start; + const end = range.end; + + const loc: IDEService.Location = { + abspath: uri.fsPath, + range: { + start: { + line: start.line, + character: start.character, + }, + end: { + line: end.line, + character: end.character, + }, + }, + }; + + return loc; +} diff --git a/src/ide_services/services.ts b/src/ide_services/services.ts index a8991dc..cb39a8e 100644 --- a/src/ide_services/services.ts +++ b/src/ide_services/services.ts @@ -12,6 +12,7 @@ import { LegacyEndpoints } from "./endpoints/legacy"; import { UnofficialEndpoints } from "./endpoints/unofficial"; import { getDocumentSymbols } from "./endpoints/getDocumentSymbols"; import { findTypeDefinitionLocations } from "./endpoints/findTypeDefs"; +import { findDefinitionLocations } from "./endpoints/findDefs"; const functionRegistry: any = { /** @@ -41,6 +42,10 @@ const functionRegistry: any = { keys: ["abspath"], handler: getDocumentSymbols, }, + "/find_def_locations": { + keys: ["abspath", "line", "character"], + handler: findDefinitionLocations, + }, "/find_type_def_locations": { keys: ["abspath", "line", "character"], handler: findTypeDefinitionLocations,