| 1 | import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; |
| 2 | import { |
| 3 | AutocompleteCodeSnippet, |
| 4 | AutocompleteSnippetType, |
| 5 | } from "core/autocomplete/snippets/types"; |
| 6 | import { GetLspDefinitionsFunction } from "core/autocomplete/types"; |
| 7 | import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; |
| 8 | import { |
| 9 | FUNCTION_BLOCK_NODE_TYPES, |
| 10 | FUNCTION_DECLARATION_NODE_TYPEs, |
| 11 | } from "core/indexing/chunk/code"; |
| 12 | import { intersection } from "core/util/ranges"; |
| 13 | import * as URI from "uri-js"; |
| 14 | import * as vscode from "vscode"; |
| 15 | |
| 16 | import type { |
| 17 | IDE, |
| 18 | Range, |
| 19 | RangeInFile, |
| 20 | RangeInFileWithContents, |
| 21 | SignatureHelp, |
| 22 | } from "core"; |
| 23 | import type Parser from "web-tree-sitter"; |
| 24 | |
| 25 | type GotoProviderName = |
| 26 | | "vscode.executeDefinitionProvider" |
| 27 | | "vscode.executeTypeDefinitionProvider" |
| 28 | | "vscode.executeDeclarationProvider" |
| 29 | | "vscode.executeImplementationProvider" |
| 30 | | "vscode.executeReferenceProvider"; |
| 31 | |
| 32 | type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider"; |
| 33 | |
| 34 | interface GotoInput { |
| 35 | uri: vscode.Uri; |
| 36 | line: number; |
| 37 | character: number; |
| 38 | name: GotoProviderName; |
| 39 | } |
| 40 | function gotoInputKey(input: GotoInput) { |
| 41 | return `${input.name}${input.uri.toString()}${input.line}${input.character}`; |
| 42 | } |
| 43 | |
| 44 | interface SignatureHelpInput { |
| 45 | uri: vscode.Uri; |
| 46 | line: number; |
| 47 | character: number; |
| 48 | name: SignatureHelpProviderName; |
| 49 | } |
| 50 | function signatureHelpKey(input: SignatureHelpInput) { |
| 51 | return `${input.name}${input.uri.toString()}${input.line}${input.character}`; |
| 52 | } |
| 53 | |
| 54 | const MAX_CACHE_SIZE = 500; |
| 55 | const gotoCache = new Map<string, RangeInFile[]>(); |
| 56 | const signatureHelpCache = new Map<string, vscode.SignatureHelp>(); |
| 57 | |
| 58 | export async function executeGotoProvider( |
| 59 | input: GotoInput, |
| 60 | ): Promise<RangeInFile[]> { |
| 61 | const cacheKey = gotoInputKey(input); |
| 62 | const cached = gotoCache.get(cacheKey); |
| 63 | if (cached) { |
| 64 | return cached; |
| 65 | } |
| 66 | |
| 67 | try { |
| 68 | const definitions = (await vscode.commands.executeCommand( |
| 69 | input.name, |
| 70 | input.uri, |
| 71 | new vscode.Position(input.line, input.character), |
| 72 | )) as any; |
| 73 | |
| 74 | const results = definitions |
| 75 | .filter((d: any) => (d.targetUri || d.uri) && (d.targetRange || d.range)) |
| 76 | .map((d: any) => ({ |
| 77 | filepath: (d.targetUri || d.uri).toString(), |
| 78 | range: d.targetRange || d.range, |
| 79 | })); |
| 80 | |
| 81 | // Add to cache |
| 82 | if (gotoCache.size >= MAX_CACHE_SIZE) { |
| 83 | // Remove the oldest item from the cache |
| 84 | const oldestKey = gotoCache.keys().next().value; |
| 85 | if (oldestKey) { |
| 86 | gotoCache.delete(oldestKey); |
| 87 | } |
| 88 | } |
| 89 | gotoCache.set(cacheKey, results); |
| 90 | |
| 91 | return results; |
| 92 | } catch (e) { |
| 93 | console.warn(`Error executing ${input.name}:`, e); |
| 94 | return []; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | function isRifWithContents( |
| 99 | rif: RangeInFile | RangeInFileWithContents, |
| 100 | ): rif is RangeInFileWithContents { |
| 101 | return typeof (rif as any).contents === "string"; |
| 102 | } |
| 103 | |
| 104 | function findChildren( |
| 105 | node: Parser.SyntaxNode, |
| 106 | predicate: (n: Parser.SyntaxNode) => boolean, |
| 107 | firstN?: number, |
| 108 | ): Parser.SyntaxNode[] { |
| 109 | let matchingNodes: Parser.SyntaxNode[] = []; |
| 110 | |
| 111 | if (firstN && firstN <= 0) { |
| 112 | return []; |
| 113 | } |
| 114 | |
| 115 | // Check if the current node's type is in the list of types we're interested in |
| 116 | if (predicate(node)) { |
| 117 | matchingNodes.push(node); |
| 118 | } |
| 119 | |
| 120 | // Recursively search for matching types in all children of the current node |
| 121 | for (const child of node.children) { |
| 122 | matchingNodes = matchingNodes.concat( |
| 123 | findChildren( |
| 124 | child, |
| 125 | predicate, |
| 126 | firstN ? firstN - matchingNodes.length : undefined, |
| 127 | ), |
| 128 | ); |
| 129 | } |
| 130 | |
| 131 | return matchingNodes; |
| 132 | } |
| 133 | |
| 134 | function findTypeIdentifiers(node: Parser.SyntaxNode): Parser.SyntaxNode[] { |
| 135 | return findChildren( |
| 136 | node, |
| 137 | (childNode) => |
| 138 | childNode.type === "type_identifier" || |
| 139 | (["ERROR"].includes(childNode.parent?.type ?? "") && |
| 140 | childNode.type === "identifier" && |
| 141 | childNode.text[0].toUpperCase() === childNode.text[0]), |
| 142 | ); |
| 143 | } |
| 144 | |
| 145 | async function crawlTypes( |
| 146 | rif: RangeInFile | RangeInFileWithContents, |
| 147 | ide: IDE, |
| 148 | depth: number = 1, |
| 149 | results: RangeInFileWithContents[] = [], |
| 150 | searchedLabels: Set<string> = new Set(), |
| 151 | ): Promise<RangeInFileWithContents[]> { |
| 152 | // Get the file contents if not already attached |
| 153 | const contents = isRifWithContents(rif) |
| 154 | ? rif.contents |
| 155 | : await ide.readFile(rif.filepath); |
| 156 | |
| 157 | // Parse AST |
| 158 | const ast = await getAst(rif.filepath, contents); |
| 159 | if (!ast) { |
| 160 | return results; |
| 161 | } |
| 162 | const astLineCount = ast.rootNode.text.split("\n").length; |
| 163 | |
| 164 | // Find type identifiers |
| 165 | const identifierNodes = findTypeIdentifiers(ast.rootNode).filter( |
| 166 | (node) => !searchedLabels.has(node.text), |
| 167 | ); |
| 168 | // Don't search for the same type definition more than once |
| 169 | // We deduplicate below to be sure, but this saves calls to the LSP |
| 170 | identifierNodes.forEach((node) => searchedLabels.add(node.text)); |
| 171 | |
| 172 | // Use LSP to get the definitions of those types |
| 173 | const definitions = []; |
| 174 | |
| 175 | for (const node of identifierNodes) { |
| 176 | const [typeDef] = await executeGotoProvider({ |
| 177 | uri: vscode.Uri.parse(rif.filepath), |
| 178 | // TODO: tree-sitter is zero-indexed, but there seems to be an off-by-one |
| 179 | // error at least with the .ts parser sometimes |
| 180 | line: |
| 181 | rif.range.start.line + |
| 182 | Math.min(node.startPosition.row, astLineCount - 1), |
| 183 | character: rif.range.start.character + node.startPosition.column, |
| 184 | name: "vscode.executeDefinitionProvider", |
| 185 | }); |
| 186 | |
| 187 | if (!typeDef) { |
| 188 | definitions.push(undefined); |
| 189 | continue; |
| 190 | } |
| 191 | |
| 192 | const contents = await ide.readRangeInFile(typeDef.filepath, typeDef.range); |
| 193 | |
| 194 | definitions.push({ |
| 195 | ...typeDef, |
| 196 | contents, |
| 197 | }); |
| 198 | } |
| 199 | |
| 200 | // TODO: Filter out if not in our code? |
| 201 | |
| 202 | // Filter out duplicates |
| 203 | for (const definition of definitions) { |
| 204 | if ( |
| 205 | !definition || |
| 206 | results.some( |
| 207 | (result) => |
| 208 | URI.equal(result.filepath, definition.filepath) && |
| 209 | intersection(result.range, definition.range) !== null, |
| 210 | ) |
| 211 | ) { |
| 212 | continue; // ;) |
| 213 | } |
| 214 | results.push(definition); |
| 215 | } |
| 216 | |
| 217 | // Recurse |
| 218 | if (depth > 0) { |
| 219 | for (const result of [...results]) { |
| 220 | await crawlTypes(result, ide, depth - 1, results, searchedLabels); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | return results; |
| 225 | } |
| 226 | |
| 227 | export async function getDefinitionsForNode( |
| 228 | uri: vscode.Uri, |
| 229 | node: Parser.SyntaxNode, |
| 230 | ide: IDE, |
| 231 | lang: AutocompleteLanguageInfo, |
| 232 | ): Promise<RangeInFileWithContents[]> { |
| 233 | const ranges: (RangeInFile | RangeInFileWithContents)[] = []; |
| 234 | switch (node.type) { |
| 235 | case "call_expression": { |
| 236 | // function call -> function definition |
| 237 | const [funDef] = await executeGotoProvider({ |
| 238 | uri, |
| 239 | line: node.startPosition.row, |
| 240 | character: node.startPosition.column, |
| 241 | name: "vscode.executeDefinitionProvider", |
| 242 | }); |
| 243 | if (!funDef) { |
| 244 | return []; |
| 245 | } |
| 246 | |
| 247 | // Don't display a function of more than 15 lines |
| 248 | // We can of course do something smarter here eventually |
| 249 | let funcText = await ide.readRangeInFile(funDef.filepath, funDef.range); |
| 250 | if (funcText.split("\n").length > 15) { |
| 251 | let truncated = false; |
| 252 | const funRootAst = await getAst(funDef.filepath, funcText); |
| 253 | if (funRootAst) { |
| 254 | const [funNode] = findChildren( |
| 255 | funRootAst?.rootNode, |
| 256 | (node) => FUNCTION_DECLARATION_NODE_TYPEs.includes(node.type), |
| 257 | 1, |
| 258 | ); |
| 259 | if (funNode) { |
| 260 | const [statementBlockNode] = findChildren( |
| 261 | funNode, |
| 262 | (node) => FUNCTION_BLOCK_NODE_TYPES.includes(node.type), |
| 263 | 1, |
| 264 | ); |
| 265 | if (statementBlockNode) { |
| 266 | funcText = funRootAst.rootNode.text |
| 267 | .slice(0, statementBlockNode.startIndex) |
| 268 | .trim(); |
| 269 | truncated = true; |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | if (!truncated) { |
| 274 | funcText = funcText.split("\n")[0]; |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | ranges.push(funDef); |
| 279 | |
| 280 | const typeDefs = await crawlTypes( |
| 281 | { |
| 282 | ...funDef, |
| 283 | contents: funcText, |
| 284 | }, |
| 285 | ide, |
| 286 | ); |
| 287 | ranges.push(...typeDefs); |
| 288 | break; |
| 289 | } |
| 290 | case "variable_declarator": |
| 291 | // variable assignment -> variable definition/type |
| 292 | // usages of the var that appear after the declaration |
| 293 | break; |
| 294 | case "impl_item": |
| 295 | // impl of trait -> trait definition |
| 296 | break; |
| 297 | case "new_expression": |
| 298 | // In 'new MyClass(...)', "MyClass" is the classNameNode |
| 299 | const classNameNode = node.children.find( |
| 300 | (child) => child.type === "identifier", |
| 301 | ); |
| 302 | const [classDef] = await executeGotoProvider({ |
| 303 | uri, |
| 304 | line: (classNameNode ?? node).endPosition.row, |
| 305 | character: (classNameNode ?? node).endPosition.column, |
| 306 | name: "vscode.executeDefinitionProvider", |
| 307 | }); |
| 308 | if (!classDef) { |
| 309 | break; |
| 310 | } |
| 311 | const contents = await ide.readRangeInFile( |
| 312 | classDef.filepath, |
| 313 | classDef.range, |
| 314 | ); |
| 315 | |
| 316 | ranges.push({ |
| 317 | ...classDef, |
| 318 | contents: `${ |
| 319 | classNameNode?.text |
| 320 | ? `${lang.singleLineComment} ${classNameNode.text}:\n` |
| 321 | : "" |
| 322 | }${contents.trim()}`, |
| 323 | }); |
| 324 | |
| 325 | const definitions = await crawlTypes({ ...classDef, contents }, ide); |
| 326 | ranges.push(...definitions.filter(Boolean)); |
| 327 | |
| 328 | break; |
| 329 | case "": |
| 330 | // function definition -> implementations? |
| 331 | break; |
| 332 | } |
| 333 | return await Promise.all( |
| 334 | ranges.map(async (rif) => { |
| 335 | // Convert the VS Code Range type to ours |
| 336 | const range: Range = { |
| 337 | start: { |
| 338 | line: rif.range.start.line, |
| 339 | character: rif.range.start.character, |
| 340 | }, |
| 341 | end: { |
| 342 | line: rif.range.end.line, |
| 343 | character: rif.range.end.character, |
| 344 | }, |
| 345 | }; |
| 346 | rif.range = range; |
| 347 | |
| 348 | if (!isRifWithContents(rif)) { |
| 349 | return { |
| 350 | ...rif, |
| 351 | contents: await ide.readRangeInFile(rif.filepath, rif.range), |
| 352 | }; |
| 353 | } |
| 354 | return rif; |
| 355 | }), |
| 356 | ); |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * and other stuff not directly on the path: |
| 361 | * - variables defined on line above |
| 362 | * ...etc... |
| 363 | */ |
| 364 | |
| 365 | export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( |
| 366 | filepath: string, |
| 367 | contents: string, |
| 368 | cursorIndex: number, |
| 369 | ide: IDE, |
| 370 | lang: AutocompleteLanguageInfo, |
| 371 | ): Promise<AutocompleteCodeSnippet[]> => { |
| 372 | try { |
| 373 | const ast = await getAst(filepath, contents); |
| 374 | if (!ast) { |
| 375 | return []; |
| 376 | } |
| 377 | |
| 378 | const treePath = await getTreePathAtCursor(ast, cursorIndex); |
| 379 | if (!treePath) { |
| 380 | return []; |
| 381 | } |
| 382 | |
| 383 | const results: RangeInFileWithContents[] = []; |
| 384 | for (const node of treePath.reverse()) { |
| 385 | const definitions = await getDefinitionsForNode( |
| 386 | vscode.Uri.parse(filepath), |
| 387 | node, |
| 388 | ide, |
| 389 | lang, |
| 390 | ); |
| 391 | results.push(...definitions); |
| 392 | } |
| 393 | |
| 394 | return results.map((result) => ({ |
| 395 | filepath: result.filepath, |
| 396 | content: result.contents, |
| 397 | type: AutocompleteSnippetType.Code, |
| 398 | })); |
| 399 | } catch (e) { |
| 400 | console.warn("Error getting definitions from LSP: ", e); |
| 401 | return []; |
| 402 | } |
| 403 | }; |
| 404 | |
| 405 | export async function executeSignatureHelpProvider( |
| 406 | input: SignatureHelpInput, |
| 407 | ): Promise<SignatureHelp | null> { |
| 408 | const cacheKey = signatureHelpKey(input); |
| 409 | const cached = signatureHelpCache.get(cacheKey); |
| 410 | if (cached) { |
| 411 | return cached; |
| 412 | } |
| 413 | |
| 414 | try { |
| 415 | const definitions = (await vscode.commands.executeCommand( |
| 416 | input.name, |
| 417 | input.uri, |
| 418 | new vscode.Position(input.line, input.character), |
| 419 | )) as SignatureHelp; |
| 420 | |
| 421 | // Add to cache |
| 422 | if (signatureHelpCache.size >= MAX_CACHE_SIZE) { |
| 423 | // Remove the oldest item from the cache |
| 424 | const oldestKey = signatureHelpCache.keys().next().value; |
| 425 | if (oldestKey) { |
| 426 | signatureHelpCache.delete(oldestKey); |
| 427 | } |
| 428 | } |
| 429 | signatureHelpCache.set(cacheKey, definitions); |
| 430 | |
| 431 | return definitions; |
| 432 | } catch (e) { |
| 433 | console.warn(`Error executing ${input.name}:`, e); |
| 434 | return null; |
| 435 | } |
| 436 | } |