diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/brackets.ts new file mode 100644 index 000000000..883863090 --- /dev/null +++ b/core/autocomplete/brackets.ts @@ -0,0 +1,105 @@ +/** + * 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, + suffix: string, + filepath: string, + ): AsyncGenerator { + // Add opening brackets from the previous response + let stack: string[] = []; + if (this.lastCompletionFile === filepath) { + stack = [...this.openingBracketsFromLastCompletion]; + } else { + this.lastCompletionFile = undefined; + } + + // Add corresponding open brackets from suffix to stack + 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 index 6cf03cbe6..30a44084e 100644 --- a/core/autocomplete/charStream.ts +++ b/core/autocomplete/charStream.ts @@ -37,58 +37,3 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { yield char; } } - -const BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" }; -const BRACKETS_REVERSE: { [key: string]: string } = { - ")": "(", - "}": "{", - "]": "[", -}; -export async function* stopOnUnmatchedClosingBracket( - stream: AsyncGenerator, - suffix: string, -): AsyncGenerator { - // Add corresponding open brackets from suffix to stack - const stack: string[] = []; - for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") continue; - const openBracket = 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; - for (let i = 0; i < chunk.length; i++) { - const char = chunk[i]; - if (Object.values(BRACKETS).includes(char)) { - // It's a closing bracket - if (stack.length === 0 || 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(BRACKETS).includes(char)) { - // It's an opening bracket - stack.push(char); - } - } - yield chunk; - } -} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 234715038..66ebf9cee 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -23,11 +23,11 @@ import { } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; +import { BracketMatchingService } from "./brackets.js"; import AutocompleteLruCache from "./cache.js"; import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine, - stopOnUnmatchedClosingBracket, } from "./charStream.js"; import { constructAutocompletePrompt, @@ -139,6 +139,7 @@ export async function getTabCompletion( generatorReuseManager: GeneratorReuseManager, input: AutocompleteInput, getDefinitionsFromLsp: GetLspDefinitionsFunction, + bracketMatchingService: BracketMatchingService, ): Promise { const startTime = Date.now(); @@ -354,7 +355,11 @@ export async function getTabCompletion( let charGenerator = generatorWithCancellation(); charGenerator = noFirstCharNewline(charGenerator); charGenerator = onlyWhitespaceAfterEndOfLine(charGenerator, lang.endOfLine); - charGenerator = stopOnUnmatchedClosingBracket(charGenerator, suffix); + charGenerator = bracketMatchingService.stopOnUnmatchedClosingBracket( + charGenerator, + suffix, + filepath, + ); let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator); @@ -387,6 +392,14 @@ export async function getTabCompletion( // Post-processing completion = completion.trimEnd(); + if (llm.model.includes("codestral")) { + // Codestral sometimes starts with an extra space + if (completion[0] === " " && completion[1] !== " ") { + if (suffix.startsWith("\n")) { + completion = completion.slice(1); + } + } + } } const time = Date.now() - startTime; @@ -423,6 +436,7 @@ export class CompletionProvider { private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); + private bracketMatchingService = new BracketMatchingService(); private onError(e: any) { console.warn("Error generating autocompletion: ", e); @@ -469,6 +483,11 @@ export class CompletionProvider { cacheHit: outcome.cacheHit, }); this._outcomes.delete(completionId); + + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, + ); } } @@ -582,6 +601,7 @@ export class CompletionProvider { this.generatorReuseManager, input, this.getDefinitionsFromLsp, + this.bracketMatchingService, ); if (!outcome?.completion) {