From 37355ec1db07e7fca51b65944289f0b91a6ffffd Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 21 Jun 2024 21:59:38 -0700 Subject: [PATCH] organize autocomplete folder --- .../services/BracketMatchingService.ts | 134 +++++++ .../services/ImportDefinitionsService.ts | 81 ++++ .../services/NearbyDefinitionsService.ts | 45 +++ .../streamTransforms/charStream.ts | 41 ++ .../streamTransforms/lineStream.ts | 349 ++++++++++++++++++ 5 files changed, 650 insertions(+) create mode 100644 core/autocomplete/services/BracketMatchingService.ts create mode 100644 core/autocomplete/services/ImportDefinitionsService.ts create mode 100644 core/autocomplete/services/NearbyDefinitionsService.ts create mode 100644 core/autocomplete/streamTransforms/charStream.ts create mode 100644 core/autocomplete/streamTransforms/lineStream.ts diff --git a/core/autocomplete/services/BracketMatchingService.ts b/core/autocomplete/services/BracketMatchingService.ts new file mode 100644 index 000000000..63afdfd10 --- /dev/null +++ b/core/autocomplete/services/BracketMatchingService.ts @@ -0,0 +1,134 @@ +/** + * 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/services/ImportDefinitionsService.ts b/core/autocomplete/services/ImportDefinitionsService.ts new file mode 100644 index 000000000..19287bf81 --- /dev/null +++ b/core/autocomplete/services/ImportDefinitionsService.ts @@ -0,0 +1,81 @@ +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/services/NearbyDefinitionsService.ts b/core/autocomplete/services/NearbyDefinitionsService.ts new file mode 100644 index 000000000..12d6f7947 --- /dev/null +++ b/core/autocomplete/services/NearbyDefinitionsService.ts @@ -0,0 +1,45 @@ +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/streamTransforms/charStream.ts b/core/autocomplete/streamTransforms/charStream.ts new file mode 100644 index 000000000..39a1c6729 --- /dev/null +++ b/core/autocomplete/streamTransforms/charStream.ts @@ -0,0 +1,41 @@ +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/streamTransforms/lineStream.ts b/core/autocomplete/streamTransforms/lineStream.ts new file mode 100644 index 000000000..268801994 --- /dev/null +++ b/core/autocomplete/streamTransforms/lineStream.ts @@ -0,0 +1,349 @@ +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()!; + } +}