diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts index 0ad669280..13a9c3acb 100644 --- a/core/diff/streamDiff.test.ts +++ b/core/diff/streamDiff.test.ts @@ -224,18 +224,18 @@ describe("streamDiff(", () => { }); test("tabs vs. spaces differences are ignored", async () => { - await expectDiff("fastapi-tabs-vs-spaces"); + await expectDiff("fastapi-tabs-vs-spaces.py"); }); test("FastAPI example", async () => { - await expectDiff("fastapi"); + await expectDiff("fastapi.py"); }); test("FastAPI comments", async () => { - await expectDiff("add-comments"); + await expectDiff("add-comments.py"); }); test("Mock LLM example", async () => { - await expectDiff("mock-llm"); + await expectDiff("mock-llm.ts"); }); }); diff --git a/core/diff/test-examples/add-comments.diff b/core/diff/test-examples/add-comments.py.diff similarity index 100% rename from core/diff/test-examples/add-comments.diff rename to core/diff/test-examples/add-comments.py.diff diff --git a/core/diff/test-examples/fastapi-tabs-vs-spaces.diff b/core/diff/test-examples/fastapi-tabs-vs-spaces.py.diff similarity index 100% rename from core/diff/test-examples/fastapi-tabs-vs-spaces.diff rename to core/diff/test-examples/fastapi-tabs-vs-spaces.py.diff diff --git a/core/diff/test-examples/fastapi.diff b/core/diff/test-examples/fastapi.py.diff similarity index 100% rename from core/diff/test-examples/fastapi.diff rename to core/diff/test-examples/fastapi.py.diff diff --git a/core/diff/test-examples/mock-llm.diff b/core/diff/test-examples/mock-llm.ts.diff similarity index 100% rename from core/diff/test-examples/mock-llm.diff rename to core/diff/test-examples/mock-llm.ts.diff diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts new file mode 100644 index 000000000..ca3a1c40c --- /dev/null +++ b/core/edit/lazy/deterministic.test.ts @@ -0,0 +1,126 @@ +import fs from "node:fs"; + +// @ts-ignore no typings available +import { changed, diff as myersDiff } from "myers-diff"; +import path from "node:path"; +import { DiffLine, DiffLineType } from "../.."; +import { dedent } from "../../util"; +import { deterministicApplyLazyEdit } from "./deterministic"; + +// "modification" is an extra type used to represent an "old" + "new" diff line +type MyersDiffTypes = Extract | "modification"; + +const UNIFIED_DIFF_SYMBOLS = { + same: "", + new: "+", + old: "-", +}; + +async function collectDiffs( + oldFile: string, + newFile: string, + filename: string, +): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> { + const ourDiffs: DiffLine[] = []; + + for (const diffLine of (await deterministicApplyLazyEdit( + oldFile, + newFile, + filename, + )) ?? []) { + ourDiffs.push(diffLine); + } + + const myersDiffs = myersDiff(oldFile, newFile); + + return { ourDiffs, myersDiffs }; +} + +function getMyersDiffType(diff: any): MyersDiffTypes | undefined { + if (changed(diff.rhs) && !changed(diff.lhs)) { + return "new"; + } + + if (!changed(diff.rhs) && changed(diff.lhs)) { + return "old"; + } + + if (changed(diff.rhs) && changed(diff.lhs)) { + return "modification"; + } + + return undefined; +} + +function displayDiff(diff: DiffLine[]) { + return diff + .map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`) + .join("\n"); +} + +async function expectDiff(file: string) { + const testFilePath = path.join( + __dirname, + "edit", + "lazy", + "test-examples", + file + ".diff", + ); + const testFileContents = fs.readFileSync(testFilePath, "utf-8"); + const [oldFile, newFile, expectedDiff] = testFileContents + .split("\n---\n") + .map((s) => s.replace(/^\n+/, "").trimEnd()); + const { ourDiffs: streamDiffs, myersDiffs } = await collectDiffs( + oldFile, + newFile, + file, + ); + const displayedDiff = displayDiff(streamDiffs); + + if (!expectedDiff || expectedDiff.trim() === "") { + console.log( + "Expected diff was empty. Writing computed diff to the test file", + ); + fs.writeFileSync( + testFilePath, + `${oldFile}\n\n---\n\n${newFile}\n\n---\n\n${displayedDiff}`, + ); + + throw new Error("Expected diff is empty"); + } + + expect(displayedDiff).toEqual(expectedDiff); +} + +describe("deterministicApplyLazyEdit(", () => { + test("no changes", async () => { + const file = dedent` + function test() { + return 1; + } + + function test2(a) { + return a * 2; + } + `; + + const { ourDiffs: streamDiffs, myersDiffs } = await collectDiffs( + file, + file, + "test.js", + ); + + expect(streamDiffs).toEqual( + file.split("\n").map((line) => ({ + line, + type: "same", + })), + ); + + expect(myersDiffs).toEqual([]); + }); + + test.only("tabs vs. spaces differences are ignored", async () => { + await expectDiff("fastapi.py"); + }); +}); diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts new file mode 100644 index 000000000..d3da100db --- /dev/null +++ b/core/edit/lazy/deterministic.ts @@ -0,0 +1,136 @@ +import Parser from "web-tree-sitter"; +import { DiffLine } from "../.."; +import { getParserForFile } from "../../util/treeSitter"; + +// TODO: If we don't have high confidence, return undefined to fall back to slower methods +export async function deterministicApplyLazyEdit( + oldFile: string, + newLazyFile: string, + filename: string, +): Promise { + const parser = await getParserForFile(filename); + if (!parser) { + return undefined; + } + + const oldTree = parser.parse(oldFile); + const newTree = parser.parse(newLazyFile); + + const diffLines = diffNodes(oldTree.rootNode, newTree.rootNode); + + return diffLines; +} + +const COMMENT_TYPES = ["comment"]; +const LAZY_COMMENT_REGEX = /\s*...\s*.?\s...$/; +function isLazyBlock(node: Parser.SyntaxNode): boolean { + return ( + COMMENT_TYPES.includes(node.type) && LAZY_COMMENT_REGEX.test(node.text) + ); +} + +/** + * Determine whether two nodes are similar + * @param a + * @param b + * @returns + */ +function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + if (a.type !== b.type) { + return false; + } + + return true; // TODO +} + +function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + return a.text === b.text; +} + +function diffLinesForNode( + node: Parser.SyntaxNode, + type: DiffLine["type"], +): DiffLine[] { + return node.text.split("\n").map((line) => ({ + line, + type, + })); +} + +/** + * Should be like Myers diff, but lazy blocks consume all nodes until the next match + * @param newNode + * @param oldNode + * @returns + */ +function diffNodes( + oldNode: Parser.SyntaxNode, + newNode: Parser.SyntaxNode, +): DiffLine[] { + // Base case + if (nodesAreExact(oldNode, newNode)) { + return diffLinesForNode(newNode, "same"); + } + + const diffLines: DiffLine[] = []; + const leftChildren = oldNode.children; + const rightChildren = newNode.children; + let isLazy = false; + + while (leftChildren.length > 0 && rightChildren.length > 0) { + const L = leftChildren[0]; + const R = rightChildren[0]; + + // Consume lazy block + if (isLazyBlock(R)) { + isLazy = true; + rightChildren.shift(); + continue; + } + + if (isLazy) { + if (nodesAreSimilar(L, R)) { + // L ~= R + + // recurse + const subDiffs = diffNodes(L, R); + diffLines.push(...subDiffs); + + // then consume lazy, L, and R + isLazy = false; + leftChildren.shift(); + rightChildren.shift(); + } else { + // L != R, consume L + leftChildren.shift(); + } + } else { + // When not lazy, we look for the first match of L + const index = rightChildren.findIndex((node) => nodesAreSimilar(L, node)); + + if (index === -1) { + leftChildren.shift(); + diffLines.push( + // TODO: What are we returning? Iterate over the lines? + ...diffLinesForNode(L, "old"), + ); + } else { + // Match found, insert all right nodes before the match + for (let i = 0; i < index; i++) { + diffLines.push(...diffLinesForNode(rightChildren[0], "new")); + rightChildren.shift(); + } + + // then recurse at the match + const subDiffs = diffNodes(L, rightChildren[0]); + diffLines.push(...subDiffs); + + // then consume L and R + leftChildren.shift(); + rightChildren.shift(); + } + } + } + + return diffLines; +} diff --git a/core/edit/lazy/prompts.ts b/core/edit/lazy/prompts.ts index 94c7dd58d..aa8328e76 100644 --- a/core/edit/lazy/prompts.ts +++ b/core/edit/lazy/prompts.ts @@ -18,6 +18,7 @@ const RULES = [ // `You should lean toward using a smaller number of these comments rather than rewriting it for every function if all of them are unchanged.`, // `You may do this for imports as well if needed.`, // `Do not explain your changes either before or after the code block.`, + `The code should always be syntactically valid, even with the comments.`, ]; function claude35SonnetLazyApplyPrompt( diff --git a/core/edit/lazy/test-examples/fastapi.py.diff b/core/edit/lazy/test-examples/fastapi.py.diff new file mode 100644 index 000000000..030d330c6 --- /dev/null +++ b/core/edit/lazy/test-examples/fastapi.py.diff @@ -0,0 +1,37 @@ +from fastapi import FastAPI + +app = FastAPI() + +@app.get("/") +def read_root(): + return {"Hello": "World"} + +@app.get("/landing") +def read_landing_page(): + return {"message": "Welcome to the landing page"} + +--- + +from fastapi import FastAPI, HTTPException + +# ... same ... + +@app.get("/landing") +def read_landing_page(): + raise HTTPException(status_code=404, detail="Page not found") + +--- + +- from fastapi import FastAPI ++ from fastapi import FastAPI, HTTPException + + app = FastAPI() + + @app.get("/") + def read_root(): + return {"Hello": "World"} + + @app.get("/landing") + def read_landing_page(): ++ raise HTTPException(status_code=404, detail="Page not found") +- return {"message": "Welcome to the landing page"} \ No newline at end of file