Elffuss BraidHub

kikocis/continue public

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