Elffuss BraidHub

kikocis/continue public

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