Elffuss BraidHub

kikocis/continue public

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