Elffuss BraidHub

kikocis/continue public

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