working implementation with single ts query

This commit is contained in:
Nate Sesti 2024-06-23 10:08:50 -07:00
parent cf36262738
commit faffaf08c4
15 changed files with 189 additions and 31 deletions

View file

@ -2,6 +2,8 @@ import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { getParserForFile } from "../util/treeSitter.js";
export type AstPath = Parser.SyntaxNode[];
export async function getAst(
filepath: string,
fileContents: string,
@ -23,7 +25,7 @@ export async function getAst(
export async function getTreePathAtCursor(
ast: Parser.Tree,
cursorIndex: number,
): Promise<Parser.SyntaxNode[] | undefined> {
): Promise<AstPath> {
const path = [ast.rootNode];
while (path[path.length - 1].childCount > 0) {
let foundChild = false;

View file

@ -33,6 +33,7 @@ import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
import { BracketMatchingService } from "./services/BracketMatchingService.js";
import { HierarchicalContextService } from "./services/HierarchicalContextService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import {
noFirstCharNewline,
@ -154,9 +155,14 @@ export class CompletionProvider {
this.onError.bind(this),
);
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
this.hierarchicalContextService = new HierarchicalContextService(
this.importDefinitionsService,
this.ide,
);
}
private importDefinitionsService: ImportDefinitionsService;
private hierarchicalContextService: HierarchicalContextService;
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -516,6 +522,7 @@ export class CompletionProvider {
llm.model,
extrasSnippets,
this.importDefinitionsService,
this.hierarchicalContextService,
);
// If prefix is manually passed

View file

@ -1,4 +1,3 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { TabAutocompleteOptions } from "../index.js";
@ -7,7 +6,7 @@ import {
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
LANGUAGES,
@ -21,6 +20,7 @@ import {
type AutocompleteSnippet,
} from "./ranking.js";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
import { HierarchicalContextService } from "./services/HierarchicalContextService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
export function languageForFilepath(
@ -32,7 +32,7 @@ export function languageForFilepath(
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean {
}
async function shouldCompleteMultiline(
filepath: string,
treePath: AstPath | undefined,
fullPrefix: string,
fullSuffix: string,
language: AutocompleteLanguageInfo,
@ -94,18 +94,6 @@ async function shouldCompleteMultiline(
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (!ast) {
return true;
}
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
} catch (e) {
console.error("Failed to parse AST", e);
}
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
@ -127,6 +115,7 @@ export async function constructAutocompletePrompt(
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
hierarchicalContextService: HierarchicalContextService,
): Promise<{
prefix: string;
suffix: string;
@ -145,6 +134,17 @@ export async function constructAutocompletePrompt(
);
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// Calculate AST Path
let treePath: AstPath | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (ast) {
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
}
} catch (e) {
console.error("Failed to parse AST", e);
}
// Find external snippets
let snippets: AutocompleteSnippet[] = [];
@ -215,6 +215,14 @@ export async function constructAutocompletePrompt(
snippets.push(...importSnippets);
}
if (options.useHierarchicalContext && treePath) {
const ctx = await hierarchicalContextService.getContextForPath(
filepath,
treePath,
);
snippets.push(...ctx);
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))
@ -269,7 +277,7 @@ export async function constructAutocompletePrompt(
suffix,
useFim: true,
completeMultiline: await shouldCompleteMultiline(
filepath,
treePath,
fullPrefix,
fullSuffix,
language,

View file

@ -0,0 +1,116 @@
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../..";
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
import { AstPath } from "../ast";
import { AutocompleteSnippet } from "../ranking";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
export class HierarchicalContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
max: 100,
});
constructor(
private readonly importDefinitionsService: ImportDefinitionsService,
private readonly ide: IDE,
) {}
private static getNodeId(node: Parser.SyntaxNode): string {
return `${node.startIndex}`;
}
private static TYPES_TO_USE = new Set(["program", "function_declaration"]);
/**
* Key comes from hash of parent key and node type and node id.
*/
private static keyFromNode(
parentKey: string,
astNode: Parser.SyntaxNode,
): string {
return createHash("sha256")
.update(parentKey)
.update(astNode.type)
.update(HierarchicalContextService.getNodeId(astNode))
.digest("hex");
}
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let query: Parser.Query | undefined;
switch (node.type) {
case "program":
this.importDefinitionsService.get(filepath);
break;
case "function_declaration":
query = await getQueryForFile(
filepath,
TSQueryType.FunctionDeclaration,
);
break;
default:
break;
}
if (!query) {
return snippets;
}
await Promise.all(
query.matches(node).map(async (match) => {
const startPosition = match.captures[0].node.startPosition;
const endPosition = match.captures[0].node.endPosition;
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
snippets.push(...newSnippets);
}),
);
return snippets;
}
async getContextForPath(
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>
HierarchicalContextService.TYPES_TO_USE.has(node.type),
)) {
const key = HierarchicalContextService.keyFromNode(parentKey, astNode);
const foundInCache = this.cache.get(key);
const newSnippets =
foundInCache ?? (await this.getSnippetsForNode(filepath, astNode));
snippets.push(...newSnippets);
if (!foundInCache) {
this.cache.set(key, newSnippets);
}
parentKey = key;
}
return snippets;
}
}

View file

@ -1,11 +1,11 @@
import { IDE } from "..";
import { RangeInFileWithContents } from "../commands/util";
import { PrecalculatedLruCache } from "../util/LruCache";
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter";
} from "../../util/treeSitter";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };

1
core/index.d.ts vendored
View file

@ -768,6 +768,7 @@ export interface TabAutocompleteOptions {
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
useHierarchicalContext?: boolean;
}
export interface ContinueUIConfig {

21
core/package-lock.json generated
View file

@ -37,6 +37,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -2027,6 +2028,15 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@ -10826,12 +10836,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
"integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
"engines": {
"node": "14 || >=16.14"
}
},
"node_modules/mac-ca": {

View file

@ -57,6 +57,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

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

View file

@ -120,6 +120,8 @@ export async function getLanguageForFile(
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
// Used in HierarchicalContextService.ts
FunctionDeclaration = "hierarchical-context-queries/function_declaration",
}
export async function getQueryForFile(

View file

@ -121,6 +121,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -1,5 +1,5 @@
import { VsCodeExtension } from "../extension/vscodeExtension";
import { IContextProvider } from "core";
import { VsCodeExtension } from "../extension/vscodeExtension";
export class VsCodeContinueApi {
constructor(private readonly vscodeExtension: VsCodeExtension) {}
@ -7,4 +7,4 @@ export class VsCodeContinueApi {
registerCustomContextProvider(contextProvider: IContextProvider) {
this.vscodeExtension.registerCustomContextProvider(contextProvider);
}
}
}

View file

@ -1,7 +1,7 @@
import { devDataPath } from "core/util/paths";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { devDataPath } from "core/util/paths";
import * as vscode from "vscode";
import { getMetaKeyLabel, getPlatform } from "../util/util";
import { uriFromFilePath } from "../util/vscode";

View file

@ -0,0 +1,9 @@
(
(function_declaration
(formal_parameters
(_
(type_annotation) @a
)
)
)
)

1
gui/package-lock.json generated
View file

@ -114,6 +114,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",