refactor: clean up code, add tests

This commit is contained in:
tomasz-io 2024-11-21 10:39:59 -08:00
parent 85d8581230
commit 78ef8fe118
14 changed files with 103 additions and 73 deletions

View file

@ -10,7 +10,7 @@ import { aggregateSnippets } from "./aggregateSnippets";
// @prettier-ignore
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import { AutocompleteSnippet } from "./context/ranking/index.js";
import { AutocompleteSnippetDeprecated } from "./context/ranking/index.js";
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
@ -38,7 +38,7 @@ export type GetLspDefinitionsFunction = (
cursorIndex: number,
ide: IDE,
lang: AutocompleteLanguageInfo,
) => Promise<AutocompleteSnippet[]>;
) => Promise<AutocompleteSnippetDeprecated[]>;
export class CompletionProvider {
private autocompleteCache = AutocompleteLruCache.get();
@ -291,7 +291,7 @@ export class CompletionProvider {
private async _getExtraSnippets(
helper: HelperVars,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
let extraSnippets = helper.options.useOtherFiles
? ((await Promise.race([
this.getDefinitionsFromLsp(
@ -304,7 +304,7 @@ export class CompletionProvider {
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
])) as AutocompleteSnippetDeprecated[])
: [];
const workspaceDirs = await this.ide.getWorkspaceDirs();

View file

@ -2,14 +2,14 @@ import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,
rankAndOrderSnippets,
type AutocompleteSnippet,
type AutocompleteSnippetDeprecated,
} from "./context/ranking/index.js";
import { HelperVars } from "./util/HelperVars.js";
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
caretWindow: string,
): AutocompleteSnippet[] {
): AutocompleteSnippetDeprecated[] {
return snippets
.map((snippet) => ({ ...snippet }))
.filter(
@ -20,9 +20,9 @@ function filterSnippetsAlreadyInCaretWindow(
export async function aggregateSnippets(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
extraSnippets: AutocompleteSnippetDeprecated[],
contextRetrievalService: ContextRetrievalService,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
helper,
extraSnippets,

View file

@ -3,7 +3,7 @@ import { HelperVars } from "../util/HelperVars";
import { RecentlyEditedRange } from "../util/types";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking";
import { AutocompleteSnippetDeprecated, getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
export class ContextRetrievalService {
@ -20,13 +20,13 @@ export class ContextRetrievalService {
public async retrieveCandidateSnippets(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
extraSnippets: AutocompleteSnippetDeprecated[],
) {
if (helper.options.useOtherFiles === false) {
return [];
}
let snippets: AutocompleteSnippet[] = [];
let snippets: AutocompleteSnippetDeprecated[] = [];
// Snippets injected by the IDE for IDE-specific reasons
snippets.push(...extraSnippets);
@ -52,7 +52,7 @@ export class ContextRetrievalService {
private getSnippetsFromRecentlyEditedRanges(
helper: HelperVars,
): AutocompleteSnippet[] {
): AutocompleteSnippetDeprecated[] {
if (helper.options.useRecentlyEdited === false) {
return [];
}
@ -85,7 +85,7 @@ export class ContextRetrievalService {
private async getSnippetsFromImportDefinitions(
helper: HelperVars,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
if (helper.options.useImports === false) {
return [];
}

View file

@ -3,7 +3,12 @@ import { Range } from "../../../index.js";
import { countTokens } from "../../../llm/countTokens.js";
import { HelperVars } from "../../util/HelperVars.js";
export type AutocompleteSnippet = RangeInFileWithContents & {
/**
* @deprecated This type should be removed in the future or renamed.
* We have a new interface called AutocompleteSnippet which is more
* general.
*/
export type AutocompleteSnippetDeprecated = RangeInFileWithContents & {
score?: number;
};
@ -43,9 +48,9 @@ export function jaccardSimilarity(a: string, b: string): number {
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
*/
export function rankAndOrderSnippets(
ranges: AutocompleteSnippet[],
ranges: AutocompleteSnippetDeprecated[],
helper: HelperVars,
): Required<AutocompleteSnippet>[] {
): Required<AutocompleteSnippetDeprecated>[] {
const windowAroundCursor =
helper.fullPrefix.slice(
-helper.options.slidingWindowSize *
@ -56,11 +61,14 @@ export function rankAndOrderSnippets(
(1 - helper.options.slidingWindowPrefixPercentage),
);
const snippets: Required<AutocompleteSnippet>[] = ranges.map((snippet) => ({
score:
snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),
...snippet,
}));
const snippets: Required<AutocompleteSnippetDeprecated>[] = ranges.map(
(snippet) => ({
score:
snippet.score ??
jaccardSimilarity(snippet.contents, windowAroundCursor),
...snippet,
}),
);
const uniqueSnippets = deduplicateSnippets(snippets);
return uniqueSnippets.sort((a, b) => a.score - b.score);
}
@ -69,10 +77,12 @@ export function rankAndOrderSnippets(
* Deduplicate code snippets by merging overlapping ranges into a single range.
*/
export function deduplicateSnippets(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
snippets: Required<AutocompleteSnippetDeprecated>[],
): Required<AutocompleteSnippetDeprecated>[] {
// Group by file
const fileGroups: { [key: string]: Required<AutocompleteSnippet>[] } = {};
const fileGroups: {
[key: string]: Required<AutocompleteSnippetDeprecated>[];
} = {};
for (const snippet of snippets) {
if (!fileGroups[snippet.filepath]) {
fileGroups[snippet.filepath] = [];
@ -89,8 +99,8 @@ export function deduplicateSnippets(
}
function mergeSnippetsByRange(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
snippets: Required<AutocompleteSnippetDeprecated>[],
): Required<AutocompleteSnippetDeprecated>[] {
if (snippets.length <= 1) {
return snippets;
}
@ -98,7 +108,7 @@ function mergeSnippetsByRange(
const sorted = snippets.sort(
(a, b) => a.range.start.line - b.range.start.line,
);
const merged: Required<AutocompleteSnippet>[] = [];
const merged: Required<AutocompleteSnippetDeprecated>[] = [];
while (sorted.length > 0) {
const next = sorted.shift()!;
@ -134,12 +144,12 @@ function mergeOverlappingRangeContents(
* It is assumed that the snippets are sorted by score.
*/
export function fillPromptWithSnippets(
snippets: Required<AutocompleteSnippet>[],
snippets: Required<AutocompleteSnippetDeprecated>[],
maxSnippetTokens: number,
modelName: string,
): Required<AutocompleteSnippet>[] {
): Required<AutocompleteSnippetDeprecated>[] {
let tokensRemaining = maxSnippetTokens;
const keptSnippets: Required<AutocompleteSnippet>[] = [];
const keptSnippets: Required<AutocompleteSnippetDeprecated>[] = [];
for (let i = 0; i < snippets.length; i++) {
const snippet = snippets[i];
const tokenCount = countTokens(snippet.contents, modelName);

View file

@ -1,6 +1,6 @@
import { RangeInFileWithContents } from "../../../commands/util.js";
import { AutocompleteSnippet, jaccardSimilarity } from "./index.js";
import { AutocompleteSnippetDeprecated, jaccardSimilarity } from "./index.js";
function* slidingWindow(
content: string,
@ -37,9 +37,9 @@ export async function slidingWindowMatcher(
windowAroundCursor: string,
topN: number,
windowSize: number,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
// Sorted lowest similarity to highest
const topMatches: Required<AutocompleteSnippet>[] = [];
const topMatches: Required<AutocompleteSnippetDeprecated>[] = [];
for (const { filepath, contents, range } of recentFiles) {
for (const window of slidingWindow(contents, windowSize)) {

View file

@ -12,7 +12,7 @@ import {
} from "../../../util/treeSitter";
import { AstPath } from "../../util/ast";
import { ImportDefinitionsService } from "../ImportDefinitionsService";
import { AutocompleteSnippet } from "../ranking";
import { AutocompleteSnippetDeprecated } from "../ranking";
function getSyntaxTreeString(
node: Parser.SyntaxNode,
@ -30,7 +30,7 @@ function getSyntaxTreeString(
}
export class RootPathContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
private cache = new LRUCache<string, AutocompleteSnippetDeprecated[]>({
max: 100,
});
@ -72,8 +72,8 @@ export class RootPathContextService {
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
): Promise<AutocompleteSnippetDeprecated[]> {
const snippets: AutocompleteSnippetDeprecated[] = [];
const language = getFullLanguageName(filepath);
let query: Parser.Query | undefined;
@ -123,7 +123,7 @@ export class RootPathContextService {
filepath: string,
endPosition: Parser.Point,
language: LanguageName,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
@ -153,8 +153,8 @@ export class RootPathContextService {
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
): Promise<AutocompleteSnippetDeprecated[]> {
const snippets: AutocompleteSnippetDeprecated[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>

View file

@ -1565,7 +1565,19 @@ interface User {
age: number;
}`,
},
{
description: "Should autocomplete TypeScript interface declarations",
filename: "autocomplete.ts",
input: `interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {}
interface AutocompleteCodeSnippet`,
llmOutput: ` extends BaseAutocompleteSnippet {
filepath: string;
}`,
expectedCompletion: ` extends BaseAutocompleteSnippet {
filepath: string;
}`,
},
{
description:
"Should autocomplete a TypeScript arrow function inside a variable assignment",

View file

@ -54,7 +54,6 @@ export async function testAutocompleteFiltering(
const line = prefix.split("\n").length - 1;
const character = prefix.split("\n")[line].length;
const autocompleteInput: AutocompleteInput = {
clipboardText: "",
completionId: "test-completion-id",
filepath,
pos: {

View file

@ -0,0 +1,17 @@
interface BaseAutocompleteSnippet {
score?: number;
content: string;
}
export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet {
filepath: string;
}
export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {}
export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {}
export type AutocompleteSnippet =
| AutocompleteCodeSnippet
| AutocompleteDiffSnippet
| AutocompleteClipboardSnippet;

View file

@ -2,7 +2,7 @@
import { CompletionOptions } from "../../index.js";
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
import { AutocompleteSnippet } from "../context/ranking/index.js";
import { AutocompleteSnippetDeprecated } from "../context/ranking/index.js";
export interface AutocompleteTemplate {
compilePrefixSuffix?: (
@ -10,7 +10,7 @@ export interface AutocompleteTemplate {
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
) => [string, string];
template:
| string
@ -20,7 +20,7 @@ export interface AutocompleteTemplate {
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
) => string);
completionOptions?: Partial<CompletionOptions>;
}
@ -73,7 +73,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
): [string, string] => {
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
@ -101,7 +101,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
): string => {
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
},
@ -133,7 +133,7 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
filename: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
): string => {
const otherFiles =
snippets.length === 0
@ -187,7 +187,7 @@ const codegeexFimTemplate: AutocompleteTemplate = {
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
): string => {
const relativePaths = shortestRelativePaths([
...snippets.map((snippet) => snippet.filepath),
@ -233,7 +233,7 @@ const holeFillerTemplate: AutocompleteTemplate = {
filename: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
) => {
// From https://github.com/VictorTaelin/AI-scripts
const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a <COMPLETION/> XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct.

View file

@ -3,7 +3,7 @@ import Handlebars from "handlebars";
import { CompletionOptions } from "../..";
import { getBasename, getLastNPathParts } from "../../util";
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
import { AutocompleteSnippet } from "../context/ranking";
import { AutocompleteSnippetDeprecated } from "../context/ranking";
import { HelperVars } from "../util/HelperVars";
import {
@ -34,7 +34,7 @@ export function formatExternalSnippet(
}
function getContextComments(
snippets: AutocompleteSnippet[],
snippets: AutocompleteSnippetDeprecated[],
lang: AutocompleteLanguageInfo,
filepath: string,
) {
@ -137,7 +137,7 @@ export function renderPrompt({
diff,
clipboardContent,
}: {
snippets: AutocompleteSnippet[];
snippets: AutocompleteSnippetDeprecated[];
workspaceDirs: string[];
helper: HelperVars;
diff?: string;

View file

@ -13,7 +13,6 @@ export interface AutocompleteInput {
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RecentlyEditedRange[];
clipboardText: string;
// Used for notebook files
manuallyPassFileContents?: string;
// Used for VS Code git commit input box

View file

@ -42,7 +42,7 @@ export class ContinueCompletionProvider
e.message,
this.configHandler.reloadConfig.bind(this.configHandler),
() => {
void this.webviewProtocol.request("openOnboardingCard", undefined)
void this.webviewProtocol.request("openOnboardingCard", undefined);
},
);
return;
@ -153,12 +153,6 @@ export class ContinueCompletionProvider
const signal = abortController.signal;
token.onCancellationRequested(() => abortController.abort());
const config = await this.configHandler.loadConfig();
let clipboardText = "";
if (config.tabAutocompleteOptions?.useCopyBuffer === true) {
clipboardText = await vscode.env.clipboard.readText();
}
// Handle notebook cells
const pos = {
line: position.line,
@ -194,12 +188,6 @@ export class ContinueCompletionProvider
}
// Handle commit message input box
let manuallyPassPrefix: string | undefined = undefined;
if (document.uri.scheme === "vscode-scm") {
return null;
// let diff = await this.ide.getDiff();
// diff = diff.split("\n").splice(-150).join("\n");
// manuallyPassPrefix = `${diff}\n\nCommit message: `;
}
const input: AutocompleteInput = {
completionId: uuidv4(),
@ -208,7 +196,6 @@ export class ContinueCompletionProvider
recentlyEditedFiles: [],
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
clipboardText: clipboardText,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,

View file

@ -1,6 +1,6 @@
import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider";
import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo";
import { AutocompleteSnippet } from "core/autocomplete/context/ranking";
import { AutocompleteSnippetDeprecated } from "core/autocomplete/context/ranking";
import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast";
import { RangeInFileWithContents } from "core/commands/util";
import {
@ -134,7 +134,9 @@ async function crawlTypes(
// Parse AST
const ast = await getAst(rif.filepath, contents);
if (!ast) {return results;}
if (!ast) {
return results;
}
const astLineCount = ast.rootNode.text.split("\n").length;
// Find type identifiers
@ -340,13 +342,17 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async (
cursorIndex: number,
ide: IDE,
lang: AutocompleteLanguageInfo,
): Promise<AutocompleteSnippet[]> => {
): Promise<AutocompleteSnippetDeprecated[]> => {
try {
const ast = await getAst(filepath, contents);
if (!ast) {return [];}
if (!ast) {
return [];
}
const treePath = await getTreePathAtCursor(ast, cursorIndex);
if (!treePath) {return [];}
if (!treePath) {
return [];
}
const results: RangeInFileWithContents[] = [];
for (const node of treePath.reverse()) {