From b0d382277dc07768056a5ebffc948e92fe151850 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 22 Dec 2024 22:18:29 -0500 Subject: [PATCH] new tests for edge cases --- core/edit/lazy/deterministic.test.ts | 8 ++ core/edit/lazy/deterministic.ts | 110 ++++++++++++++++-- core/edit/lazy/findInAst.ts | 6 +- .../calculator-class-neglected.js.diff | 103 ++++++++++++++++ .../calculator-only-method.js.diff | 99 ++++++++++++++++ 5 files changed, 315 insertions(+), 11 deletions(-) create mode 100644 core/edit/lazy/test-examples/calculator-class-neglected.js.diff create mode 100644 core/edit/lazy/test-examples/calculator-only-method.js.diff diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index 997c24c3a..7590e5025 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -158,4 +158,12 @@ describe("deterministicApplyLazyEdit(", () => { test("should acknowledge jsx_expression lazy comments", async () => { await expectDiff("migration-page.tsx"); }); + + test.skip("should handle case where surrounding class is neglected, with lazy block surrounding", async () => { + await expectDiff("calculator-class-neglected.js"); + }); + + test("should handle case where surrounding class is neglected, without lazy block surrounding", async () => { + await expectDiff("calculator-only-method.js"); + }); }); diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 564656d23..99d5c9a01 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -102,6 +102,24 @@ function shouldRejectDiff(diff: DiffLine[]): boolean { return false; } +function nodeSurroundedInLazyBlocks( + parser: Parser, + + file: string, + filename: string, +): { newTree: Parser.Tree; newFile: string } | undefined { + const ext = path.extname(filename).slice(1); + const language = LANGUAGES[ext]; + if (language) { + const newFile = `${language.singleLineComment} ... existing code ...\n\n${file}\n\n${language.singleLineComment} ... existing code...`; + const newTree = parser.parse(newFile); + + return { newTree, newFile }; + } + + return undefined; +} + // TODO: If we don't have high confidence, return undefined to fall back to slower methods export async function deterministicApplyLazyEdit( oldFile: string, @@ -115,6 +133,7 @@ export async function deterministicApplyLazyEdit( const oldTree = parser.parse(oldFile); let newTree = parser.parse(newLazyFile); + let reconstructedNewFile: string | undefined = undefined; // If there is no lazy block anywhere, we add our own to the outsides // so that large chunks of the file don't get removed @@ -125,24 +144,51 @@ export async function deterministicApplyLazyEdit( ); if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) { // If so, we tack lazy blocks to start and end, and run the usual algorithm - const ext = path.extname(filename).slice(1); - const language = LANGUAGES[ext]; - if (language) { - newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`; - newTree = parser.parse(newLazyFile); + const result = nodeSurroundedInLazyBlocks(parser, newLazyFile, filename); + if (result) { + newLazyFile = result.newFile; + newTree = result.newTree; } } else { // If not, we need to recursively search for the nodes that are being rewritten, // and we apply a slightly different algorithm - return undefined; // TODO + const newCodeNumLines = newTree.rootNode.text.split("\n").length; + const matchingNode = findInAst( + oldTree.rootNode, + (node) => programNodeIsSimilar(newTree.rootNode, node), + // This isn't perfect—we want the length of the matching code in the old tree + // and the new version could have more lines, or fewer. But should work a lot. + (node) => node.text.split("\n").length >= newCodeNumLines, + ); + if (matchingNode) { + // Now that we've successfully matched the node from the old tree, + // we create the full new lazy file + const startIndex = matchingNode.startIndex; + const endIndex = matchingNode.endIndex; + const oldText = oldTree.rootNode.text; + reconstructedNewFile = + oldText.slice(0, startIndex) + + newTree.rootNode.text + + oldText.slice(endIndex); + } else { + console.warn("No matching node found for lazy block"); + return []; + } } } - const replacements: AstReplacements = []; - findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); + if (!reconstructedNewFile) { + const replacements: AstReplacements = []; + findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); - const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements); - const diff = myersDiff(oldFile, newFullFile); + reconstructedNewFile = reconstructNewFile( + oldFile, + newLazyFile, + replacements, + ); + } + + const diff = myersDiff(oldFile, reconstructedNewFile); // If the diff is too messy and seems likely borked, we fall back to LLM strategy if (shouldRejectDiff(diff)) { @@ -179,6 +225,50 @@ function stringsWithinLevDistThreshold( return dist / Math.min(a.length, b.length) <= threshold; } +function programNodeIsSimilar( + programNode: Parser.SyntaxNode, + otherNode: Parser.SyntaxNode, +): boolean { + // Check purely based on whether they are similar strings + const newLines = programNode.text.split("\n"); + const oldLines = otherNode.text.split("\n"); + + // Check that there is a line that matches the start of the old range + const oldFirstLine = oldLines[0].trim(); + let matchForOldFirstLine = -1; + for (let i = 0; i < newLines.length; i++) { + if (newLines[i].trim() === oldFirstLine) { + matchForOldFirstLine = i; + break; + } + } + + if (matchForOldFirstLine < 0) { + return false; + } + + // Check that the last lines match each other + const oldLastLine = oldLines[oldLines.length - 1].trim(); + const newLastLine = newLines[newLines.length - 1].trim(); + if (oldLastLine !== newLastLine) { + return false; + } + + // Check that the number of matching lines is at least half of the shorter length + let matchingLines = 0; + for (let i = 0; i < Math.min(newLines.length, oldLines.length); i++) { + if (oldLines[i].trim() === newLines[matchForOldFirstLine + i].trim()) { + matchingLines += 1; + } + } + + if (matchingLines >= Math.max(newLines.length, oldLines.length) / 2) { + return true; + } + + return false; +} + /** * Determine whether two nodes are similar * @param a diff --git a/core/edit/lazy/findInAst.ts b/core/edit/lazy/findInAst.ts index 9f47355b8..93809ea20 100644 --- a/core/edit/lazy/findInAst.ts +++ b/core/edit/lazy/findInAst.ts @@ -3,6 +3,7 @@ import Parser from "web-tree-sitter"; export function findInAst( node: Parser.SyntaxNode, criterion: (node: Parser.SyntaxNode) => boolean, + shouldRecurse: (node: Parser.SyntaxNode) => boolean = () => true, ): Parser.SyntaxNode | null { const stack = [node]; while (stack.length > 0) { @@ -10,7 +11,10 @@ export function findInAst( if (criterion(node)) { return node; } - stack.push(...node.children); + + if (shouldRecurse(node)) { + stack.push(...node.children); + } } return null; } diff --git a/core/edit/lazy/test-examples/calculator-class-neglected.js.diff b/core/edit/lazy/test-examples/calculator-class-neglected.js.diff new file mode 100644 index 000000000..eb6dcc285 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-class-neglected.js.diff @@ -0,0 +1,103 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +// ... existing code ... + + /** + * Divides the current result by the given number + * @param {number} number - The number to divide by + * @throws {Error} If attempting to divide by zero + * @returns {Calculator} The calculator instance for chaining + */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + +// ... existing code ... + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + ++ /** ++ * Divides the current result by the given number ++ * @param {number} number - The number to divide by ++ * @throws {Error} If attempting to divide by zero ++ * @returns {Calculator} The calculator instance for chaining ++ */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-only-method.js.diff b/core/edit/lazy/test-examples/calculator-only-method.js.diff new file mode 100644 index 000000000..6f69d0142 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-only-method.js.diff @@ -0,0 +1,99 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + + /** + * Divides the current result by the given number + * @param {number} number - The number to divide by + * @throws {Error} If attempting to divide by zero + * @returns {Calculator} The calculator instance for chaining + */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + ++ /** ++ * Divides the current result by the given number ++ * @param {number} number - The number to divide by ++ * @throws {Error} If attempting to divide by zero ++ * @returns {Calculator} The calculator instance for chaining ++ */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file