⚡️ find recently edited ranges with perfect prefix match

This commit is contained in:
Nate Sesti 2024-05-06 21:18:00 -07:00
parent 52b99dca84
commit 07b3abaa20
8 changed files with 116 additions and 77 deletions

View file

@ -36,6 +36,7 @@ import {
streamWithNewLines,
} from "./lineStream";
import { AutocompleteSnippet } from "./ranking";
import { RecentlyEditedRange } from "./recentlyEdited";
import { getTemplateForModel } from "./templates";
import { GeneratorReuseManager } from "./util";
@ -44,7 +45,7 @@ export interface AutocompleteInput {
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RangeInFileWithContents[];
recentlyEditedRanges: RecentlyEditedRange[];
clipboardText: string;
// Used for notebook files
manuallyPassFileContents?: string;

View file

@ -15,6 +15,7 @@ import {
rankSnippets,
removeRangeFromSnippets,
} from "./ranking";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited";
export function languageForFilepath(
filepath: string,
@ -106,7 +107,7 @@ export async function constructAutocompletePrompt(
clipboardText: string,
language: AutocompleteLanguageInfo,
options: TabAutocompleteOptions,
recentlyEditedRanges: RangeInFileWithContents[],
recentlyEditedRanges: RecentlyEditedRange[],
recentlyEditedFiles: RangeInFileWithContents[],
modelName: string,
extraSnippets: AutocompleteSnippet[],
@ -142,6 +143,7 @@ export async function constructAutocompletePrompt(
options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage),
);
// This was much too slow, and not super useful
// const slidingWindowMatches = await slidingWindowMatcher(
// recentlyEditedFiles,
// windowAroundCursor,
@ -150,22 +152,38 @@ export async function constructAutocompletePrompt(
// );
// snippets.push(...slidingWindowMatches);
const recentlyEdited = (
await Promise.all(
recentlyEditedRanges.map(async (r) => {
return r;
// return await getScopeAroundRange(r);
}),
)
).filter((s) => !!s);
snippets.push(...(recentlyEdited as any));
// snippets.push(
// ...recentlyEditedRanges.map((r) => ({
// ...r,
// contents: r.lines.join("\n"),
// })),
// );
// Filter out empty snippets
snippets = snippets.filter(
(s) =>
s.contents.trim() !== "" &&
!(prefix + suffix).includes(s.contents.trim()),
);
if (options.useRecentlyEdited) {
const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0];
if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) {
const matchingRange = findMatchingRange(
recentlyEditedRanges,
currentLinePrefix,
);
if (matchingRange) {
snippets.push({
...matchingRange,
contents: matchingRange.lines.join("\n"),
score: 0.8,
});
}
}
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))
.filter(
(s) =>
s.contents.trim() !== "" &&
!(prefix + suffix).includes(s.contents.trim()),
);
// Rank / order the snippets
const scoredSnippets = rankSnippets(snippets, windowAroundCursor);

View file

@ -3,11 +3,11 @@ import { RangeInFileWithContents } from "../commands/util";
import { countTokens } from "../llm/countTokens";
export type AutocompleteSnippet = RangeInFileWithContents & {
score: number;
score?: number;
};
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
function getSymbolsForSnippet(snippet: string): Set<string> {
export function getSymbolsForSnippet(snippet: string): Set<string> {
const symbols = snippet
.split(rx)
.map((s) => s.trim())
@ -42,11 +42,12 @@ 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(
ranges: RangeInFileWithContents[],
ranges: AutocompleteSnippet[],
windowAroundCursor: string,
): AutocompleteSnippet[] {
const snippets = ranges.map((snippet) => ({
score: jaccardSimilarity(snippet.contents, windowAroundCursor),
): Required<AutocompleteSnippet>[] {
const snippets: Required<AutocompleteSnippet>[] = ranges.map((snippet) => ({
score:
snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),
...snippet,
}));
const uniqueSnippets = deduplicateSnippets(snippets);
@ -57,10 +58,10 @@ export function rankSnippets(
* Deduplicate code snippets by merging overlapping ranges into a single range.
*/
export function deduplicateSnippets(
snippets: AutocompleteSnippet[],
): AutocompleteSnippet[] {
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
// Group by file
const fileGroups: { [key: string]: AutocompleteSnippet[] } = {};
const fileGroups: { [key: string]: Required<AutocompleteSnippet>[] } = {};
for (const snippet of snippets) {
if (!fileGroups[snippet.filepath]) {
fileGroups[snippet.filepath] = [];
@ -77,8 +78,8 @@ export function deduplicateSnippets(
}
function mergeSnippetsByRange(
snippets: AutocompleteSnippet[],
): AutocompleteSnippet[] {
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
if (snippets.length === 0) {
return snippets;
}
@ -86,7 +87,7 @@ function mergeSnippetsByRange(
const sorted = snippets.sort(
(a, b) => a.range.start.line - b.range.start.line,
);
const merged: AutocompleteSnippet[] = [];
const merged: Required<AutocompleteSnippet>[] = [];
while (sorted.length > 0) {
const next = sorted.shift()!;
@ -121,12 +122,12 @@ function mergeOverlappingRangeContents(
* Fill the allowed space with snippets
*/
export function fillPromptWithSnippets(
snippets: AutocompleteSnippet[],
snippets: Required<AutocompleteSnippet>[],
maxSnippetTokens: number,
modelName: string,
): AutocompleteSnippet[] {
): Required<AutocompleteSnippet>[] {
let tokensRemaining = maxSnippetTokens;
const keptSnippets: AutocompleteSnippet[] = [];
const keptSnippets: Required<AutocompleteSnippet>[] = [];
for (let i = 0; i < snippets.length; i++) {
const snippet = snippets[i];
const tokenCount = countTokens(snippet.contents, modelName);
@ -214,11 +215,11 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
}
export function removeRangeFromSnippets(
snippets: AutocompleteSnippet[],
snippets: Required<AutocompleteSnippet>[],
filepath: string,
range: Range,
): AutocompleteSnippet[] {
const finalSnippets: AutocompleteSnippet[] = [];
): Required<AutocompleteSnippet>[] {
const finalSnippets: Required<AutocompleteSnippet>[] = [];
for (let snippet of snippets) {
if (snippet.filepath !== filepath) {
finalSnippets.push(snippet);

View file

@ -1,5 +1,18 @@
import { RangeInFileWithContents } from "../commands/util";
import { RangeInFile } from "..";
export type RecentlyEditedRange = RangeInFileWithContents & {
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
lines: string[];
symbols: Set<string>;
};
export function findMatchingRange(
recentlyEditedRanges: RecentlyEditedRange[],
linePrefix: string,
): RecentlyEditedRange | undefined {
return recentlyEditedRanges.find((recentlyEditedRange) => {
return recentlyEditedRange.lines.some((line) =>
line.startsWith(linePrefix),
);
});
}

2
core/index.d.ts vendored
View file

@ -693,6 +693,8 @@ export interface TabAutocompleteOptions {
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;
useRecentlyEdited: boolean;
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
}

View file

@ -16,6 +16,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
useCache: true,
onlyMyCode: true,
useOtherFiles: true,
useRecentlyEdited: true,
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
};

View file

@ -9,6 +9,7 @@ import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { getDefinitionsFromLsp } from "./lsp";
import { RecentlyEditedTracker } from "./recentlyEdited";
import { setupStatusBar, stopStatusBarLoading } from "./statusBar";
interface VsCodeCompletionInput {
@ -39,6 +40,7 @@ export class ContinueCompletionProvider
}
private completionProvider: CompletionProvider;
private recentlyEditedTracker = new RecentlyEditedTracker();
constructor(
private readonly configHandler: ConfigHandler,
@ -184,7 +186,8 @@ export class ContinueCompletionProvider
filepath: document.uri.fsPath,
pos,
recentlyEditedFiles: [],
recentlyEditedRanges: [],
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
clipboardText: clipboardText,
manuallyPassFileContents,
manuallyPassPrefix,

View file

@ -1,12 +1,12 @@
import { getSymbolsForSnippet } from "core/autocomplete/ranking";
import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited";
import { RangeInFileWithContents } from "core/commands/util";
import * as vscode from "vscode";
interface VsCodeRecentlyEditedRange {
timestamp: number;
type VsCodeRecentlyEditedRange = {
uri: vscode.Uri;
range: vscode.Range;
}
} & Omit<RecentlyEditedRange, "filepath" | "range">;
interface VsCodeRecentlyEditedDocument {
timestamp: number;
@ -46,21 +46,35 @@ export class RecentlyEditedTracker {
}, 1000 * 15);
}
private insertRange(editedRange: VsCodeRecentlyEditedRange): void {
private async insertRange(
editedRange: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
): Promise<void> {
// Check for overlap with any existing ranges
for (let i = 0; i < this.recentlyEditedRanges.length; i++) {
let range = this.recentlyEditedRanges[i];
if (range.range.intersection(editedRange.range)) {
const union = range.range.union(editedRange.range);
const contents = await this._getContentsForRange({
...range,
range: union,
});
range = {
...range,
range: range.range.union(editedRange.range),
range: union,
lines: contents.split("\n"),
symbols: getSymbolsForSnippet(contents),
};
return;
}
}
// Otherwise, just add the new and maintain max size
const newLength = this.recentlyEditedRanges.unshift(editedRange);
const contents = await this._getContentsForRange(editedRange);
const newLength = this.recentlyEditedRanges.unshift({
...editedRange,
lines: contents.split("\n"),
symbols: getSymbolsForSnippet(contents),
});
if (newLength >= RecentlyEditedTracker.maxRecentlyEditedRanges) {
this.recentlyEditedRanges = this.recentlyEditedRanges.slice(
0,
@ -93,40 +107,25 @@ export class RecentlyEditedTracker {
);
}
public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
const results = await Promise.all(
this.recentlyEditedRanges.map(async (entry) => {
try {
const contents = await vscode.workspace.fs
.readFile(entry.uri)
.then((content) =>
content
.toString()
.split("\n")
.slice(entry.range.start.line, entry.range.end.line + 1)
.join("\n"),
);
return {
timestamp: entry.timestamp,
filepath: entry.uri.fsPath,
contents,
range: {
start: {
line: entry.range.start.line,
character: entry.range.start.character,
},
end: {
line: entry.range.end.line,
character: entry.range.end.character,
},
},
};
} catch (e) {
return null;
}
}),
private async _getContentsForRange(
entry: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
): Promise<string> {
return vscode.workspace.fs.readFile(entry.uri).then((content) =>
content
.toString()
.split("\n")
.slice(entry.range.start.line, entry.range.end.line + 1)
.join("\n"),
);
return results.filter((result) => result !== null) as any;
}
public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
return this.recentlyEditedRanges.map((entry) => {
return {
...entry,
filepath: entry.uri.fsPath,
};
});
}
public async getRecentlyEditedDocuments(): Promise<