diff --git a/core/diff/diffLines.ts b/core/diff/diffLines.ts new file mode 100644 index 000000000..6fc3e1768 --- /dev/null +++ b/core/diff/diffLines.ts @@ -0,0 +1,53 @@ +import { matchLine } from "./util"; + +interface DiffLineNew { + type: "new"; + newLine: string; +} + +interface DiffLineOldOrSame { + type: "old" | "same"; +} + +export type DiffLine = DiffLineNew | DiffLineOldOrSame; + +/** + * https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ + */ +async function* streamDiff( + oldLines: string[], + newLines: AsyncGenerator +): AsyncGenerator { + let newLineResult = await newLines.next(); + while (oldLines.length > 0 && !newLineResult.done) { + const newLine = newLineResult.value; + const [matchIndex, isPerfectMatch] = matchLine(newLine, oldLines); + + if (matchIndex < 0) { + yield { type: "new", newLine }; + } else { + for (let i = 0; i < matchIndex; i++) { + yield { type: "old" }; + } + if (isPerfectMatch) { + yield { type: "same" }; + } else { + yield { type: "old" }; + yield { type: "new", newLine }; + } + } + + newLineResult = await newLines.next(); + } + + // Once at the edge, only one choice + if (newLineResult.done === true && oldLines.length > 0) { + for (let _ of oldLines) { + yield { type: "old" }; + } + } else if (!newLineResult.done && oldLines.length === 0) { + for await (const newLine of newLines) { + yield { type: "new", newLine }; + } + } +} diff --git a/core/diff/util.ts b/core/diff/util.ts new file mode 100644 index 000000000..0dcbf0818 --- /dev/null +++ b/core/diff/util.ts @@ -0,0 +1,47 @@ +import { distance } from "fastest-levenshtein"; + +function linesMatchPerfectly(lineA: string, lineB: string): boolean { + return lineA === lineB; +} + +function linesMatch(lineA: string, lineB: string): boolean { + return distance(lineA, lineB) / Math.max(lineA.length, lineB.length) < 0.25; +} + +/** + * Return the index of the first match and whether it is a perfect match + */ +export function matchLine( + newLine: string, + oldLines: string[] +): [number, boolean] { + for (let i = 0; i < oldLines.length; i++) { + if (linesMatchPerfectly(newLine, oldLines[i])) { + return [i, true]; + } else if (linesMatch(newLine, oldLines[i])) { + return [i, false]; + } + } + + return [-1, false]; +} + +/** + * Convert a stream of arbitrary chunks to a stream of lines + */ +export async function* streamLines( + streamCompletion: AsyncGenerator +): AsyncGenerator { + let buffer = ""; + for await (const chunk of streamCompletion) { + buffer += chunk; + const lines = buffer.split("\n"); + buffer = lines.pop() ?? ""; + for (const line of lines) { + yield line; + } + } + if (buffer.length > 0) { + yield buffer; + } +} diff --git a/core/package-lock.json b/core/package-lock.json index 7dc812c88..68f61f675 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -11,6 +11,7 @@ "license": "Apache-2.0", "dependencies": { "dotenv": "^16.3.1", + "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", @@ -2024,6 +2025,14 @@ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", + "engines": { + "node": ">= 4.9.1" + } + }, "node_modules/fb-watchman": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", diff --git a/core/package.json b/core/package.json index f75d51e5d..d3c6e494a 100644 --- a/core/package.json +++ b/core/package.json @@ -24,6 +24,7 @@ }, "dependencies": { "dotenv": "^16.3.1", + "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", "openai": "^4.20.1", diff --git a/extensions/vscode/src/diff/oldVerticalPerLine.ts b/extensions/vscode/src/diff/oldVerticalPerLine.ts new file mode 100644 index 000000000..c4fbcd52b --- /dev/null +++ b/extensions/vscode/src/diff/oldVerticalPerLine.ts @@ -0,0 +1,94 @@ +import { matchLine } from "core/diff/util"; + +interface NextLineEvent { + type: "nextLine"; +} + +interface InsertDeletionEvent { + type: "insertDeletion"; + lines: string[]; + aboveLineAtIndex: number; +} + +interface ReplaceLineEvent { + type: "replaceLine"; + index: number; + newLine: string; +} + +interface InsertLineEvent { + type: "insertLine"; + aboveLineAtIndex: number; + line: string; +} + +type VerticalPerLineDiffEvent = + | NextLineEvent + | InsertDeletionEvent + | ReplaceLineEvent + | InsertLineEvent; + +async function* streamVerticalPerLineDiff( + lineGenerator: AsyncGenerator, + oldCode: string +): AsyncGenerator { + const remainingLines = oldCode.split("\n"); + let index = 0; // Index in terms of oldCode + + let accumulatedDeletedLines: string[] = []; + + for await (const line of lineGenerator) { + const [matchIndex, isPerfectMatch] = matchLine(line, remainingLines); + + if (matchIndex < 0) { + // No match, so insert above remainingLines[0] + yield { + type: "insertLine", + aboveLineAtIndex: index, + line, + }; + } else if (matchIndex === 0) { + if (isPerfectMatch) { + // Perfect match of the next line, so insert and clear existing block + yield { + type: "insertDeletion", + lines: accumulatedDeletedLines, + aboveLineAtIndex: index, + }; + remainingLines.shift(); + accumulatedDeletedLines = []; + } else { + // Replace next line, so part of same block if one exists + yield { + type: "replaceLine", + index, + newLine: line, + }; + + let nextLine = remainingLines.shift(); + nextLine && accumulatedDeletedLines.push(); + } + } else { + // Already in a block, which is disconnected from this one, so insert and clear it + accumulatedDeletedLines.push(...remainingLines.splice(0, matchIndex)); + if (isPerfectMatch) { + yield { + type: "insertDeletion", + lines: accumulatedDeletedLines, + aboveLineAtIndex: index - accumulatedDeletedLines.length, + }; + accumulatedDeletedLines = []; + } else { + // Add to the current block all of the lines in between, then replace with the new line + yield { + type: "insertLine", + aboveLineAtIndex: index - accumulatedDeletedLines.length, + line, + }; + } + } + + index += Math.max(0, matchIndex); + remainingLines.splice(0, matchIndex); + } +} diff --git a/extensions/vscode/src/diff/vertical.ts b/extensions/vscode/src/diff/vertical.ts deleted file mode 100644 index 656158c1c..000000000 --- a/extensions/vscode/src/diff/vertical.ts +++ /dev/null @@ -1,30 +0,0 @@ -interface DiffBlock { - startLine: number; - endLine: number; - replacement: string[]; -} - -function linesMatch(lineA: string, lineB: string): boolean { - return lineA === lineB; -} - -function matchLine(newLine: string, oldLines: string[]): number { - let matchIndex = -1; - for (let i = 0; i < oldLines.length; i++) { - if (linesMatch(newLine, oldLines[i])) { - matchIndex = i; - break; - } - } - - return matchIndex; -} - -async function* streamDiffBlocks( - newLinesStream: AsyncGenerator, - oldCode: string -): AsyncGenerator {} - -// But you also want to stream between the diff blocks. -// So...not only do you want to stream DiffBlocks -// Next is stream lines: {line: string, type: "match" | ""} diff --git a/extensions/vscode/src/diff/verticalPerCharacter.ts b/extensions/vscode/src/diff/verticalPerCharacter.ts new file mode 100644 index 000000000..a7f2d962b --- /dev/null +++ b/extensions/vscode/src/diff/verticalPerCharacter.ts @@ -0,0 +1,90 @@ +import { matchLine } from "core/diff/util"; + +interface DiffBlock { + startLine: number; + endLine: number; + replacement: string[]; +} + +interface LineUpdate { + content: string; + line: number; + replace: boolean; +} + +type DiffEvent = LineUpdate | DiffBlock; + +/** + * Returns a stream of characters, but with "undefined" inserted into the stream whenever there is a new line + */ +async function* streamWithLineBreaks( + completionStream: AsyncGenerator +): AsyncGenerator { + for await (const chunk of completionStream) { + if (chunk.includes("\n")) { + const lines = chunk.split("\n"); + for (let i = 0; i < lines.length; i++) { + yield lines[i]; + if (i < lines.length - 1) { + yield undefined; + } + } + } else { + yield chunk; + } + } +} + +async function* streamDiffEvents( + completionStream: AsyncGenerator, + oldCode: string +): AsyncGenerator { + let remainingLines = oldCode.split("\n"); + let i = 0; + let oldLine = remainingLines.shift(); + let newLine = ""; + let alreadyReplacedCurrentLine = false; + + for await (const chunk of streamWithLineBreaks(completionStream)) { + if (chunk === undefined) { + // Decide whether there is a match + const matchIndex = matchLine(newLine, remainingLines); + // Delete all of the lines in the middle + // TODO + + // Start a new line + oldLine = remainingLines.shift(); + newLine = ""; + alreadyReplacedCurrentLine = false; + i++; + } else { + // Continue current line + newLine += chunk; + + if (oldLine?.startsWith(newLine)) { + // Match, do nothing + } else { + // Difference, send the update + // This also handles when we are past all of the oldLines + if (alreadyReplacedCurrentLine) { + yield { + content: chunk, + line: i, + replace: false, + }; + } else { + yield { + content: newLine, + line: i, + replace: true, + }; + alreadyReplacedCurrentLine = true; + } + } + } + } +} + +// But you also want to stream between the diff blocks. +// So...not only do you want to stream DiffBlocks +// Next is stream lines: {line: string, type: "match" | ""} diff --git a/extensions/vscode/src/diff/verticalPerLine.ts b/extensions/vscode/src/diff/verticalPerLine.ts new file mode 100644 index 000000000..e9e66cc3b --- /dev/null +++ b/extensions/vscode/src/diff/verticalPerLine.ts @@ -0,0 +1,44 @@ +import { DiffLine } from "core/diff/diffLines"; + +class VerticalPerLineDiffHandler { + private startLine: number; + private endLine: number; + private currentLineIndex: number; + + constructor(startLine: number, endLine: number) { + this.startLine = startLine; + this.endLine = endLine; + this.currentLineIndex = startLine; + } + + async *displayVerticalPerLineDiff( + diffLineGenerator: AsyncGenerator + ) { + for await (const diffLine of diffLineGenerator) { + this.handleDiffLine(diffLine); + } + } + + handleDiffLine(diffLine: DiffLine) { + switch (diffLine.type) { + case "same": + this.currentLineIndex++; + break; + case "old": + this.setLineAtIndexRed(this.currentLineIndex); + this.currentLineIndex++; + break; + case "new": + break; + } + + this.updateIndexLineDecorations(); + } + + setLineAtIndexRed(index: number) {} + + updateIndexLineDecorations() { + // Highlight the line at the currentLineIndex + // And lightly highlight all lines between that and endLine + } +}