Create processSingleLineCompletion pure function with unit tests

This commit is contained in:
ferenci84 2025-02-07 22:44:20 +01:00
parent 3ee6c3b168
commit be2c9cb92d
5 changed files with 331 additions and 66 deletions

View file

@ -0,0 +1,62 @@
import { processTestCase, type CompletionTestCase } from './completionTestUtils';
describe('processTestCase utility', () => {
it('processes simple console.log completion', () => {
const testCase: CompletionTestCase = {
original: 'console.log(|cur||till|)',
completion: '"foo,", bar',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar',
currentText: ')',
cursorPosition: 'console.log('.length,
},
expectedResult: {
completionText: '"foo,", bar',
},
});
});
it('processes simple console.log completion with overwriting', () => {
const testCase: CompletionTestCase = {
original: 'console.log(|cur|)|till|',
completion: '"foo,", bar);',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar);',
currentText: ')',
cursorPosition: 'console.log('.length,
},
expectedResult: {
completionText: '"foo,", bar);',
range: {
start: 'console.log('.length,
end: 'console.log()'.length
},
},
});
});
it('partially applying completion', () => {
const testCase: CompletionTestCase = {
original: '|cur||till|fetch("https://example.com");',
completion: 'await fetch("https://example.com");',
appliedCompletion: 'await '
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: 'await fetch("https://example.com");',
currentText: 'fetch("https://example.com");',
cursorPosition: 0,
},
expectedResult: {
completionText: 'await '
},
});
});
});

View file

@ -0,0 +1,63 @@
export interface CompletionTestCase {
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
}
export interface ProcessedTestCase {
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
};
}
export function processTestCase({
original,
completion,
appliedCompletion = null,
cursorMarker = '|cur|',
tillMarker = '|till|',
}: CompletionTestCase): ProcessedTestCase {
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error('Cursor marker not found in original text');
}
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, '');
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, '')
}
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range: cursorPos === tillPos ? undefined : {
start: cursorPos,
end: tillPos,
},
},
};
}

View file

@ -0,0 +1,97 @@
import { processTestCase } from './completionTestUtils';
import { processSingleLineCompletion } from './processSingleLineCompletion';
describe('processSingleLineCompletion', () => {
it('should handle simple end of line completion', () => {
const testCase = processTestCase({
original: 'console.log(|cur|',
completion: '"Hello, world!")',
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it('should handle midline insert repeating the end of line', () => {
const testCase = processTestCase({
original: 'console.log(|cur|);|till|',
completion: '"Hello, world!");',
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it('should handle midline insert repeating the end of line plus adding a semicolon', () => {
const testCase = processTestCase({
original: 'console.log(|cur|)|till|',
completion: '"Hello, world!");',
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it('should handle simple midline insert', () => {
const testCase = processTestCase({
original: 'console.log(|cur|)',
completion: '"Hello, world!"',
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it('should handle complex dif with addition in the beginning', () => {
const testCase = processTestCase({
original: 'console.log(|cur||till|, "param1", )', // TODO
completion: '"Hello world!", "param1", param1);',
appliedCompletion: '"Hello world!"'
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it('should handle simple insertion even with random equality', () => {
const testCase = processTestCase({
original: 'print(f"Foobar length: |cur||till|")',
completion: '{len(foobar)}',
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
});

View file

@ -0,0 +1,92 @@
import * as Diff from "diff"
interface SingleLineCompletionResult {
completionText: string;
range?: {
start: number;
end: number;
};
}
interface DiffType {
count?: number;
added?: boolean;
removed?: boolean;
value: string;
}
function diffPatternMatches(
diffs: DiffType[],
pattern: DiffPartType[],
): boolean {
if (diffs.length !== pattern.length) {
return false;
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
return true;
}
type DiffPartType = "+" | "-" | "=";
export function processSingleLineCompletion(
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number
): SingleLineCompletionResult | undefined {
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
return {
completionText: lastLineOfCompletionText,
};
}

View file

@ -24,8 +24,7 @@ import {
import type { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { IDE } from "core";
const Diff = require("diff");
import { processSingleLineCompletion } from "core/autocomplete/util/processSingleLineCompletion";
interface DiffType {
count: number;
@ -258,54 +257,29 @@ export class ContinueCompletionProvider
const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
if (isSingleLineCompletion) {
const lastLineOfCompletionText = completionText.split("\n").pop();
const lastLineOfCompletionText = completionText.split("\n").pop() || "";
const currentText = document
.lineAt(startPos)
.text.substring(startPos.character);
const diffs: DiffType[] = Diff.diffWords(
currentText,
const result = processSingleLineCompletion(
lastLineOfCompletionText,
currentText,
startPos.character
);
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
} else if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
range = new vscode.Range(
startPos,
document.lineAt(startPos).range.end,
);
} else if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
// We want to move the cursor to the end of the line
// range = new vscode.Range(
// startPos,
// document.lineAt(startPos).range.end,
// );
// // Find the last removed part of the diff
// const lastRemovedIndex = findLastIndex(
// diffs,
// (diff) => diff.removed === true,
// );
// const lastRemovedContent = diffs[lastRemovedIndex].value;
// completionText += lastRemovedContent;
} else {
// Diff is too complicated, just insert the first added part of the diff
// This is the safe way to ensure that it is displayed
if (diffs[0]?.added) {
completionText = diffs[0].value;
} else {
// If the first part of the diff isn't an insertion, then the model is
// probably rewriting other parts of the line
// return undefined; - Let's assume it's simply an insertion
}
if (result === undefined) {
return undefined;
}
completionText = result.completionText;
if (result.range) {
range = new vscode.Range(
new vscode.Position(startPos.line, result.range.start),
new vscode.Position(startPos.line, result.range.end)
);
}
} else {
// Extend the range to the end of the line for multiline completions
range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
@ -352,26 +326,3 @@ export class ContinueCompletionProvider
return true;
}
}
type DiffPartType = "+" | "-" | "=";
function diffPatternMatches(
diffs: DiffType[],
pattern: DiffPartType[],
): boolean {
if (diffs.length !== pattern.length) {
return false;
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
return true;
}