lazy ast diff algorithm

This commit is contained in:
Nate 2024-09-13 01:13:06 -07:00
parent aca3f1652f
commit 396ca3e704
9 changed files with 304 additions and 4 deletions

View file

@ -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");
});
});

View file

@ -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<DiffLineType, "new" | "old"> | "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");
});
});

View file

@ -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<DiffLine[] | undefined> {
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;
}

View file

@ -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(

View file

@ -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"}