Elffuss BraidHub

kikocis/continue public

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