⚡️ deduplicate autocomplete snippets

This commit is contained in:
Nate Sesti 2024-02-24 23:35:34 -05:00
parent 28a8e81cb9
commit e147b5abfe
5 changed files with 114 additions and 36 deletions

View file

@ -1,5 +1,5 @@
import Parser from "web-tree-sitter";
import { FileWithContents, TabAutocompleteOptions } from "..";
import { TabAutocompleteOptions } from "..";
import { RangeInFileWithContents } from "../commands/util";
import {
countTokens,
@ -72,10 +72,10 @@ export async function constructAutocompletePrompt(
filepath: string,
line: number,
character: number
) => Promise<FileWithContents | undefined>,
) => Promise<RangeInFileWithContents | undefined>,
options: TabAutocompleteOptions,
recentlyEditedRanges: RangeInFileWithContents[],
recentlyEditedDocuments: FileWithContents[]
recentlyEditedDocuments: RangeInFileWithContents[]
): Promise<{
prefix: string;
suffix: string;
@ -83,7 +83,7 @@ export async function constructAutocompletePrompt(
completeMultiline: boolean;
}> {
// Find external snippets
let snippets: FileWithContents[] = [];
let snippets: RangeInFileWithContents[] = [];
const windowAroundCursor =
fullPrefix.slice(
@ -107,10 +107,7 @@ export async function constructAutocompletePrompt(
const scope = await getScopeAroundRange(r);
if (!scope) return null;
return {
filepath: r.filepath,
contents: r.contents,
};
return r;
})
.filter((s) => !!s)
);
@ -155,7 +152,10 @@ export async function constructAutocompletePrompt(
}
// Rank / order the snippets
snippets = rankSnippets(snippets, windowAroundCursor);
snippets = rankSnippets(snippets, windowAroundCursor).filter(
// Filter out snippets that are already in prefix
(snippet) => snippet.score < 0.98
);
// How to add snippets to the prefix? Count separately? Always keep some of the prefix??

View file

@ -1,4 +1,8 @@
import { FileWithContents } from "..";
import { RangeInFileWithContents } from "../commands/util";
export type AutocompleteSnippet = RangeInFileWithContents & {
score: number;
};
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
function getSymbolsForSnippet(snippet: string): Set<string> {
@ -36,12 +40,73 @@ 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 rankSnippets(
snippets: FileWithContents[],
ranges: RangeInFileWithContents[],
windowAroundCursor: string
): FileWithContents[] {
const scores = snippets.map((snippet) => ({
): AutocompleteSnippet[] {
const snippets = ranges.map((snippet) => ({
score: jaccardSimilarity(snippet.contents, windowAroundCursor),
snippet,
...snippet,
}));
return scores.sort((a, b) => a.score - b.score).map((s) => s.snippet);
const uniqueSnippets = deduplicateSnippets(snippets);
return uniqueSnippets.sort((a, b) => a.score - b.score);
}
/**
* Deduplicate code snippets by merging overlapping ranges into a single range.
*/
export function deduplicateSnippets(
snippets: AutocompleteSnippet[]
): AutocompleteSnippet[] {
// Group by file
const fileGroups: { [key: string]: AutocompleteSnippet[] } = {};
for (const snippet of snippets) {
if (!fileGroups[snippet.filepath]) {
fileGroups[snippet.filepath] = [];
}
fileGroups[snippet.filepath].push(snippet);
}
// Merge overlapping ranges
const allRanges = [];
for (const file of Object.keys(fileGroups)) {
allRanges.push(...mergeSnippetsByRange(fileGroups[file]));
}
return allRanges;
}
function mergeSnippetsByRange(
snippets: AutocompleteSnippet[]
): AutocompleteSnippet[] {
if (snippets.length === 0) {
return snippets;
}
const sorted = snippets.sort(
(a, b) => a.range.start.line - b.range.start.line
);
const merged: AutocompleteSnippet[] = [];
while (sorted.length > 0) {
const next = sorted.shift()!;
const last = merged[merged.length - 1];
if (merged.length > 0 && last.range.end.line >= next.range.start.line) {
// Merge with previous snippet
last.score = Math.max(last.score, next.score);
last.range.end = next.range.end;
last.contents = mergeOverlappingRangeContents(last, next);
} else {
merged.push(next);
}
}
return merged;
}
function mergeOverlappingRangeContents(
first: RangeInFileWithContents,
second: RangeInFileWithContents
): string {
const firstLines = first.contents.split("\n");
const numOverlapping = first.range.end.line - second.range.start.line;
return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents;
}

View file

@ -1,5 +1,5 @@
import { FileWithContents } from "..";
import { jaccardSimilarity } from "./ranking";
import { RangeInFileWithContents } from "../commands/util";
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking";
function* slidingWindow(
content: string,
@ -32,25 +32,22 @@ function* slidingWindow(
* @param suffix
*/
export async function slidingWindowMatcher(
recentDocuments: FileWithContents[],
recentDocuments: RangeInFileWithContents[],
windowAroundCursor: string,
topN: number,
windowSize: number
): Promise<FileWithContents[]> {
): Promise<AutocompleteSnippet[]> {
// Sorted lowest similarity to highest
const topMatches: (FileWithContents & { similarity: number })[] = [];
const topMatches: AutocompleteSnippet[] = [];
for (const { filepath, contents } of recentDocuments) {
for (const { filepath, contents, range } of recentDocuments) {
for (const window of slidingWindow(contents, windowSize)) {
const similarity = jaccardSimilarity(window, windowAroundCursor);
const score = jaccardSimilarity(window, windowAroundCursor);
// Insertion sort
let i = -1;
while (
++i < topMatches.length &&
similarity > topMatches[i].similarity
) {}
topMatches.splice(i + 1, 0, { filepath, contents, similarity });
while (++i < topMatches.length && score > topMatches[i].score) {}
topMatches.splice(i + 1, 0, { filepath, contents, score, range });
if (topMatches.length > topN) {
topMatches.shift();
}

View file

@ -1,4 +1,4 @@
import { FileWithContents, TabAutocompleteOptions } from "core";
import { TabAutocompleteOptions } from "core";
import { AutocompleteLruCache } from "core/autocomplete/cache";
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
import {
@ -11,6 +11,7 @@ import {
} from "core/autocomplete/lineStream";
import { getTemplateForModel } from "core/autocomplete/templates";
import { GeneratorReuseManager } from "core/autocomplete/util";
import { RangeInFileWithContents } from "core/commands/util";
import { streamLines } from "core/diff/util";
import OpenAI from "core/llm/llms/OpenAI";
import Handlebars from "handlebars";
@ -25,7 +26,7 @@ async function getDefinition(
uri: string,
line: number,
character: number
): Promise<FileWithContents | undefined> {
): Promise<RangeInFileWithContents | undefined> {
const definitions = (await vscode.commands.executeCommand(
"vscode.executeDefinitionProvider",
vscode.Uri.parse(uri),
@ -39,6 +40,7 @@ async function getDefinition(
definitions[0].targetUri.fsPath,
definitions[0].targetRange
),
range: definitions[0].targetRange,
};
}

View file

@ -1,5 +1,5 @@
import { FileWithContents } from "core";
import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited";
import { RangeInFileWithContents } from "core/commands/util";
import * as vscode from "vscode";
interface VsCodeRecentlyEditedRange {
@ -112,14 +112,28 @@ export class RecentlyEditedTracker {
);
}
public async getRecentlyEditedDocuments(): Promise<FileWithContents[]> {
public async getRecentlyEditedDocuments(): Promise<
RangeInFileWithContents[]
> {
return Promise.all(
this.recentlyEditedDocuments.map(async (entry) => ({
filepath: entry.uri.fsPath,
contents: await vscode.workspace.fs
this.recentlyEditedDocuments.map(async (entry) => {
const contents = await vscode.workspace.fs
.readFile(entry.uri)
.then((content) => content.toString()),
}))
.then((content) => content.toString());
const lines = contents.split("\n");
return {
filepath: entry.uri.fsPath,
contents,
range: {
start: { line: 0, character: 0 },
end: {
line: lines.length - 1,
character: lines[lines.length - 1].length,
},
},
};
})
);
}
}