From e147b5abfec0eb2fdcca8332091eb944e2a1ee56 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 24 Feb 2024 23:35:34 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20deduplicate=20autocomplete?= =?UTF-8?q?=20snippets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 18 ++--- core/autocomplete/ranking.ts | 77 +++++++++++++++++-- core/autocomplete/slidingWindow.ts | 21 +++-- .../src/autocomplete/getTabCompletion.ts | 6 +- .../vscode/src/autocomplete/recentlyEdited.ts | 28 +++++-- 5 files changed, 114 insertions(+), 36 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7b731c509..c25228d97 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -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, + ) => Promise, 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?? diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index a5d9abbe0..81da512eb 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -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 { @@ -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; } diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts index 1a1e1935a..cfcdbb340 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/slidingWindow.ts @@ -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 { +): Promise { // 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(); } diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index 14c0242b0..b277cc611 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -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 { +): Promise { 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, }; } diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 4e942cb9f..3e5847efc 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -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 { + 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, + }, + }, + }; + }) ); } }