| 1 | import Parser from "web-tree-sitter"; |
| 2 | import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; |
| 3 | import { getAst } from "../autocomplete/util/ast"; |
| 4 | import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; |
| 5 | import { |
| 6 | NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 7 | NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 8 | } from "./constants"; |
| 9 | |
| 10 | export enum EditableRegionStrategy { |
| 11 | Naive = "naive", |
| 12 | Sliding = "sliding", |
| 13 | Rerank = "rerank", |
| 14 | StaticRerank = "staticRerank", |
| 15 | Static = "static", |
| 16 | } |
| 17 | |
| 18 | export async function getNextEditableRegion( |
| 19 | strategy: EditableRegionStrategy, |
| 20 | ctx: any, |
| 21 | ): Promise<RangeInFile[] | null> { |
| 22 | switch (strategy) { |
| 23 | case EditableRegionStrategy.Naive: |
| 24 | return naiveJump(ctx); |
| 25 | case EditableRegionStrategy.Sliding: |
| 26 | return slidingJump(ctx); |
| 27 | case EditableRegionStrategy.Rerank: |
| 28 | return await rerankJump(ctx); |
| 29 | case EditableRegionStrategy.StaticRerank: |
| 30 | return await staticRerankJump(ctx); |
| 31 | case EditableRegionStrategy.Static: |
| 32 | return await staticJump(ctx); |
| 33 | default: |
| 34 | return null; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Naive assumes that the entire file is editable. |
| 39 | // This relies on the next edit model to figure out where to jump next. |
| 40 | function naiveJump(ctx: any): RangeInFile[] | null { |
| 41 | const { fileLines, filepath } = ctx; |
| 42 | if (!fileLines || !filepath) { |
| 43 | console.warn("Missing required context for naive jump"); |
| 44 | return null; |
| 45 | } |
| 46 | |
| 47 | return [ |
| 48 | { |
| 49 | filepath, |
| 50 | range: { |
| 51 | start: { line: 0, character: 0 }, |
| 52 | end: { |
| 53 | line: fileLines.length - 1, |
| 54 | character: fileLines.at(-1).length, |
| 55 | }, |
| 56 | }, |
| 57 | }, |
| 58 | ]; |
| 59 | } |
| 60 | |
| 61 | // Sliding splits the file using into sliding window. |
| 62 | function slidingJump(ctx: any): RangeInFile[] | null { |
| 63 | const { fileLines, filepath } = ctx; |
| 64 | if (!fileLines || !filepath) { |
| 65 | console.warn("Missing required context for naive jump"); |
| 66 | return null; |
| 67 | } |
| 68 | |
| 69 | const windowSize = |
| 70 | NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN + |
| 71 | NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN + |
| 72 | 1; // 1 for current line; |
| 73 | |
| 74 | if (fileLines.length <= windowSize) { |
| 75 | return [ |
| 76 | { |
| 77 | filepath, |
| 78 | range: { |
| 79 | start: { line: 0, character: 0 }, |
| 80 | end: { |
| 81 | line: fileLines.length - 1, |
| 82 | character: fileLines[fileLines.length - 1].length, |
| 83 | }, |
| 84 | }, |
| 85 | }, |
| 86 | ]; |
| 87 | } |
| 88 | |
| 89 | const slidingStep = Math.max(1, Math.floor(windowSize / 2)); |
| 90 | const ranges: RangeInFile[] = []; |
| 91 | |
| 92 | for ( |
| 93 | let startLine = 0; |
| 94 | startLine < fileLines.length; |
| 95 | startLine += slidingStep |
| 96 | ) { |
| 97 | const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1); |
| 98 | |
| 99 | ranges.push({ |
| 100 | filepath, |
| 101 | range: { |
| 102 | start: { line: startLine, character: 0 }, |
| 103 | end: { |
| 104 | line: endLine, |
| 105 | character: fileLines[endLine].length, |
| 106 | }, |
| 107 | }, |
| 108 | }); |
| 109 | |
| 110 | if (endLine >= fileLines.length - 1) { |
| 111 | break; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | return ranges; |
| 116 | } |
| 117 | |
| 118 | // A rerank jump splits the current file into chunks. |
| 119 | // Then it uses a rerank model to get the most relevant chunks and their positions. |
| 120 | async function rerankJump(ctx: { |
| 121 | fileContent: string; |
| 122 | query: string; |
| 123 | filepath: string; |
| 124 | reranker: ILLM; |
| 125 | chunkSize: number; |
| 126 | }): Promise<RangeInFile[] | null> { |
| 127 | try { |
| 128 | const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; |
| 129 | |
| 130 | if (!fileContent || !query || !filepath || !reranker) { |
| 131 | console.warn( |
| 132 | "Missing required context for rerank jump:", |
| 133 | !fileContent, |
| 134 | !query, |
| 135 | !filepath, |
| 136 | !reranker, |
| 137 | ); |
| 138 | return null; |
| 139 | } |
| 140 | |
| 141 | const lines = fileContent.split("\n"); |
| 142 | const chunks: Chunk[] = []; |
| 143 | |
| 144 | // Create chunks from the file. |
| 145 | for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { |
| 146 | const endLine = Math.min(i + chunkSize - 1, lines.length - 1); |
| 147 | const chunkContent = lines.slice(i, endLine + 1).join("\n"); |
| 148 | if (chunkContent === "") continue; // Voyager throws an error if there are empty strings in its document field in the body. |
| 149 | chunks.push({ |
| 150 | content: chunkContent, |
| 151 | startLine: i, |
| 152 | endLine: endLine, |
| 153 | digest: `chunk-${i}-${endLine}`, |
| 154 | filepath: filepath, |
| 155 | index: i, |
| 156 | }); |
| 157 | } |
| 158 | |
| 159 | // Use the reranker to score each chunk against the query. |
| 160 | const scores = await reranker.rerank(query, chunks); |
| 161 | |
| 162 | // Sort by score in descending order and get the highest scoring chunk. |
| 163 | chunks.sort( |
| 164 | (a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)], |
| 165 | ); |
| 166 | |
| 167 | // const mostRelevantChunk = chunks[0]; |
| 168 | // Get the third most relevant chunk if there are enough chunks, |
| 169 | // otherwise fallback to second or first. |
| 170 | // The most relevant chunk seems to be the one that |
| 171 | // is similar enough lexically, |
| 172 | // but different enough to still justify making an edit. |
| 173 | const chunkIndex = Math.min(2, chunks.length - 1); |
| 174 | const mostRelevantChunk = chunks[chunkIndex]; |
| 175 | |
| 176 | // Return the range of the most relevant chunk. |
| 177 | // NOTE: It might be better to return a list of chunks, |
| 178 | // because it's very difficult to gauge when to stop the model. |
| 179 | // We could argue that we should always try to jump until the user says no. |
| 180 | return [ |
| 181 | { |
| 182 | filepath, |
| 183 | range: { |
| 184 | start: { line: mostRelevantChunk.startLine, character: 0 }, |
| 185 | end: { |
| 186 | line: mostRelevantChunk.endLine, |
| 187 | character: lines[mostRelevantChunk.endLine].length, |
| 188 | }, |
| 189 | }, |
| 190 | }, |
| 191 | ]; |
| 192 | } catch (error) { |
| 193 | console.error("Error in rerank jump:", error); |
| 194 | return null; |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | // A static rerank jump runs a lightweight static analysis on the file |
| 199 | // and uses the reranker to jump to relevant locations. |
| 200 | async function staticRerankJump(ctx: { |
| 201 | oldFileContent: string; |
| 202 | newFileContent: string; |
| 203 | completionRange: Range; |
| 204 | filepath: string; |
| 205 | ide: IDE; |
| 206 | reranker?: ILLM; |
| 207 | chunkSize?: number; |
| 208 | }): Promise<RangeInFile[] | null> { |
| 209 | try { |
| 210 | const { oldFileContent, newFileContent, completionRange, filepath, ide } = |
| 211 | ctx; |
| 212 | |
| 213 | if ( |
| 214 | !oldFileContent || |
| 215 | !newFileContent || |
| 216 | !completionRange || |
| 217 | !filepath || |
| 218 | !ide |
| 219 | ) { |
| 220 | console.warn( |
| 221 | "Missing required context for static rerank jump:", |
| 222 | !oldFileContent, |
| 223 | !newFileContent, |
| 224 | !completionRange, |
| 225 | !filepath, |
| 226 | !ide, |
| 227 | ); |
| 228 | return null; |
| 229 | } |
| 230 | |
| 231 | // TODO: |
| 232 | // Parse the old file contents into an AST. |
| 233 | // Parse the new file contents into an AST. |
| 234 | // Compare the two trees and find which nodes have changed. |
| 235 | // Save the queue of changed nodes. The queue should contain the old node and the new node. Each of them can be null if the change is a deletion or insertion. |
| 236 | // Rank the queue by node depth (decreasing order because we want granular edits). |
| 237 | // Pop front until we find a queue item with an old node != null. |
| 238 | // Search the codebase for the old node's expression. For this, either use ide.getReferences(some_location), or other methods you see fit. If you can utilize the strategy pattern, even better. |
| 239 | // For now, filter out results from outside files. We only want to keep the results in the current file. |
| 240 | // Return the first result from this filtered list of results. |
| 241 | |
| 242 | // Parse the old file contents into an AST. |
| 243 | const oldAst = await getAst(filepath, oldFileContent); |
| 244 | if (!oldAst) return null; |
| 245 | |
| 246 | // Parse the new file contents into an AST. |
| 247 | const newAst = await getAst(filepath, newFileContent); |
| 248 | if (!newAst) return null; |
| 249 | |
| 250 | // Compare the two trees and find which nodes have changed. |
| 251 | const changedNodes = compareAsts(oldAst, newAst); |
| 252 | if (!changedNodes || changedNodes.length === 0) return null; |
| 253 | |
| 254 | // Save the queue of changed nodes. |
| 255 | // The queue should contain the old node and the new node. |
| 256 | // Each can be null if the change is a deletion or insertion. |
| 257 | // const nodeQueue = changedNodes.map((change) => ({ |
| 258 | // oldNode: change.oldNode, |
| 259 | // newNode: change.newNode, |
| 260 | // depth: change.depth, |
| 261 | // })); |
| 262 | |
| 263 | // Rank the queue by node depth. |
| 264 | // Decreasing order for granular edits. |
| 265 | // Increasing order for larger definition-based searches. |
| 266 | // Making it decreasing has issues when the deepest node is a string_fragment. |
| 267 | const nodeQueue = changedNodes.sort((a, b) => a.depth - b.depth); |
| 268 | console.log( |
| 269 | "nodeQueue:", |
| 270 | nodeQueue.map((node) => ({ |
| 271 | oldText: node.oldNode?.text || "", |
| 272 | newText: node.newNode?.text || "", |
| 273 | oldType: node.oldNode?.type || "", |
| 274 | newType: node.newNode?.type || "", |
| 275 | depth: node.depth, |
| 276 | })), |
| 277 | ); |
| 278 | |
| 279 | // Find the first item with a non-null old node. |
| 280 | let targetNode = null; |
| 281 | while (nodeQueue.length > 0 && !targetNode) { |
| 282 | const candidate = nodeQueue.shift(); |
| 283 | if ( |
| 284 | candidate && |
| 285 | candidate.oldNode && |
| 286 | candidate.oldNode.type !== "program" |
| 287 | ) { |
| 288 | targetNode = candidate.oldNode; |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | if (!targetNode) return null; |
| 293 | |
| 294 | // Get the text representation of the old node's expression. |
| 295 | const nodeText = getNodeText(targetNode); |
| 296 | if (!nodeText || nodeText.trim() === "") return null; |
| 297 | |
| 298 | // Search for similar code in the file. |
| 299 | let references: RangeInFile[] = []; |
| 300 | |
| 301 | // Try to use IDE's reference finding capabilities if available. |
| 302 | try { |
| 303 | // Get the position of the target node in the old file. |
| 304 | const nodePosition = getNodePosition(targetNode); |
| 305 | if (nodePosition) { |
| 306 | // Use IDE to find references. |
| 307 | |
| 308 | // TODO: |
| 309 | // Get the list of document symbols using await ide.getDocumentSymbols. |
| 310 | // Each document symbol will be our query. |
| 311 | // Use the rerank model to rank the nodeText against the query. |
| 312 | // Get the highest scoring query and its location. |
| 313 | |
| 314 | // Get the list of document symbols using await ide.getDocumentSymbols. |
| 315 | // Filter out symbols that are directly inside the completion range. |
| 316 | const symbols = await ide.getDocumentSymbols(filepath); |
| 317 | |
| 318 | // Filter out symbols that are directly inside the completion range |
| 319 | const filteredSymbols = symbols.filter((symbol) => { |
| 320 | // Check if the symbol's range is outside of the completion range |
| 321 | return !doRangesOverlap(symbol.range, completionRange); |
| 322 | }); |
| 323 | |
| 324 | // Use the reranker to rank the filtered symbols against the node text. |
| 325 | if (!ctx.reranker) { |
| 326 | console.warn("No reranker available for static jump symbol ranking"); |
| 327 | return null; |
| 328 | } |
| 329 | |
| 330 | const symbolChunks: Chunk[] = filteredSymbols.map((symbol) => ({ |
| 331 | content: symbol.name, |
| 332 | startLine: symbol.range.start.line, |
| 333 | endLine: symbol.range.end.line, |
| 334 | digest: `symbol-${symbol.name}-${symbol.range.start.line}`, |
| 335 | filepath: filepath, |
| 336 | index: symbol.range.start.line, |
| 337 | })); |
| 338 | |
| 339 | if (symbolChunks.length === 0) { |
| 340 | console.warn("No symbols found for ranking"); |
| 341 | return null; |
| 342 | } |
| 343 | |
| 344 | const scores = await ctx.reranker.rerank(nodeText, symbolChunks); |
| 345 | symbolChunks.sort( |
| 346 | (a, b) => |
| 347 | scores[symbolChunks.indexOf(b)] - scores[symbolChunks.indexOf(a)], |
| 348 | ); |
| 349 | |
| 350 | const mostRelevantSymbol = symbolChunks[0]; |
| 351 | const originalSymbol = filteredSymbols.find( |
| 352 | (symbol) => |
| 353 | symbol.range.start.line === mostRelevantSymbol.startLine && |
| 354 | symbol.range.end.line === mostRelevantSymbol.endLine, |
| 355 | ); |
| 356 | |
| 357 | if (originalSymbol) { |
| 358 | references = [ |
| 359 | { |
| 360 | filepath, |
| 361 | range: originalSymbol.range, |
| 362 | }, |
| 363 | ]; |
| 364 | } |
| 365 | |
| 366 | // const foundReferences = await ide.getReferences({ |
| 367 | // filepath, |
| 368 | // position: nodePosition, |
| 369 | // }); |
| 370 | |
| 371 | // if (foundReferences && foundReferences.length > 0) { |
| 372 | // references = foundReferences; |
| 373 | // } |
| 374 | } |
| 375 | } catch (e) { |
| 376 | console.warn( |
| 377 | "Failed to use IDE references, falling back to text search:", |
| 378 | e, |
| 379 | ); |
| 380 | } |
| 381 | |
| 382 | // If IDE reference finding failed or returned no results, fall back to text search. |
| 383 | if (references.length === 0) { |
| 384 | references = findTextOccurrences(oldFileContent, nodeText).map( |
| 385 | (range) => ({ filepath, range }), |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | // Filter out results from outside the current file. |
| 390 | const currentFileReferences = references.filter( |
| 391 | (ref) => ref.filepath === filepath, |
| 392 | ); |
| 393 | |
| 394 | // Return the first reference if any found. |
| 395 | if (currentFileReferences.length > 0) { |
| 396 | return [currentFileReferences[0]]; |
| 397 | // return currentFileReferences; |
| 398 | } |
| 399 | |
| 400 | return null; |
| 401 | } catch (error) { |
| 402 | console.error("Error in static jump:", error); |
| 403 | return null; |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | // Static jump relies purely on static analysis |
| 408 | // to determine where to edit next. |
| 409 | async function staticJump(ctx: { |
| 410 | cursorPosition: { line: number; character: number }; |
| 411 | filepath: string; |
| 412 | ide: IDE; |
| 413 | }): Promise<RangeInFile[] | null> { |
| 414 | try { |
| 415 | const { cursorPosition, filepath, ide } = ctx; |
| 416 | if (!cursorPosition || !filepath || !ide) { |
| 417 | console.warn( |
| 418 | "Missing required context for static jump:", |
| 419 | !cursorPosition, |
| 420 | !filepath, |
| 421 | !ide, |
| 422 | ); |
| 423 | return null; |
| 424 | } |
| 425 | |
| 426 | // Get the file's AST. |
| 427 | // Getting this once helps us live-track the current node. |
| 428 | const tree = |
| 429 | await DocumentHistoryTracker.getInstance().getMostRecentAst(filepath); |
| 430 | // const tree = await getAst(filepath, fileContent); |
| 431 | if (!tree) return null; |
| 432 | |
| 433 | // Convert cursor position to tree-sitter point format (0-based). |
| 434 | const point = { |
| 435 | row: cursorPosition.line, |
| 436 | column: cursorPosition.character, |
| 437 | }; |
| 438 | |
| 439 | // Find the node at the cursor position. |
| 440 | const nodeAtCursor = tree.rootNode.descendantForPosition(point); |
| 441 | if (!nodeAtCursor) { |
| 442 | console.log("No node found at cursor position"); |
| 443 | return null; |
| 444 | } |
| 445 | |
| 446 | // Find the closest identifier node. |
| 447 | const identifierNode = findClosestIdentifierNode(nodeAtCursor); |
| 448 | if (!identifierNode) { |
| 449 | console.log("No identifier node found near cursor position"); |
| 450 | return null; |
| 451 | } |
| 452 | // console.log("closest identifier:", identifierNode.text); |
| 453 | |
| 454 | // Get all references to this identifier using the IDE's API |
| 455 | const references = await ide.getReferences({ |
| 456 | filepath, |
| 457 | position: { |
| 458 | line: identifierNode.startPosition.row, |
| 459 | character: identifierNode.startPosition.column, |
| 460 | }, |
| 461 | }); |
| 462 | |
| 463 | if (!references || references.length === 0) { |
| 464 | console.log(`No references found for identifier: ${identifierNode.text}`); |
| 465 | return null; |
| 466 | } |
| 467 | |
| 468 | // console.log( |
| 469 | // "references:", |
| 470 | // JSON.stringify( |
| 471 | // references.map((ref) => ({ |
| 472 | // line: ref.range.start.line, |
| 473 | // character: ref.range.start.character, |
| 474 | // })), |
| 475 | // null, |
| 476 | // 2, |
| 477 | // ), |
| 478 | // ); |
| 479 | |
| 480 | return references.length > 1 ? references.slice(1) : null; |
| 481 | } catch (error) { |
| 482 | console.error("Error in staticJump:", error); |
| 483 | return null; |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /* AST HELPER FUNCTIONS */ |
| 488 | |
| 489 | // Helper function to find the closest identifier node. |
| 490 | function findClosestIdentifierNode( |
| 491 | node: Parser.SyntaxNode | null, |
| 492 | ): Parser.SyntaxNode | null { |
| 493 | if (!node) return null; |
| 494 | |
| 495 | if (isIdentifierNode(node)) return node; |
| 496 | if (isDeclarationNode(node)) return findLeftmostIdentifier(node); |
| 497 | |
| 498 | // Check if the parent is an identifier. |
| 499 | // NOTE: This will probably never get triggered. |
| 500 | // Most identifiers are leaf nodes. |
| 501 | const parent = node.parent; |
| 502 | if (parent && isIdentifierNode(parent)) { |
| 503 | return parent; |
| 504 | } |
| 505 | |
| 506 | if (parent) { |
| 507 | if (isDeclarationNode(parent)) return findLeftmostIdentifier(parent); |
| 508 | |
| 509 | // Check if one of the siblings is an identifier. |
| 510 | for (let i = 0; i < parent.childCount; ++i) { |
| 511 | // const sibling = node.child(i); |
| 512 | const sibling = parent.child(i); |
| 513 | if (sibling && isIdentifierNode(sibling)) { |
| 514 | // Get the leftmost identifier sibling. |
| 515 | return sibling; |
| 516 | } |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | return findClosestIdentifierNode(parent); |
| 521 | } |
| 522 | |
| 523 | function findLeftmostIdentifier( |
| 524 | node: Parser.SyntaxNode, |
| 525 | ): Parser.SyntaxNode | null { |
| 526 | if (isIdentifierNode(node)) return node; |
| 527 | |
| 528 | for (let i = 0; i < node.childCount; ++i) { |
| 529 | const child = node.child(i); |
| 530 | if (child) { |
| 531 | const result = findLeftmostIdentifier(child); |
| 532 | if (result) return result; |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | return null; |
| 537 | } |
| 538 | |
| 539 | // Helper function to check if a node is an identifier. |
| 540 | function isIdentifierNode(node: Parser.SyntaxNode) { |
| 541 | const nodeType = node.type; |
| 542 | |
| 543 | if (nodeType === "identifier") return true; |
| 544 | if (nodeType.includes("identifier")) return true; |
| 545 | |
| 546 | // Most language grammars will use the term "identifier". |
| 547 | // However some might not. |
| 548 | // Update this as they come. |
| 549 | const specialIdentifiers = ["name", "constant"]; |
| 550 | return specialIdentifiers.includes(nodeType); |
| 551 | } |
| 552 | |
| 553 | // Helper function to check if a node is a declaration. |
| 554 | function isDeclarationNode(node: Parser.SyntaxNode) { |
| 555 | const nodeType = node.type; |
| 556 | |
| 557 | // Common declaration patterns. |
| 558 | if (nodeType.endsWith("_declaration")) return true; |
| 559 | if (nodeType.endsWith("_definition")) return true; |
| 560 | if (nodeType.endsWith("_item")) return true; // Rust. |
| 561 | |
| 562 | // Language-specific patterns. |
| 563 | const declarationTypes = [ |
| 564 | // Python. |
| 565 | "function_definition", |
| 566 | "class_definition", |
| 567 | "async_function_definition", |
| 568 | "decorated_definition", |
| 569 | |
| 570 | // Ruby. |
| 571 | "method", |
| 572 | "class", |
| 573 | "module", |
| 574 | "singleton_method", |
| 575 | |
| 576 | // Java. |
| 577 | "variable_declarator", |
| 578 | "local_variable_declaration", |
| 579 | |
| 580 | // Go. |
| 581 | "short_var_declaration", |
| 582 | |
| 583 | // General |
| 584 | "method_definition", |
| 585 | ]; |
| 586 | |
| 587 | return declarationTypes.includes(nodeType); |
| 588 | } |
| 589 | |
| 590 | // // Helper function to find the closest identifier node. |
| 591 | // function findClosestIdentifierNode( |
| 592 | // node: Parser.SyntaxNode | undefined, |
| 593 | // ): Parser.SyntaxNode | undefined { |
| 594 | // if (!node) return undefined; |
| 595 | |
| 596 | // // Check if the current node is an identifier |
| 597 | // if (isIdentifierLike(node)) { |
| 598 | // return node; |
| 599 | // } |
| 600 | |
| 601 | // // Check if the parent is an identifier |
| 602 | // const parent = node.parent; |
| 603 | // if (parent && isIdentifierLike(parent)) { |
| 604 | // return parent; |
| 605 | // } |
| 606 | |
| 607 | // // Check if any of the node's children are identifiers |
| 608 | // // Return the leftmost identifier child if found |
| 609 | // for (let i = 0; i < node.childCount; i++) { |
| 610 | // const child = node.child(i); |
| 611 | // if (child && isIdentifierLike(child)) { |
| 612 | // return child; |
| 613 | // } |
| 614 | // } |
| 615 | |
| 616 | // // Check if any of the parent's children are identifiers |
| 617 | // if (parent) { |
| 618 | // for (let i = 0; i < parent.childCount; i++) { |
| 619 | // const sibling = parent.child(i); |
| 620 | // if (sibling && isIdentifierLike(sibling)) { |
| 621 | // return sibling; |
| 622 | // } |
| 623 | // } |
| 624 | // } |
| 625 | |
| 626 | // // Recurse on the parent if we haven't found anything yet |
| 627 | // return findClosestIdentifierNode(parent); |
| 628 | // } |
| 629 | |
| 630 | // // Helper function to determine if a node is identifier-like |
| 631 | // function isIdentifierLike(node: Parser.SyntaxNode): boolean { |
| 632 | // // Common identifier node types across languages |
| 633 | // const commonIdentifierTypes = [ |
| 634 | // "identifier", |
| 635 | // "property_identifier", |
| 636 | // "type_identifier", |
| 637 | // "field_identifier", |
| 638 | // "variable_identifier", |
| 639 | // "constant", |
| 640 | // "symbol", |
| 641 | // ]; |
| 642 | |
| 643 | // if (commonIdentifierTypes.includes(node.type)) { |
| 644 | // return true; |
| 645 | // } |
| 646 | |
| 647 | // // Check for common identifier patterns in node types |
| 648 | // return /identifier$|^identifier|_identifier/.test(node.type); |
| 649 | // } |
| 650 | |
| 651 | // Helper function to compare ASTs and find changed nodes. |
| 652 | function compareAsts(oldAst: Parser.Tree, newAst: Parser.Tree) { |
| 653 | const changedNodes: { |
| 654 | oldNode: Parser.SyntaxNode | null; |
| 655 | newNode: Parser.SyntaxNode | null; |
| 656 | depth: number; |
| 657 | }[] = []; |
| 658 | |
| 659 | // This is a simplified implementation. |
| 660 | // In practice, you would traverse both ASTs in parallel |
| 661 | // and identify nodes that differ. |
| 662 | |
| 663 | function traverse( |
| 664 | oldNode: Parser.SyntaxNode | null, |
| 665 | newNode: Parser.SyntaxNode | null, |
| 666 | depth: number = 0, |
| 667 | ) { |
| 668 | if (!oldNode && !newNode) return; |
| 669 | |
| 670 | // If one node exists and the other doesn't, or they're different types. |
| 671 | if ( |
| 672 | (!oldNode && newNode) || |
| 673 | (oldNode && !newNode) || |
| 674 | oldNode?.type !== newNode?.type |
| 675 | ) { |
| 676 | changedNodes.push({ oldNode, newNode, depth }); |
| 677 | return; |
| 678 | } |
| 679 | |
| 680 | // Compare properties. |
| 681 | if (oldNode?.text !== newNode?.text) { |
| 682 | changedNodes.push({ oldNode, newNode, depth }); |
| 683 | } |
| 684 | |
| 685 | // Recursively compare children. |
| 686 | const oldChildCount = oldNode?.childCount || 0; |
| 687 | const newChildCount = newNode?.childCount || 0; |
| 688 | |
| 689 | const maxLength = Math.max(oldChildCount, newChildCount); |
| 690 | for (let i = 0; i < maxLength; i++) { |
| 691 | const oldChild = i < oldChildCount ? oldNode?.child(i) || null : null; |
| 692 | const newChild = i < newChildCount ? newNode?.child(i) || null : null; |
| 693 | traverse(oldChild, newChild, depth + 1); |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | traverse(oldAst.rootNode, newAst.rootNode); |
| 698 | return changedNodes; |
| 699 | } |
| 700 | |
| 701 | // Helper function to get a node's text. |
| 702 | function getNodeText(node: Parser.SyntaxNode): string { |
| 703 | if (!node) return ""; |
| 704 | |
| 705 | return node.text; |
| 706 | } |
| 707 | |
| 708 | // Helper function to get a node's position. |
| 709 | function getNodePosition(node: Parser.SyntaxNode): Position | null { |
| 710 | if (!node) return null; |
| 711 | |
| 712 | // Tree-sitter nodes have startPosition property that contains row and column. |
| 713 | return { |
| 714 | line: node.startPosition.row, |
| 715 | character: node.startPosition.column, |
| 716 | }; |
| 717 | } |
| 718 | |
| 719 | /* OTHER HELPER FUNCTIONS */ |
| 720 | |
| 721 | // Helper function to find all occurrences of text in a string. |
| 722 | function findTextOccurrences(text: string, searchText: string): Range[] { |
| 723 | const results: Range[] = []; |
| 724 | const lines = text.split("\n"); |
| 725 | |
| 726 | for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { |
| 727 | const line = lines[lineIndex]; |
| 728 | let charIndex = 0; |
| 729 | |
| 730 | while (charIndex < line.length) { |
| 731 | const foundIndex = line.indexOf(searchText, charIndex); |
| 732 | if (foundIndex === -1) break; |
| 733 | |
| 734 | results.push({ |
| 735 | start: { line: lineIndex, character: foundIndex }, |
| 736 | end: { line: lineIndex, character: foundIndex + searchText.length }, |
| 737 | }); |
| 738 | |
| 739 | charIndex = foundIndex + 1; |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | return results; |
| 744 | } |
| 745 | |
| 746 | // Helper function to check if a range is within another range. |
| 747 | function isRangeWithin(innerRange: Range, outerRange: Range): boolean { |
| 748 | // Check if the inner range's start position is after or equal to the outer range's start. |
| 749 | const startWithin = |
| 750 | innerRange.start.line > outerRange.start.line || |
| 751 | (innerRange.start.line === outerRange.start.line && |
| 752 | innerRange.start.character >= outerRange.start.character); |
| 753 | |
| 754 | // Check if the inner range's end position is before or equal to the outer range's end. |
| 755 | const endWithin = |
| 756 | innerRange.end.line < outerRange.end.line || |
| 757 | (innerRange.end.line === outerRange.end.line && |
| 758 | innerRange.end.character <= outerRange.end.character); |
| 759 | |
| 760 | return startWithin && endWithin; |
| 761 | } |
| 762 | |
| 763 | // Helper function to check if two ranges overlap. |
| 764 | function doRangesOverlap(range1: Range, range2: Range): boolean { |
| 765 | // Check if one range starts after the other ends |
| 766 | const range1StartsAfterRange2Ends = |
| 767 | range1.start.line > range2.end.line || |
| 768 | (range1.start.line === range2.end.line && |
| 769 | range1.start.character > range2.end.character); |
| 770 | |
| 771 | const range2StartsAfterRange1Ends = |
| 772 | range2.start.line > range1.end.line || |
| 773 | (range2.start.line === range1.end.line && |
| 774 | range2.start.character > range1.end.character); |
| 775 | |
| 776 | // If either condition is true, the ranges don't overlap |
| 777 | return !(range1StartsAfterRange2Ends || range2StartsAfterRange1Ends); |
| 778 | } |
| 779 | |
| 780 | // Helper function to check if the upper part of range1 overlaps with range2. |
| 781 | function doesUpperPartOverlap(range1: Range, range2: Range): boolean { |
| 782 | // Check if range1 starts before range2 ends |
| 783 | const range1StartsBeforeRange2Ends = |
| 784 | range1.start.line < range2.end.line || |
| 785 | (range1.start.line === range2.end.line && |
| 786 | range1.start.character <= range2.end.character); |
| 787 | |
| 788 | // Check if range1 starts before range2 starts (meaning it's "upper" than range2) |
| 789 | const range1StartsBeforeRange2Starts = |
| 790 | range1.start.line < range2.start.line || |
| 791 | (range1.start.line === range2.start.line && |
| 792 | range1.start.character < range2.start.character); |
| 793 | |
| 794 | // The upper part overlaps if range1 starts before range2 ends |
| 795 | // AND range1 starts before range2 starts |
| 796 | return range1StartsBeforeRange2Ends && range1StartsBeforeRange2Starts; |
| 797 | } |
| 798 | |
| 799 | // Helper function to check if the lower part of range1 overlaps with range2. |
| 800 | function doesLowerPartOverlap(range1: Range, range2: Range): boolean { |
| 801 | // Check if range1 starts inside range2 |
| 802 | const range1StartsInsideRange2 = |
| 803 | (range1.start.line > range2.start.line || |
| 804 | (range1.start.line === range2.start.line && |
| 805 | range1.start.character >= range2.start.character)) && |
| 806 | (range1.start.line < range2.end.line || |
| 807 | (range1.start.line === range2.end.line && |
| 808 | range1.start.character < range2.end.character)); |
| 809 | |
| 810 | // Check if range1 ends after range2 ends |
| 811 | const range1EndsAfterRange2 = |
| 812 | range1.end.line > range2.end.line || |
| 813 | (range1.end.line === range2.end.line && |
| 814 | range1.end.character > range2.end.character); |
| 815 | |
| 816 | // The lower part overlaps if range1 starts inside range2 |
| 817 | // AND range1 ends after range2 ends |
| 818 | return range1StartsInsideRange2 && range1EndsAfterRange2; |
| 819 | } |
| 820 | |
| 821 | // Helper function to check if a range overlaps with another range from either end |
| 822 | function doesRangePartiallyOverlap(range1: Range, range2: Range): boolean { |
| 823 | // Upper part overlap: range1 starts before range2 starts but ends inside range2 |
| 824 | const upperPartOverlap = |
| 825 | (range1.start.line < range2.start.line || |
| 826 | (range1.start.line === range2.start.line && |
| 827 | range1.start.character < range2.start.character)) && |
| 828 | (range1.end.line > range2.start.line || |
| 829 | (range1.end.line === range2.start.line && |
| 830 | range1.end.character > range2.start.character)) && |
| 831 | (range1.end.line < range2.end.line || |
| 832 | (range1.end.line === range2.end.line && |
| 833 | range1.end.character <= range2.end.character)); |
| 834 | |
| 835 | // Lower part overlap: range1 starts inside range2 but ends after range2 ends |
| 836 | const lowerPartOverlap = |
| 837 | (range1.start.line > range2.start.line || |
| 838 | (range1.start.line === range2.start.line && |
| 839 | range1.start.character >= range2.start.character)) && |
| 840 | (range1.start.line < range2.end.line || |
| 841 | (range1.start.line === range2.end.line && |
| 842 | range1.start.character < range2.end.character)) && |
| 843 | (range1.end.line > range2.end.line || |
| 844 | (range1.end.line === range2.end.line && |
| 845 | range1.end.character > range2.end.character)); |
| 846 | |
| 847 | return upperPartOverlap || lowerPartOverlap; |
| 848 | } |
| 849 | |
| 850 | // Utility function to print chunks. |
| 851 | function printChunks(chunks: Chunk[]) { |
| 852 | console.log( |
| 853 | "chunks:", |
| 854 | JSON.stringify( |
| 855 | chunks.map((chunk) => ({ |
| 856 | content: chunk.content, |
| 857 | startLine: chunk.startLine, |
| 858 | endLine: chunk.endLine, |
| 859 | })), |
| 860 | null, |
| 861 | 2, |
| 862 | ), |
| 863 | ); |
| 864 | } |