This commit is contained in:
Nate Sesti 2024-06-21 15:55:33 -07:00
commit 1ecf593939
36 changed files with 653 additions and 383 deletions

View file

@ -3,6 +3,6 @@ import { MessageIde } from "core/util/messageIde";
export class IpcIde extends MessageIde {
constructor(messenger: TODO) {
super(messenger.request.bind(messenger));
super(messenger.request.bind(messenger), messenger.on.bind(messenger));
}
}

View file

@ -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<FileInfo> =
new PrecalculatedLruCache<FileInfo>(
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<FileInfo> {
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;
}
}

View file

@ -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,
},
};
}),
);
}
}

View file

@ -1,5 +1,5 @@
import Handlebars from "handlebars";
import ignore from "ignore";
import OpenAI from "openai";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { RangeInFileWithContents } from "../commands/util.js";
@ -14,7 +14,6 @@ import {
Range,
TabAutocompleteOptions,
} from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { logDevData } from "../util/devdata.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import {
@ -23,6 +22,7 @@ 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 {
@ -138,342 +138,6 @@ export type GetLspDefinitionsFunction = (
lang: AutocompleteLanguageInfo,
) => Promise<AutocompleteSnippet[]>;
export async function getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
llm: ILLM,
ide: IDE,
generatorReuseManager: GeneratorReuseManager,
input: AutocompleteInput,
getDefinitionsFromLsp: GetLspDefinitionsFunction,
bracketMatchingService: BracketMatchingService,
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
const {
filepath,
pos,
recentlyEditedFiles,
recentlyEditedRanges,
clipboardText,
manuallyPassFileContents,
manuallyPassPrefix,
} = input;
const fileContents =
manuallyPassFileContents ?? (await ide.readFile(filepath));
const fileLines = fileContents.split("\n");
// Filter
const lang = languageForFilepath(filepath);
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
}
}
// Model
if (!llm) {
return;
}
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
} else if (
llm.providerName === "free-trial" &&
llm.model !== TRIAL_FIM_MODEL
) {
llm.model = TRIAL_FIM_MODEL;
}
if (
!shownGptClaudeWarning &&
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
!llm.model.includes("deepseek")
) {
shownGptClaudeWarning = true;
throw new Error(
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
);
}
// Prompt
let fullPrefix =
getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: input.selectedCompletionInfo?.range.start ?? pos,
}) + (input.selectedCompletionInfo?.text ?? "");
if (input.injectDetails) {
const lines = fullPrefix.split("\n");
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${
lang.singleLineComment
} ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${
lines[lines.length - 1]
}`;
}
const fullSuffix = getRangeInString(fileContents, {
start: pos,
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
});
// First non-whitespace line below the cursor
let lineBelowCursor = "";
let i = 1;
while (
lineBelowCursor.trim() === "" &&
pos.line + i <= fileLines.length - 1
) {
lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)];
i++;
}
let extrasSnippets = options.useOtherFiles
? ((await Promise.race([
getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
ide,
lang,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
: [];
const workspaceDirs = await ide.getWorkspaceDirs();
if (options.onlyMyCode) {
extrasSnippets = extrasSnippets.filter((snippet) => {
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
});
}
let { prefix, suffix, completeMultiline, snippets } =
await constructAutocompletePrompt(
filepath,
pos.line,
fullPrefix,
fullSuffix,
clipboardText,
lang,
options,
recentlyEditedRanges,
recentlyEditedFiles,
llm.model,
extrasSnippets,
);
// If prefix is manually passed
if (manuallyPassPrefix) {
prefix = manuallyPassPrefix;
suffix = "";
}
// Template prompt
const {
template,
completionOptions,
compilePrefixSuffix = undefined,
} = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
if (compilePrefixSuffix) {
[prefix, suffix] = compilePrefixSuffix(
prefix,
suffix,
filepath,
reponame,
snippets,
);
}
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = `${formattedSnippets}\n\n${prefix}`;
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
// If it's an empty file, include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`;
}
prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filepath, reponame, snippets);
}
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
const stop = [
...(completionOptions?.stop || []),
...multilineStops,
...commonStops,
...(llm.model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...(lang.stopWords ?? []),
...lang.topLevelKeywords.map((word) => `\n${word}`),
];
let langMultilineDecision = lang.useMultiline?.({ prefix, suffix });
let multiline: boolean = false;
if (langMultilineDecision) {
multiline = langMultilineDecision;
} else {
multiline =
!input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || completeMultiline);
}
// Try to reuse pending requests if what the user typed matches start of completion
const generator = generatorReuseManager.getGenerator(
prefix,
() =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, {
...completionOptions,
stop,
})
: llm.streamComplete(prompt, {
...completionOptions,
raw: true,
stop,
}),
multiline,
);
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () => generatorReuseManager.currentGenerator?.cancel();
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.aborted) {
cancelled = true;
return;
}
yield update;
}
};
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(
charGenerator,
lang.endOfLine,
fullStop,
);
charGenerator = bracketMatchingService.stopOnUnmatchedClosingBracket(
charGenerator,
prefix,
suffix,
filepath,
multiline,
);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,
lang.topLevelKeywords,
fullStop,
);
for (const lineFilter of lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
}
lineGenerator = streamWithNewLines(lineGenerator);
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
try {
for await (const update of finalGenerator) {
completion += update;
}
} catch (e: any) {
if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) {
return undefined;
}
throw e;
}
if (cancelled) {
return undefined;
}
const processedCompletion = postprocessCompletion({
completion,
prefix,
suffix,
llm,
});
if (!processedCompletion) {
return undefined;
}
completion = processedCompletion;
}
const time = Date.now() - startTime;
return {
time,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
filepath: input.filepath,
completionId: input.completionId,
gitRepo: await ide.getRepoName(input.filepath),
uniqueId: await ide.getUniqueId(),
...options,
};
}
export class CompletionProvider {
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
private static debouncing = false;
@ -489,12 +153,15 @@ export class CompletionProvider {
this.generatorReuseManager = new GeneratorReuseManager(
this.onError.bind(this),
);
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
}
private importDefinitionsService: ImportDefinitionsService;
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
private bracketMatchingService = new BracketMatchingService();
// private nearbyDefinitionsService = new NearbyDefinitionsService();
private onError(e: any) {
console.warn("Error generating autocompletion: ", e);
@ -654,16 +321,7 @@ export class CompletionProvider {
options.maxPromptTokens = 500;
}
const outcome = await getTabCompletion(
token,
options,
llm,
this.ide,
this.generatorReuseManager,
input,
this.getDefinitionsFromLsp,
this.bracketMatchingService,
);
const outcome = await this.getTabCompletion(token, options, llm, input);
if (!outcome?.completion) {
return undefined;
@ -735,4 +393,338 @@ export class CompletionProvider {
displayedAt: now,
};
}
async getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
llm: ILLM,
input: AutocompleteInput,
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
const {
filepath,
pos,
recentlyEditedFiles,
recentlyEditedRanges,
clipboardText,
manuallyPassFileContents,
manuallyPassPrefix,
} = input;
const fileContents =
manuallyPassFileContents ?? (await this.ide.readFile(filepath));
const fileLines = fileContents.split("\n");
// Filter
const lang = languageForFilepath(filepath);
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
}
}
// Model
if (!llm) {
return;
}
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
} else if (
llm.providerName === "free-trial" &&
llm.model !== TRIAL_FIM_MODEL
) {
llm.model = TRIAL_FIM_MODEL;
}
if (
!shownGptClaudeWarning &&
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
!llm.model.includes("deepseek")
) {
shownGptClaudeWarning = true;
throw new Error(
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
);
}
// Prompt
let fullPrefix =
getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: input.selectedCompletionInfo?.range.start ?? pos,
}) + (input.selectedCompletionInfo?.text ?? "");
if (input.injectDetails) {
const lines = fullPrefix.split("\n");
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${
lang.singleLineComment
} ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${
lines[lines.length - 1]
}`;
}
const fullSuffix = getRangeInString(fileContents, {
start: pos,
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
});
// First non-whitespace line below the cursor
let lineBelowCursor = "";
let i = 1;
while (
lineBelowCursor.trim() === "" &&
pos.line + i <= fileLines.length - 1
) {
lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)];
i++;
}
let extrasSnippets = options.useOtherFiles
? ((await Promise.race([
this.getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
this.ide,
lang,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
: [];
const workspaceDirs = await this.ide.getWorkspaceDirs();
if (options.onlyMyCode) {
extrasSnippets = extrasSnippets.filter((snippet) => {
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
});
}
let { prefix, suffix, completeMultiline, snippets } =
await constructAutocompletePrompt(
filepath,
pos.line,
fullPrefix,
fullSuffix,
clipboardText,
lang,
options,
recentlyEditedRanges,
recentlyEditedFiles,
llm.model,
extrasSnippets,
this.importDefinitionsService,
);
// If prefix is manually passed
if (manuallyPassPrefix) {
prefix = manuallyPassPrefix;
suffix = "";
}
// Template prompt
const {
template,
completionOptions,
compilePrefixSuffix = undefined,
} = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
if (compilePrefixSuffix) {
[prefix, suffix] = compilePrefixSuffix(
prefix,
suffix,
filepath,
reponame,
snippets,
);
}
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = `${formattedSnippets}\n\n${prefix}`;
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
// If it's an empty file, include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`;
}
prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filepath, reponame, snippets);
}
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
const stop = [
...(completionOptions?.stop || []),
...multilineStops,
...commonStops,
...(llm.model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...(lang.stopWords ?? []),
...lang.topLevelKeywords.map((word) => `\n${word}`),
];
let langMultilineDecision = lang.useMultiline?.({ prefix, suffix });
let multiline: boolean = false;
if (langMultilineDecision) {
multiline = langMultilineDecision;
} else {
multiline =
!input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || completeMultiline);
}
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
() =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, {
...completionOptions,
stop,
})
: llm.streamComplete(prompt, {
...completionOptions,
raw: true,
stop,
}),
multiline,
);
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () =>
this.generatorReuseManager.currentGenerator?.cancel();
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.aborted) {
cancelled = true;
return;
}
yield update;
}
};
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(
charGenerator,
lang.endOfLine,
fullStop,
);
charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket(
charGenerator,
prefix,
suffix,
filepath,
multiline,
);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,
lang.topLevelKeywords,
fullStop,
);
for (const lineFilter of lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
}
lineGenerator = streamWithNewLines(lineGenerator);
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
try {
for await (const update of finalGenerator) {
completion += update;
}
} catch (e: any) {
if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) {
return undefined;
}
throw e;
}
if (cancelled) {
return undefined;
}
const processedCompletion = postprocessCompletion({
completion,
prefix,
suffix,
llm,
});
if (!processedCompletion) {
return undefined;
}
completion = processedCompletion;
}
const time = Date.now() - startTime;
return {
time,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
filepath: input.filepath,
completionId: input.completionId,
gitRepo: await this.ide.getRepoName(input.filepath),
uniqueId: await this.ide.getUniqueId(),
...options,
};
}
}

View file

@ -7,6 +7,7 @@ import {
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
@ -15,6 +16,7 @@ import {
} from "./languages.js";
import {
fillPromptWithSnippets,
getSymbolsForSnippet,
rankSnippets,
removeRangeFromSnippets,
type AutocompleteSnippet,
@ -124,6 +126,7 @@ export async function constructAutocompletePrompt(
recentlyEditedFiles: RangeInFileWithContents[],
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
): Promise<{
prefix: string;
suffix: string;
@ -189,6 +192,29 @@ export async function constructAutocompletePrompt(
}
}
// Use imports
if (options.useImports) {
const importSnippets = [];
const fileInfo = importDefinitionsService.get(filepath);
if (fileInfo) {
const { imports } = fileInfo;
// Look for imports of any symbols around the current range
const textAroundCursor =
fullPrefix.split("\n").slice(-5).join("\n") +
fullSuffix.split("\n").slice(0, 3).join("\n");
const symbols = Array.from(
getSymbolsForSnippet(textAroundCursor),
).filter((symbol) => !language.topLevelKeywords.includes(symbol));
for (const symbol of symbols) {
const rifs = imports[symbol];
if (rifs) {
importSnippets.push(...rifs);
}
}
}
snippets.push(...importSnippets);
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))

12
core/index.d.ts vendored
View file

@ -201,6 +201,11 @@ export interface RangeInFile {
range: Range;
}
export interface Location {
filepath: string;
position: Position;
}
export interface FileWithContents {
filepath: string;
contents: string;
@ -462,6 +467,12 @@ export interface IDE {
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getGitHubAuthToken(): Promise<string | undefined>;
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;
// Callbacks
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
}
// Slash Commands
@ -756,6 +767,7 @@ export interface TabAutocompleteOptions {
useRecentlyEdited: boolean;
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
}
export interface ContinueUIConfig {

View file

@ -1,5 +1,3 @@
import fs from "node:fs";
import path from "node:path";
import type {
ChunkWithoutID,
ContextItem,
@ -10,9 +8,9 @@ import type {
} from "../index.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import {
getLanguageForFile,
TSQueryType,
getParserForFile,
supportedLanguages,
getQueryForFile,
} from "../util/treeSitter.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import {
@ -46,35 +44,16 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
)`);
}
private getQuerySource(filepath: string) {
const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""];
const sourcePath = path.join(
__dirname,
"..",
"tree-sitter",
"code-snippet-queries",
`tree-sitter-${fullLangName}-tags.scm`,
);
if (!fs.existsSync(sourcePath)) {
return "";
}
return fs.readFileSync(sourcePath).toString();
}
async getSnippetsInFile(
filepath: string,
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
const lang = await getLanguageForFile(filepath);
if (!lang) {
return [];
}
const parser = await getParserForFile(filepath);
if (!parser) {
return [];
}
const ast = parser.parse(contents);
const query = lang?.query(this.getQuerySource(filepath));
const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets);
const matches = query?.matches(ast.rootNode);
return (

View file

@ -5,8 +5,10 @@ import type {
IdeInfo,
IdeSettings,
IndexTag,
Location,
Problem,
Range,
RangeInFile,
Thread,
} from "..";
@ -73,5 +75,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
listDir: [{ dir: string }, [string, FileType][]];
getLastModified: [{ files: string[] }, { [path: string]: number }];
gotoDefinition: [{ location: Location }, RangeInFile[]];
getGitHubAuthToken: [undefined, string | undefined];
};

View file

@ -12,7 +12,10 @@ export type IProtocol = Record<string, [any, any]>;
// IDE
export type ToIdeProtocol = ToIdeFromWebviewProtocol & ToIdeFromCoreProtocol;
export type FromIdeProtocol = ToWebviewFromIdeProtocol & ToCoreFromIdeProtocol;
export type FromIdeProtocol = ToWebviewFromIdeProtocol &
ToCoreFromIdeProtocol & {
didChangeActiveTextEditor: [{ filepath: string }, void];
};
// Webview
export type ToWebviewProtocol = ToWebviewFromIdeProtocol &

30
core/util/LruCache.ts Normal file
View file

@ -0,0 +1,30 @@
export class PrecalculatedLruCache<V> {
private items: [string, V][] = [];
constructor(
private readonly calculateValue: (key: string) => Promise<V>,
private readonly N: number,
) {}
async initKey(key: string) {
// Maintain LRU
const index = this.items.findIndex((item) => item[0] === key);
if (index < 0) {
// Calculate info for new file
const value: V = await this.calculateValue(key);
this.items.push([key, value]);
if (this.items.length > this.N) {
this.items.shift();
}
} else {
// Move to end of array, since it was recently used
const [item] = this.items.splice(index, 1);
this.items.push(item);
}
}
get(key: string): V | undefined {
return this.items.find((item) => item[0] === key)?.[1];
}
}

View file

@ -6,8 +6,10 @@ import {
IdeInfo,
IdeSettings,
IndexTag,
Location,
Problem,
Range,
RangeInFile,
Thread,
} from "../index.d.js";
@ -20,6 +22,13 @@ class FileSystemIde implements IDE {
fs.mkdirSync(FileSystemIde.workspaceDir, { recursive: true });
}
gotoDefinition(location: Location): Promise<RangeInFile[]> {
throw new Error("Method not implemented.");
}
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
throw new Error("Method not implemented.");
}
async getIdeSettings(): Promise<IdeSettings> {
return {
remoteConfigServerUrl: undefined,

View file

@ -5,11 +5,14 @@ import type {
IdeInfo,
IdeSettings,
IndexTag,
Location,
Problem,
Range,
RangeInFile,
Thread,
} from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js";
import { FromIdeProtocol } from "../protocol/index.js";
export class MessageIde implements IDE {
constructor(
@ -17,7 +20,18 @@ export class MessageIde implements IDE {
messageType: T,
data: ToIdeFromWebviewOrCoreProtocol[T][0],
) => Promise<ToIdeFromWebviewOrCoreProtocol[T][1]>,
private readonly on: <T extends keyof FromIdeProtocol>(
messageType: T,
callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1],
) => void,
) {}
async gotoDefinition(location: Location): Promise<RangeInFile[]> {
return this.request("gotoDefinition", { location });
}
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
}
getIdeSettings(): Promise<IdeSettings> {
return this.request("getIdeSettings", undefined);
}

View file

@ -19,6 +19,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
useRecentlyEdited: true,
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
useImports: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -1,4 +1,5 @@
import * as path from "path";
import fs from "node:fs";
import path from "node:path";
import Parser, { Language } from "web-tree-sitter";
export const supportedLanguages: { [key: string]: string } = {
@ -115,3 +116,34 @@ export async function getLanguageForFile(
return undefined;
}
}
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
}
export async function getQueryForFile(
filepath: string,
queryType: TSQueryType,
): Promise<Parser.Query | undefined> {
const language = await getLanguageForFile(filepath);
if (!language) {
return undefined;
}
const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""];
const sourcePath = path.join(
__dirname,
"..",
"tree-sitter",
queryType,
`${fullLangName}.scm`,
);
if (!fs.existsSync(sourcePath)) {
return undefined;
}
const querySource = fs.readFileSync(sourcePath).toString();
const query = language.query(querySource);
return query;
}

View file

@ -7,11 +7,11 @@ This is the Continue VS Code Extension. Its primary jobs are
# How to run the extension
See [Environment Setup](../CONTRIBUTING.md#environment-setup)
See [Environment Setup](../../CONTRIBUTING.md#environment-setup)
# How to run and debug tests
After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code.
After following the setup in [Environment Setup](../../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code.
## Notes

View file

@ -470,7 +470,7 @@ const exe = os === "win32" ? ".exe" : "";
// Validate the all of the necessary files are present
validateFilesPresent([
// Queries used to create the index for @code context provider
"tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm",
"tree-sitter/code-snippet-queries/c_sharp.scm",
// Queries used for @outline and @highlights context providers
"tag-qry/tree-sitter-c_sharp-tags.scm",

View file

@ -32,7 +32,9 @@ function gotoInputKey(input: GotoInput) {
const MAX_CACHE_SIZE = 50;
const gotoCache = new Map<string, RangeInFile[]>();
async function executeGotoProvider(input: GotoInput): Promise<RangeInFile[]> {
export async function executeGotoProvider(
input: GotoInput,
): Promise<RangeInFile[]> {
const cacheKey = gotoInputKey(input);
const cached = gotoCache.get(cacheKey);
if (cached) {

View file

@ -9,7 +9,9 @@ import type {
IdeInfo,
IdeSettings,
IndexTag,
Location,
Problem,
RangeInFile,
Thread,
} from "core";
import { Range } from "core";
@ -20,6 +22,7 @@ import {
getContinueGlobalPath,
} from "core/util/paths";
import * as vscode from "vscode";
import { executeGotoProvider } from "./autocomplete/lsp";
import { DiffManager } from "./diff/horizontal";
import { Repository } from "./otherExtensions/git";
import { VsCodeIdeUtils } from "./util/ideUtils";
@ -41,6 +44,25 @@ class VsCodeIde implements IDE {
this.ideUtils = new VsCodeIdeUtils();
}
async gotoDefinition(location: Location): Promise<RangeInFile[]> {
const result = await executeGotoProvider({
uri: location.filepath,
line: location.position.line,
character: location.position.character,
name: "vscode.executeDefinitionProvider",
});
return result;
}
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor) {
callback(editor.document.uri.fsPath);
}
});
}
private authToken: string | undefined;
private askedForAuth = false;

View file

@ -0,0 +1,9 @@
(import_statement
(import_clause
(named_imports
(import_specifier
(identifier) @import))))
(import_statement
(import_clause
(identifier) @import ))

View file

@ -42,6 +42,9 @@ async function resolveEditorContent(
if (foundSlashCommand && typeof slashCommand === "undefined") {
slashCommand = foundSlashCommand;
}
contextItemAttrs.push(...ctxItems);
if (text === "") {
continue;
}
@ -51,11 +54,14 @@ async function resolveEditorContent(
} else {
parts.push({ type: "text", text });
}
contextItemAttrs.push(...ctxItems);
} else if (p.type === "codeBlock") {
if (!p.attrs.item.editing) {
const text =
"```" + p.attrs.item.description + "\n" + p.attrs.item.content + "\n```";
"```" +
p.attrs.item.description +
"\n" +
p.attrs.item.content +
"\n```";
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
} else {
@ -96,7 +102,10 @@ async function resolveEditorContent(
if (item.itemType === "file") {
// This is a quick way to resolve @file references
const basename = getBasename(item.id);
const relativeFilePath = getRelativePath(item.id, await ideMessenger.ide.getWorkspaceDirs());
const relativeFilePath = getRelativePath(
item.id,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rawContent = await ideMessenger.ide.readFile(item.id);
const content = `\`\`\`${relativeFilePath}\n${rawContent}\n\`\`\`\n`;
contextItemsText += content;

View file

@ -54,7 +54,7 @@ export class IdeMessenger implements IIdeMessenger {
ide: IDE;
constructor() {
this.ide = new MessageIde(this.request.bind(this));
this.ide = new MessageIde(this.request.bind(this), () => {});
}
private _postToIde(messageType: string, data: any, messageId?: string) {