From faffaf08c4081dca4653c3efbe8910bd4b5c6654 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 23 Jun 2024 10:08:50 -0700 Subject: [PATCH] working implementation with single ts query --- core/autocomplete/ast.ts | 4 +- core/autocomplete/completionProvider.ts | 7 ++ core/autocomplete/constructPrompt.ts | 42 ++++--- .../services/HierarchicalContextService.ts | 116 ++++++++++++++++++ .../services/ImportDefinitionsService.ts | 8 +- core/index.d.ts | 1 + core/package-lock.json | 21 +++- core/package.json | 1 + core/util/parameters.ts | 1 + core/util/treeSitter.ts | 2 + extensions/vscode/package-lock.json | 1 + extensions/vscode/src/activation/api.ts | 4 +- extensions/vscode/src/diff/horizontal.ts | 2 +- .../function_declaration/typescript.scm | 9 ++ gui/package-lock.json | 1 + 15 files changed, 189 insertions(+), 31 deletions(-) create mode 100644 core/autocomplete/services/HierarchicalContextService.ts create mode 100644 extensions/vscode/tree-sitter/hierarchical-context-queries/function_declaration/typescript.scm diff --git a/core/autocomplete/ast.ts b/core/autocomplete/ast.ts index 933ae76c0..139b22dbf 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/ast.ts @@ -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 { +): Promise { const path = [ast.rootNode]; while (path[path.length - 1].childCount > 0) { let foundChild = false; diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 260535d4b..6a2c994a1 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -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 = new Set(); @@ -516,6 +522,7 @@ export class CompletionProvider { llm.model, extrasSnippets, this.importDefinitionsService, + this.hierarchicalContextService, ); // If prefix is manually passed diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7e63375bb..3c633218d 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -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, diff --git a/core/autocomplete/services/HierarchicalContextService.ts b/core/autocomplete/services/HierarchicalContextService.ts new file mode 100644 index 000000000..5424d1b25 --- /dev/null +++ b/core/autocomplete/services/HierarchicalContextService.ts @@ -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({ + 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 { + 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 { + 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; + } +} diff --git a/core/autocomplete/services/ImportDefinitionsService.ts b/core/autocomplete/services/ImportDefinitionsService.ts index 19287bf81..0df08f096 100644 --- a/core/autocomplete/services/ImportDefinitionsService.ts +++ b/core/autocomplete/services/ImportDefinitionsService.ts @@ -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[] }; diff --git a/core/index.d.ts b/core/index.d.ts index 658f5c980..ef12570d5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -768,6 +768,7 @@ export interface TabAutocompleteOptions { recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; + useHierarchicalContext?: boolean; } export interface ContinueUIConfig { diff --git a/core/package-lock.json b/core/package-lock.json index e4587f56b..5b9ca2b15 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -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": { diff --git a/core/package.json b/core/package.json index fd34477ef..b52c8818d 100644 --- a/core/package.json +++ b/core/package.json @@ -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", diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 8909af6f4..f64750255 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -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; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 95a7a10ce..904f87e39 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -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( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 6d0e21452..65b5fd37b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -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", diff --git a/extensions/vscode/src/activation/api.ts b/extensions/vscode/src/activation/api.ts index 03a814ae9..bc5f261e0 100644 --- a/extensions/vscode/src/activation/api.ts +++ b/extensions/vscode/src/activation/api.ts @@ -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); } -} \ No newline at end of file +} diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index 870022457..da922cd50 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -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"; diff --git a/extensions/vscode/tree-sitter/hierarchical-context-queries/function_declaration/typescript.scm b/extensions/vscode/tree-sitter/hierarchical-context-queries/function_declaration/typescript.scm new file mode 100644 index 000000000..75cac3c55 --- /dev/null +++ b/extensions/vscode/tree-sitter/hierarchical-context-queries/function_declaration/typescript.scm @@ -0,0 +1,9 @@ +( + (function_declaration + (formal_parameters + (_ + (type_annotation) @a + ) + ) + ) +) \ No newline at end of file diff --git a/gui/package-lock.json b/gui/package-lock.json index d652bc561..e9952da27 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -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",