Elffuss BraidHub

kikocis/continue public

main · 12.6 KiBRawPermalink
1import path from "path";
2
3import { distance } from "fastest-levenshtein";
4import Parser from "web-tree-sitter";
5
6import { DiffLine } from "../..";
7import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo";
8import { myersDiff } from "../../diff/myers";
9import { getParserForFile } from "../../util/treeSitter";
10
11import { findInAst } from "./findInAst";
12
13type AstReplacements = Array<{
14 nodeToReplace: Parser.SyntaxNode;
15 replacementNodes: Parser.SyntaxNode[];
16}>;
17
18const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
19export function isLazyText(text: string): boolean {
20 return LAZY_COMMENT_REGEX.test(text);
21}
22
23function reconstructNewFile(
24 oldFile: string,
25 newFile: string,
26 lazyBlockReplacements: AstReplacements,
27): string {
28 // Sort acc by reverse line number
29 lazyBlockReplacements
30 .sort((a, b) => a.nodeToReplace.startIndex - b.nodeToReplace.startIndex)
31 .reverse();
32
33 // Reconstruct entire file by replacing lazy blocks with the replacement nodes
34 const oldFileLines = oldFile.split("\n");
35 const newFileChars = newFile.split("");
36 for (const {
37 nodeToReplace: lazyBlockNode,
38 replacementNodes,
39 } of lazyBlockReplacements) {
40 // Get the full string from the replacement nodes
41 let replacementText = "";
42 if (replacementNodes.length > 0) {
43 const startPosition = replacementNodes[0].startPosition;
44 const endPosition =
45 replacementNodes[replacementNodes.length - 1].endPosition;
46 const replacementLines = oldFileLines.slice(
47 startPosition.row,
48 endPosition.row + 1,
49 );
50 replacementLines[0] = replacementLines[0].slice(startPosition.column);
51 replacementLines[replacementLines.length - 1] = replacementLines[
52 replacementLines.length - 1
53 ].slice(0, endPosition.column);
54 replacementText = replacementLines.join("\n");
55
56 // Replace the lazy block
57 newFileChars.splice(
58 lazyBlockNode.startIndex,
59 lazyBlockNode.text.length,
60 replacementText,
61 );
62 } else {
63 // If there are no replacements, then we want to strip the surrounding whitespace
64 // The example in calculator-exp.js.diff is a test where this is necessary
65 const lazyBlockStart = lazyBlockNode.startIndex;
66 const lazyBlockEnd = lazyBlockNode.endIndex - 1;
67
68 // Remove leading whitespace up to two new lines
69 let startIndex = lazyBlockStart;
70 let newLinesFound = 0;
71 while (
72 startIndex > 0 &&
73 newFileChars[startIndex - 1]?.trim() === "" &&
74 newLinesFound < 2
75 ) {
76 startIndex--;
77 if (newFileChars[startIndex - 1] === "\n") {
78 newLinesFound++;
79 }
80 }
81
82 // Remove trailing whitespace up to two new lines
83 const charAfter = newFileChars[lazyBlockEnd + 1];
84 const secondCharAfter = newFileChars[lazyBlockEnd + 2];
85 let endIndex = lazyBlockEnd;
86 if (charAfter === "\n") {
87 endIndex++;
88 if (secondCharAfter === "\n") {
89 endIndex++;
90 }
91 }
92
93 // Remove the lazy block
94 newFileChars.splice(startIndex, endIndex - startIndex + 1);
95 }
96 }
97
98 return newFileChars.join("");
99}
100
101const REMOVAL_PERCENTAGE_THRESHOLD = 0.3;
102function shouldRejectDiff(diff: DiffLine[]): boolean {
103 const numRemovals = diff.filter((line) => line.type === "old").length;
104 if (numRemovals / diff.length > REMOVAL_PERCENTAGE_THRESHOLD) {
105 return true;
106 }
107 return false;
108}
109
110function nodeSurroundedInLazyBlocks(
111 parser: Parser,
112
113 file: string,
114 filename: string,
115): { newTree: Parser.Tree; newFile: string } | undefined {
116 const ext = path.extname(filename).slice(1);
117 const language = LANGUAGES[ext];
118 if (language) {
119 const newFile = `${language.singleLineComment} ... existing code ...\n\n${file}\n\n${language.singleLineComment} ... existing code...`;
120 const newTree = parser.parse(newFile);
121
122 return { newTree, newFile };
123 }
124
125 return undefined;
126}
127
128// TODO: If we don't have high confidence, return undefined to fall back to slower methods
129export async function deterministicApplyLazyEdit({
130 oldFile,
131 newLazyFile,
132 filename,
133 /**
134 * Using this as a flag to slowly reintroduce lazy applies.
135 * With this set, we will only attempt to deterministically apply
136 * when there are no lazy blocks and then just replace the whole file,
137 * and otherwise never use instant apply
138 */
139 onlyFullFileRewrite = false,
140}: {
141 oldFile: string;
142 newLazyFile: string;
143 filename: string;
144 onlyFullFileRewrite?: boolean;
145}): Promise<DiffLine[] | undefined> {
146 const parser = await getParserForFile(filename);
147 if (!parser) {
148 return undefined;
149 }
150
151 const oldTree = parser.parse(oldFile);
152 let newTree = parser.parse(newLazyFile);
153 let reconstructedNewFile: string | undefined = undefined;
154
155 if (onlyFullFileRewrite) {
156 if (!isLazyText(newTree.rootNode.text)) {
157 const diff = myersDiff(oldFile, newLazyFile);
158
159 if (shouldRejectDiff(diff)) {
160 return undefined;
161 }
162
163 return diff;
164 } else {
165 return undefined;
166 }
167 }
168
169 // If there is no lazy block anywhere, we add our own to the outsides
170 // so that large chunks of the file don't get removed
171 if (!findInAst(newTree.rootNode, isLazyBlock)) {
172 // First, we need to check whether there are matching (similar) nodes at the root level
173 const firstSimilarNode = findInAst(oldTree.rootNode, (node) =>
174 nodesAreSimilar(node, newTree.rootNode.children[0]),
175 );
176 if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) {
177 // If so, we tack lazy blocks to start and end, and run the usual algorithm
178 const result = nodeSurroundedInLazyBlocks(parser, newLazyFile, filename);
179 if (result) {
180 newLazyFile = result.newFile;
181 newTree = result.newTree;
182 }
183 } else {
184 // If not, we need to recursively search for the nodes that are being rewritten,
185 // and we apply a slightly different algorithm
186 const newCodeNumLines = newTree.rootNode.text.split("\n").length;
187 const matchingNode = findInAst(
188 oldTree.rootNode,
189 (node) => programNodeIsSimilar(newTree.rootNode, node),
190 // This isn't perfect—we want the length of the matching code in the old tree
191 // and the new version could have more lines, or fewer. But should work a lot.
192 (node) => node.text.split("\n").length >= newCodeNumLines,
193 );
194 if (matchingNode) {
195 // Now that we've successfully matched the node from the old tree,
196 // we create the full new lazy file
197 const startIndex = matchingNode.startIndex;
198 const endIndex = matchingNode.endIndex;
199 const oldText = oldTree.rootNode.text;
200 reconstructedNewFile =
201 oldText.slice(0, startIndex) +
202 newTree.rootNode.text +
203 oldText.slice(endIndex);
204 } else {
205 console.warn("No matching node found for lazy block");
206 return undefined;
207 }
208 }
209 }
210
211 if (!reconstructedNewFile) {
212 const replacements: AstReplacements = [];
213 findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
214
215 reconstructedNewFile = reconstructNewFile(
216 oldFile,
217 newLazyFile,
218 replacements,
219 );
220 }
221
222 const diff = myersDiff(oldFile, reconstructedNewFile);
223
224 // If the diff is too messy and seems likely borked, we fall back to LLM strategy
225 if (shouldRejectDiff(diff)) {
226 return undefined;
227 }
228
229 return diff;
230}
231
232function isLazyBlock(node: Parser.SyntaxNode): boolean {
233 // Special case for "{/* ... existing code ... */}"
234 if (
235 node.type === "jsx_expression" &&
236 node.namedChildCount === 1 &&
237 isLazyBlock(node.namedChildren[0])
238 ) {
239 return true;
240 }
241
242 return node.type.includes("comment") && isLazyText(node.text);
243}
244
245function stringsWithinLevDistThreshold(
246 a: string,
247 b: string,
248 threshold: number,
249) {
250 const dist = distance(a, b);
251 return dist / Math.min(a.length, b.length) <= threshold;
252}
253
254function programNodeIsSimilar(
255 programNode: Parser.SyntaxNode,
256 otherNode: Parser.SyntaxNode,
257): boolean {
258 // Check purely based on whether they are similar strings
259 const newLines = programNode.text.split("\n");
260 const oldLines = otherNode.text.split("\n");
261
262 // Check that there is a line that matches the start of the old range
263 const oldFirstLine = oldLines[0].trim();
264 let matchForOldFirstLine = -1;
265 for (let i = 0; i < newLines.length; i++) {
266 if (newLines[i].trim() === oldFirstLine) {
267 matchForOldFirstLine = i;
268 break;
269 }
270 }
271
272 if (matchForOldFirstLine < 0) {
273 return false;
274 }
275
276 // Check that the last lines match each other
277 const oldLastLine = oldLines[oldLines.length - 1].trim();
278 const newLastLine = newLines[newLines.length - 1].trim();
279 if (oldLastLine !== newLastLine) {
280 return false;
281 }
282
283 // Check that the number of matching lines is at least half of the shorter length
284 let matchingLines = 0;
285 for (let i = 0; i < Math.min(newLines.length, oldLines.length); i++) {
286 if (oldLines[i].trim() === newLines[matchForOldFirstLine + i].trim()) {
287 matchingLines += 1;
288 }
289 }
290
291 if (matchingLines >= Math.max(newLines.length, oldLines.length) / 2) {
292 return true;
293 }
294
295 return false;
296}
297
298/**
299 * Determine whether two nodes are similar
300 * @param a
301 * @param b
302 * @returns
303 */
304function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
305 if (a.type !== b.type) {
306 return false;
307 }
308
309 // Check if they have the same name
310 if (
311 a.childForFieldName("name") !== null &&
312 a.childForFieldName("name")?.text === b.childForFieldName("name")?.text
313 ) {
314 return true;
315 }
316
317 if (
318 a.namedChildren[0]?.text === b.namedChildren[0]?.text &&
319 a.children[1]?.text === b.children[1]?.text
320 ) {
321 return true;
322 }
323
324 // Matching jsx_elements needs to be different because they have such a minimal first line
325 if (
326 a.type === "jsx_element" &&
327 b.type === "jsx_element" &&
328 // Check that the tag names match
329 a.namedChildren[0]?.children[1]?.text ===
330 b.namedChildren[0]?.children[1]?.text
331 ) {
332 if (stringsWithinLevDistThreshold(a.text, b.text, 0.3)) {
333 return true;
334 }
335 }
336
337 const lineOneA = a.text.split("\n")[0];
338 const lineOneB = b.text.split("\n")[0];
339
340 return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2);
341}
342
343function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
344 return a.text === b.text;
345}
346
347/**
348 * Should be like Myers diff, but lazy blocks consume all nodes until the next match
349 * @param newNode
350 * @param oldNode
351 * @returns
352 */
353function findLazyBlockReplacements(
354 oldNode: Parser.SyntaxNode,
355 newNode: Parser.SyntaxNode,
356 replacements: AstReplacements,
357): void {
358 // Base case
359 if (nodesAreExact(oldNode, newNode)) {
360 return;
361 }
362
363 // Other base case: no lazy blocks => use line-by-line diff
364 if (!findInAst(newNode, isLazyBlock)) {
365 return;
366 }
367
368 const leftChildren = oldNode.namedChildren;
369 const rightChildren = newNode.namedChildren;
370 let isLazy = false;
371 let currentLazyBlockNode: Parser.SyntaxNode | undefined = undefined;
372 const currentLazyBlockReplacementNodes = [];
373
374 while (leftChildren.length > 0 && rightChildren.length > 0) {
375 const L = leftChildren[0];
376 const R = rightChildren[0];
377
378 // Consume lazy block
379 if (isLazyBlock(R)) {
380 // Enter "lazy mode"
381 isLazy = true;
382 currentLazyBlockNode = R;
383 rightChildren.shift();
384 continue;
385 }
386
387 // Look for the first match of L
388 const index = rightChildren.findIndex((node) => nodesAreSimilar(L, node));
389
390 if (index === -1) {
391 // No match
392 if (isLazy) {
393 // Add to replacements if in lazy mode
394 currentLazyBlockReplacementNodes.push(L);
395 }
396
397 // Consume
398 leftChildren.shift();
399 } else {
400 // Match found, insert all right nodes before the match
401 for (let i = 0; i < index; i++) {
402 rightChildren.shift();
403 }
404
405 // then recurse at the match
406 findLazyBlockReplacements(L, rightChildren[0], replacements);
407
408 // then consume L and R
409 leftChildren.shift();
410 rightChildren.shift();
411
412 // Exit "lazy mode"
413 if (isLazy) {
414 // Record the replacement lines
415 replacements.push({
416 nodeToReplace: currentLazyBlockNode!,
417 replacementNodes: [...currentLazyBlockReplacementNodes],
418 });
419 isLazy = false;
420 currentLazyBlockReplacementNodes.length = 0;
421 currentLazyBlockNode = undefined;
422 }
423 }
424 }
425
426 if (isLazy) {
427 replacements.push({
428 nodeToReplace: currentLazyBlockNode!,
429 replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren],
430 });
431 }
432
433 // Cut out any extraneous lazy blocks
434 for (const R of rightChildren) {
435 if (isLazyBlock(R)) {
436 replacements.push({
437 nodeToReplace: R,
438 replacementNodes: [],
439 });
440 }
441 }
442}