diff --git a/core/autocomplete/ImportDefinitionsService.ts b/core/autocomplete/ImportDefinitionsService.ts deleted file mode 100644 index 19287bf81..000000000 --- a/core/autocomplete/ImportDefinitionsService.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { IDE } from ".."; -import { RangeInFileWithContents } from "../commands/util"; -import { PrecalculatedLruCache } from "../util/LruCache"; -import { - TSQueryType, - getParserForFile, - getQueryForFile, -} from "../util/treeSitter"; - -interface FileInfo { - imports: { [key: string]: RangeInFileWithContents[] }; -} - -export class ImportDefinitionsService { - static N = 10; - - private cache: PrecalculatedLruCache = - new PrecalculatedLruCache( - this._getFileInfo.bind(this), - ImportDefinitionsService.N, - ); - - constructor(private readonly ide: IDE) { - ide.onDidChangeActiveTextEditor((filepath) => { - this.cache.initKey(filepath); - }); - } - - get(filepath: string): FileInfo | undefined { - return this.cache.get(filepath); - } - - private async _getFileInfo(filepath: string): Promise { - const parser = await getParserForFile(filepath); - if (!parser) { - return { - imports: {}, - }; - } - const ast = parser.parse(await this.ide.readFile(filepath), undefined, { - includedRanges: [ - { - startIndex: 0, - endIndex: 10_000, - startPosition: { row: 0, column: 0 }, - endPosition: { row: 100, column: 0 }, - }, - ], - }); - const query = await getQueryForFile(filepath, TSQueryType.Imports); - if (!query) { - return { - imports: {}, - }; - } - - const matches = query?.matches(ast.rootNode); - - const fileInfo: FileInfo = { - imports: {}, - }; - for (const match of matches) { - const startPosition = match.captures[0].node.startPosition; - const defs = await this.ide.gotoDefinition({ - filepath, - position: { - line: startPosition.row, - character: startPosition.column, - }, - }); - fileInfo.imports[match.captures[0].node.text] = await Promise.all( - defs.map(async (def) => ({ - ...def, - contents: await this.ide.readRangeInFile(def.filepath, def.range), - })), - ); - } - - return fileInfo; - } -} diff --git a/core/autocomplete/NearbyDefinitionsService.ts b/core/autocomplete/NearbyDefinitionsService.ts deleted file mode 100644 index 79cd0af0a..000000000 --- a/core/autocomplete/NearbyDefinitionsService.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { IDE, Location } from ".."; -import { LANGUAGES } from "./languages"; -import { getSymbolsForSnippet } from "./ranking"; - -interface FileInfo { - filepath: string; -} - -export class NearbyDefinitionsService { - static N = 10; - - constructor(private readonly ide: IDE) {} - - async getDefinitionsForLine(filepath: string, line: number) { - const lineContent = await this.ide.readRangeInFile(filepath, { - start: { - line, - character: 0, - }, - end: { - line: line + 1, - character: 0, - }, - }); - - // Remove keywords - const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; - const symbols = Array.from(getSymbolsForSnippet(lineContent)) - .filter((s) => s.length > 0) - .filter((s) => !(lang && lang?.stopWords?.includes(s))); - - return Promise.all( - symbols.map((s) => { - const character = lineContent.indexOf(s); - const pos: Location = { - filepath, - position: { - line, - character, - }, - }; - }), - ); - } -} diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/brackets.ts deleted file mode 100644 index 63afdfd10..000000000 --- a/core/autocomplete/brackets.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * We follow the policy of only completing bracket pairs that we started - * But sometimes we started the pair in a previous autocomplete suggestion - */ -export class BracketMatchingService { - private openingBracketsFromLastCompletion: string[] = []; - private lastCompletionFile: string | undefined = undefined; - - static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" }; - static BRACKETS_REVERSE: { [key: string]: string } = { - ")": "(", - "}": "{", - "]": "[", - }; - - handleAcceptedCompletion(completion: string, filepath: string) { - this.openingBracketsFromLastCompletion = []; - const stack: string[] = []; - - for (let i = 0; i < completion.length; i++) { - const char = completion[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { - // It's an opening bracket - stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { - // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { - break; - } - } - } - - // Any remaining opening brackets in the stack are uncompleted - this.openingBracketsFromLastCompletion = stack; - this.lastCompletionFile = filepath; - } - - async *stopOnUnmatchedClosingBracket( - stream: AsyncGenerator, - prefix: string, - suffix: string, - filepath: string, - multiline: boolean, // Whether this is a multiline completion or not - ): AsyncGenerator { - let stack: string[] = []; - if (multiline) { - // Add opening brackets from the previous response - if (this.lastCompletionFile === filepath) { - stack = [...this.openingBracketsFromLastCompletion]; - } else { - this.lastCompletionFile = undefined; - } - } else { - // If single line completion, then allow completing bracket pairs that are - // started on the current line but not finished on the current line - if (!multiline) { - const currentLine = - (prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? ""); - for (let i = 0; i < currentLine.length; i++) { - const char = currentLine[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { - // It's an opening bracket - stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { - // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { - break; - } - } - } - } - } - - // Add corresponding open brackets from suffix to stack - // because we overwrite them and the diff is displayed, and this allows something to be edited after that - for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") continue; - const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) break; - stack.unshift(openBracket); - } - - let all = ""; - let seenNonWhitespaceOrClosingBracket = false; - for await (let chunk of stream) { - // Allow closing brackets before any non-whitespace characters - if (!seenNonWhitespaceOrClosingBracket) { - const firstNonWhitespaceOrClosingBracketIndex = - chunk.search(/[^\s\)\}\]]/); - if (firstNonWhitespaceOrClosingBracketIndex !== -1) { - yield chunk.slice(0, firstNonWhitespaceOrClosingBracketIndex); - chunk = chunk.slice(firstNonWhitespaceOrClosingBracketIndex); - seenNonWhitespaceOrClosingBracket = true; - } else { - yield chunk; - continue; - } - } - - all += chunk; - const allLines = all.split("\n"); - for (let i = 0; i < chunk.length; i++) { - const char = chunk[i]; - if (Object.values(BracketMatchingService.BRACKETS).includes(char)) { - // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { - // If the stack is empty or the top of the stack doesn't match the current closing bracket - yield chunk.slice(0, i); - return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream - } - } else if ( - Object.keys(BracketMatchingService.BRACKETS).includes(char) - ) { - // It's an opening bracket - stack.push(char); - } - } - yield chunk; - } - } -} diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/charStream.ts deleted file mode 100644 index 39a1c6729..000000000 --- a/core/autocomplete/charStream.ts +++ /dev/null @@ -1,41 +0,0 @@ -export async function* onlyWhitespaceAfterEndOfLine( - stream: AsyncGenerator, - endOfLine: string[], - fullStop: () => void, -): AsyncGenerator { - let pending = ""; - for await (let chunk of stream) { - chunk = pending + chunk; - pending = ""; - for (let i = 0; i < chunk.length - 1; i++) { - if ( - endOfLine.includes(chunk[i]) && - chunk[i + 1].trim() === chunk[i + 1] - ) { - yield chunk.slice(0, i + 1); - fullStop(); - return; - } - } - if (endOfLine.includes(chunk[chunk.length - 1])) { - pending = chunk[chunk.length - 1]; - yield chunk.slice(0, chunk.length - 1); - } else { - yield chunk; - } - } - yield pending; -} - -export async function* noFirstCharNewline(stream: AsyncGenerator) { - let first = true; - for await (const char of stream) { - if (first) { - first = false; - if (char.startsWith("\n") || char.startsWith("\r")) { - return; - } - } - yield char; - } -} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index f1cdfb165..260535d4b 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -22,19 +22,22 @@ import { } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; -import { BracketMatchingService } from "./brackets.js"; import AutocompleteLruCache from "./cache.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, -} from "./charStream.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; +import { postprocessCompletion } from "./postprocessing.js"; +import { AutocompleteSnippet } from "./ranking.js"; +import { RecentlyEditedRange } from "./recentlyEdited.js"; +import { BracketMatchingService } from "./services/BracketMatchingService.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; +import { + noFirstCharNewline, + onlyWhitespaceAfterEndOfLine, +} from "./streamTransforms/charStream.js"; import { avoidPathLine, noTopLevelKeywordsMidline, @@ -43,10 +46,7 @@ import { stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, -} from "./lineStream.js"; -import { postprocessCompletion } from "./postprocessing.js"; -import { AutocompleteSnippet } from "./ranking.js"; -import { RecentlyEditedRange } from "./recentlyEdited.js"; +} from "./streamTransforms/lineStream.js"; import { getTemplateForModel } from "./templates.js"; import { GeneratorReuseManager } from "./util.js"; diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 78770a0d5..7e63375bb 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -7,7 +7,6 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; import { getAst, getTreePathAtCursor } from "./ast.js"; import { AutocompleteLanguageInfo, @@ -22,6 +21,7 @@ import { type AutocompleteSnippet, } from "./ranking.js"; import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; export function languageForFilepath( filepath: string, diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 3360c3a9b..0ab63e716 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -1,4 +1,4 @@ -import type { LineFilter } from "./lineStream"; +import type { LineFilter } from "./streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { topLevelKeywords: string[]; diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts deleted file mode 100644 index 674f0d46e..000000000 --- a/core/autocomplete/lineStream.ts +++ /dev/null @@ -1,349 +0,0 @@ -import { distance } from "fastest-levenshtein"; -import { LineStream } from "../diff/util.js"; -import { DiffLine } from "../index.js"; - -export type LineFilter = (args: { - lines: LineStream; - fullStop: () => void; -}) => LineStream; - -export async function* noTopLevelKeywordsMidline( - lines: LineStream, - topLevelKeywords: string[], - fullStop: () => void, -): LineStream { - for await (const line of lines) { - for (const keyword of topLevelKeywords) { - const indexOf = line.indexOf(`${keyword} `); - if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") { - yield line.slice(0, indexOf); - fullStop(); - break; - } - } - yield line; - } -} - -export async function* avoidPathLine( - stream: LineStream, - comment: string, -): LineStream { - // Snippets are inserted as comments with a line at the start '// Path: '. - // Sometimes the model with copy this pattern, which is unwanted - for await (const line of stream) { - // Also filter lines that are empty comments - if (line.startsWith(`${comment} Path: `) || line.trim() === comment) { - continue; - } - yield line; - } -} - -export async function* streamWithNewLines(stream: LineStream): LineStream { - let firstLine = true; - for await (const nextLine of stream) { - if (!firstLine) { - yield "\n"; - } - firstLine = false; - yield nextLine; - } -} - -const bracketEnding = [")", "]", "}", ";"]; -function isBracketEnding(line: string): boolean { - return line - .trim() - .split("") - .some((char) => bracketEnding.includes(char)); -} - -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - -export function lineIsRepeated(a: string, b: string): boolean { - if (a.length <= 4 || b.length <= 4) { - return false; - } - - const aTrim = a.trim(); - const bTrim = b.trim(); - return ( - commonPrefixLength(aTrim, bTrim) > 12 || - distance(aTrim, bTrim) / bTrim.length < 0.1 - ); -} - -export async function* stopAtSimilarLine( - stream: LineStream, - line: string, - fullStop: () => void, -): AsyncGenerator { - const trimmedLine = line.trim(); - const lineIsBracketEnding = isBracketEnding(trimmedLine); - for await (const nextLine of stream) { - if (nextLine === line) { - fullStop(); - break; - } - - if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) { - yield nextLine; - continue; - } - - if (lineIsRepeated(nextLine, trimmedLine)) { - fullStop(); - break; - } - yield nextLine; - } -} - -const LINES_TO_STOP_AT = ["# End of file.", " void, -): LineStream { - for await (const line of stream) { - if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) { - fullStop(); - break; - } - yield line; - } -} - -const PREFIXES_TO_SKIP = [""]; -export async function* skipPrefixes(lines: LineStream): LineStream { - let isFirstLine = true; - for await (const line of lines) { - if (isFirstLine) { - const match = PREFIXES_TO_SKIP.find((prefix) => line.startsWith(prefix)); - if (match) { - yield line.slice(match.length); - continue; - } - isFirstLine = false; - } - yield line; - } -} - -const LINES_TO_SKIP = [""]; - -export async function* skipLines(stream: LineStream): LineStream { - for await (const line of stream) { - if (!LINES_TO_SKIP.some((skipAt) => line.startsWith(skipAt))) { - yield line; - } - } -} - -const LINES_TO_REMOVE_BEFORE_START = [ - "", - "[CODE]", - "", -]; - -function shouldRemoveLineBeforeStart(line: string): boolean { - return ( - line.trimStart().startsWith("```") || - LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l) - ); -} - -function shouldChangeLineAndStop(line: string): string | undefined { - if (line.trimStart() === "```") { - return line; - } - - if (line.includes("[/CODE]")) { - return line.split("[/CODE]")[0].trimEnd(); - } - - return undefined; -} - -export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { - let seenValidLine = false; - - let waitingToSeeIfLineIsLast = undefined; - - for await (const line of rawLines) { - // Filter out starting ``` - if (!seenValidLine) { - if (shouldRemoveLineBeforeStart(line)) { - continue; - } - seenValidLine = true; - } - - // Filter out ending ``` - if (typeof waitingToSeeIfLineIsLast !== "undefined") { - yield waitingToSeeIfLineIsLast; - waitingToSeeIfLineIsLast = undefined; - } - - const changedEndLine = shouldChangeLineAndStop(line); - if (typeof changedEndLine === "string") { - yield changedEndLine; - return; - } - - if (line.startsWith("```")) { - waitingToSeeIfLineIsLast = line; - } else { - yield line; - } - } -} - -function isEnglishFirstLine(line: string) { - line = line.trim().toLowerCase(); - if (line.endsWith(":") && !line.trimStart().startsWith("def")) { - return true; - } - if ( - line.startsWith("here is") || - line.startsWith("here's") || - line.startsWith("sure, here") || - line.startsWith("sure thing") || - line.startsWith("sure!") || - line.startsWith("to fill") || - line.startsWith("certainly") || - line.startsWith("of course") || - line.startsWith("the code should") - ) { - return true; - } - - return false; -} - -export async function* filterEnglishLinesAtStart(lines: LineStream) { - let i = 0; - let wasEnglishFirstLine = false; - for await (const line of lines) { - if (i === 0 && line.trim() === "") { - continue; - } - if (i === 0) { - if (isEnglishFirstLine(line)) { - wasEnglishFirstLine = true; - i++; - continue; - } - } else if (i === 1 && wasEnglishFirstLine && line.trim() === "") { - i++; - continue; - } - i++; - yield line; - } -} - -function isEnglishPostExplanation(line: string): boolean { - const lower = line.toLowerCase(); - return ( - lower.startsWith("explanation:") || - lower.startsWith("here is") || - lower.startsWith("here's how") || - lower.startsWith("the above") - ); -} - -export async function* filterEnglishLinesAtEnd(lines: LineStream) { - let finishedCodeBlock = false; - for await (const line of lines) { - if (line.trim() === "```") { - finishedCodeBlock = true; - } - if (finishedCodeBlock && isEnglishPostExplanation(line)) { - break; - } - yield line; - } -} - -export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) { - let isFirstLine = true; - for await (const line of lines) { - if (isFirstLine && line.startsWith(" ")) { - yield line.slice(2); - isFirstLine = false; - } else { - yield line; - } - } -} - -function isUselessLine(line: string): boolean { - const trimmed = line.trim().toLowerCase(); - return trimmed === "" || trimmed === "```" || trimmed.startsWith("// end"); -} - -export async function* filterLeadingAndTrailingNewLineInsertion( - diffLines: AsyncGenerator, -): AsyncGenerator { - let isFirst = true; - let buffer: DiffLine[] = []; - for await (const diffLine of diffLines) { - const isBlankLineInsertion = - diffLine.type === "new" && isUselessLine(diffLine.line); - if (isFirst && isBlankLineInsertion) { - isFirst = false; - continue; - } - isFirst = false; - - if (isBlankLineInsertion) { - buffer.push(diffLine); - } else { - if (diffLine.type === "old") { - buffer = []; - } else { - while (buffer.length > 0) { - yield buffer.shift()!; - } - } - yield diffLine; - } - } -} - -export async function* stopAtRepeatingLines( - lines: LineStream, - fullStop: () => void, -): LineStream { - const repeatedLines: string[] = []; - for await (const line of lines) { - if (repeatedLines.length === 0) { - repeatedLines.push(line); - } else if (repeatedLines.length < 3) { - if (repeatedLines[repeatedLines.length - 1] === line) { - repeatedLines.push(line); - } else { - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; - } - yield line; - } - } else { - yield repeatedLines[0]; - fullStop(); - return; - } - } - - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; - } -} diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing.ts index 724c826f2..b6841aebc 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing.ts @@ -1,6 +1,6 @@ import type { ILLM } from ".."; import { longestCommonSubsequence } from "../util/lcs"; -import { lineIsRepeated } from "./lineStream"; +import { lineIsRepeated } from "./streamTransforms/lineStream"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index af64b0933..a87ebea6e 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -5,7 +5,7 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/lineStream.js"; +} from "../../autocomplete/streamTransforms/lineStream.js"; import { streamLines } from "../../diff/util.js"; import { ContextItemWithId, ILLM, SlashCommand } from "../../index.js"; import { stripImages } from "../../llm/countTokens.js"; @@ -252,7 +252,7 @@ const EditSlashCommand: SlashCommand = { ); // if the above replace fails to find a match, the code will still be present // in the userInput. Replace it with input if available. - if (userInput.includes("\`\`\`") && (input !== "" || !input)) { + if (userInput.includes("```") && (input !== "" || !input)) { userInput = input; } diff --git a/core/util/verticalEdit.ts b/core/util/verticalEdit.ts index e018d1be4..913c38ddc 100644 --- a/core/util/verticalEdit.ts +++ b/core/util/verticalEdit.ts @@ -5,7 +5,7 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/lineStream.js"; +} from "../autocomplete/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; import {