From bc7e7d591d8ed6a71053832d4cfdf281daf3618d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 29 Feb 2024 11:27:37 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20handful=20of=20autocomplete=20edges?= =?UTF-8?q?=20cases=20fixed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/charStream.ts | 2 +- core/autocomplete/constructPrompt.ts | 60 +++++++++------ core/autocomplete/ranking.ts | 75 ++++++++++++++++++- core/util/treeSitter.ts | 45 ++++++----- .../src/autocomplete/getTabCompletion.ts | 3 +- .../vscode/src/autocomplete/recentlyEdited.ts | 5 +- 6 files changed, 144 insertions(+), 46 deletions(-) diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/charStream.ts index add4cecb8..5994c7759 100644 --- a/core/autocomplete/charStream.ts +++ b/core/autocomplete/charStream.ts @@ -7,7 +7,7 @@ export async function* onlyWhitespaceAfterEndOfLine( chunk = pending + chunk; pending = ""; for (let i = 0; i < chunk.length - 1; i++) { - if (endOfLine.includes(chunk[i]) && chunk[i + 1] === " ") { + if (endOfLine.includes(chunk[i]) && chunk[i + 1] !== " ") { yield chunk.slice(0, i + 1); return; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 1b5dab648..787d4457a 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -10,7 +10,7 @@ import { getBasename } from "../util"; import { getAst, getScopeAroundRange, getTreePathAtCursor } from "./ast"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages"; -import { AutocompleteSnippet, fillPromptWithSnippets, rankSnippets } from "./ranking"; +import { AutocompleteSnippet, fillPromptWithSnippets, rankSnippets, removeRangeFromSnippets } from "./ranking"; import { slidingWindowMatcher } from "./slidingWindow"; export function languageForFilepath( @@ -90,6 +90,7 @@ async function shouldCompleteMultiline( export async function constructAutocompletePrompt( filepath: string, + cursorLine: number, fullPrefix: string, fullSuffix: string, clipboardText: string, @@ -124,7 +125,7 @@ export async function constructAutocompletePrompt( ); snippets.push(...slidingWindowMatches); - const recentlyEdited = await Promise.all( + const recentlyEdited = (await Promise.all( recentlyEditedRanges .map(async (r) => { const scope = await getScopeAroundRange(r); @@ -132,39 +133,54 @@ export async function constructAutocompletePrompt( return r; }) - .filter((s) => !!s) - ); + )).filter((s) => !!s); snippets.push(...(recentlyEdited as any)); // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, windowAroundCursor).filter( - // Filter out snippets that are already in prefix - (snippet) => snippet.score < 0.98 - ); + const scoredSnippets = rankSnippets(snippets, windowAroundCursor) // Fill maxSnippetTokens with snippets const maxSnippetTokens = options.maxPromptTokens * options.maxSnippetPercentage; - const finalSnippets = fillPromptWithSnippets(scoredSnippets, maxSnippetTokens, modelName); - - // Construct basic prefix / suffix - const formattedSnippets = finalSnippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, language) - ) - .join("\n"); + + // Construct basic prefix const maxPrefixTokens = - options.maxPromptTokens * options.prefixPercentage - - countTokens(formattedSnippets, modelName); + options.maxPromptTokens * options.prefixPercentage let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); - if (formattedSnippets.length > 0) { - prefix = formattedSnippets + "\n" + prefix; - } - + + // Construct suffix const maxSuffixTokens = Math.min( options.maxPromptTokens - countTokens(prefix, modelName), options.maxSuffixPercentage * options.maxPromptTokens ); let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); + + // Remove prefix range from snippets + let finalSnippets = fillPromptWithSnippets(scoredSnippets, maxSnippetTokens, modelName); + const prefixLines = prefix.split('\n').length; + const suffixLines = suffix.split('\n').length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: cursorLine - prefixLines - buffer, + character: 0 + }, + end: { + line: cursorLine + suffixLines+ buffer, + character: 0 + } + } + finalSnippets = removeRangeFromSnippets(finalSnippets, filepath.split("://").slice(-1)[0], prefixSuffixRangeWithBuffer); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = finalSnippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, language) + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = formattedSnippets + "\n\n" + prefix; + } + return { prefix, diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index cb87f2e34..0c0970f7b 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -1,3 +1,4 @@ +import { Range } from ".."; import { RangeInFileWithContents } from "../commands/util"; import { countTokens } from "../llm/countTokens"; @@ -131,4 +132,76 @@ export function fillPromptWithSnippets(snippets: AutocompleteSnippet[], maxSnipp } return keptSnippets; -}; \ No newline at end of file +}; + +function rangeIntersectionByLines(a: Range, b: Range): Range | null { + const startLine = Math.max(a.start.line, b.start.line); + const endLine = Math.min(a.end.line, b.end.line); + if (startLine >= endLine) { + return null; + } else { + return { + start: { + line: startLine, + character: 0 + }, + end: { + line: endLine, + character: 0 + } + } + } +} + +/** + * Remove one range from another range, which may lead to returning two disjoint ranges + */ +function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { + if (orig.start.line >= remove.start.line && orig.end.line <= remove.end.line) { + // / | | / + return []; + } else if (orig.start.line <= remove.start.line && orig.end.line >= remove.end.line) { + // | / / | + // Splits the range + return [{ + start: orig.start, + end: remove.start + }, { + start: remove.end, + end: orig.end + }] + } else if (orig.start.line >= remove.start.line && orig.end.line >= remove.end.line) { + // \ | / | + return [{ + start: remove.end, + end: orig.end + }] + } else if (orig.start.line <= remove.start.line && orig.end.line <= remove.end.line) { + // | / | / + return [{ + start: orig.start, + end: remove.start + }] + } else { + return [orig] + } +} + +export function removeRangeFromSnippets(snippets: AutocompleteSnippet[], filepath: string, range: Range): AutocompleteSnippet[] { + const finalSnippets: AutocompleteSnippet[] = []; + for (let snippet of snippets) { + if (snippet.filepath !== filepath) { + finalSnippets.push(snippet); + continue; + } + + const intersection = rangeIntersectionByLines(range, snippet.range); + if (!intersection) { + finalSnippets.push(snippet); + } else { + finalSnippets.push(...rangeDifferenceByLines(snippet.range, intersection).map(range => ({...snippet, range}))); + } + } + + return finalSnippets; +} \ No newline at end of file diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index e0abfd457..8411eb715 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -68,26 +68,31 @@ export const supportedLanguages: { [key: string]: string } = { }; export async function getParserForFile(filepath: string) { - await Parser.init(); - const parser = new Parser(); - const extension = path.extname(filepath).slice(1); - - if (!supportedLanguages[extension]) { - console.warn( - "Unable to load language for file", - extension, - "from path: ", - filepath + try { + await Parser.init(); + const parser = new Parser(); + const extension = path.extname(filepath).slice(1); + + if (!supportedLanguages[extension]) { + console.warn( + "Unable to load language for file", + extension, + "from path: ", + filepath + ); + return undefined; + } + + const wasmPath = path.join( + __dirname, + "tree-sitter-wasms", + `tree-sitter-${supportedLanguages[extension]}.wasm` ); + const language = await Parser.Language.load(wasmPath); + parser.setLanguage(language); + return parser; + } catch (e) { + console.error("Unable to load language for file", filepath, e); return undefined; } - - const wasmPath = path.join( - __dirname, - "tree-sitter-wasms", - `tree-sitter-${supportedLanguages[extension]}.wasm` - ); - const language = await Parser.Language.load(wasmPath); - parser.setLanguage(language); - return parser; -} +} \ No newline at end of file diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index a7ec82a0e..a297819e3 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -50,7 +50,7 @@ export async function getTabCompletion( const lang = languageForFilepath(document.fileName); const line = document.lineAt(pos).text; for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { return undefined; } } @@ -88,6 +88,7 @@ export async function getTabCompletion( const { prefix, suffix, completeMultiline } = await constructAutocompletePrompt( document.uri.toString(), + pos.line, fullPrefix, fullSuffix, clipboardText, diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 3e5847efc..66e0de780 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -23,6 +23,9 @@ export class RecentlyEditedTracker { constructor() { vscode.workspace.onDidChangeTextDocument((event) => { + if (event.document.uri.scheme !== "file") { + return; + } event.contentChanges.forEach((change) => { const editedRange = { uri: event.document.uri, @@ -97,7 +100,7 @@ export class RecentlyEditedTracker { filepath: entry.uri.fsPath, contents: await vscode.workspace.fs .readFile(entry.uri) - .then((content) => content.toString()), + .then((content) => content.toString().split("\n").slice(entry.range.start.line, entry.range.end.line + 1).join("\n")), range: { start: { line: entry.range.start.line,