diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index e6111a508..0d974e317 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { getAllSnippets } from "./snippets/index.js"; +import { getAllSnippetsWithoutRace } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; @@ -121,6 +121,12 @@ export class CompletionProvider { ...config?.tabAutocompleteOptions, ...llm.autocompleteOptions, }; + + // Enable static contextualization if defined. + if (config?.experimental?.enableStaticContextualization) { + options.experimental_enableStaticContextualization = true; + } + return options; } @@ -171,7 +177,7 @@ export class CompletionProvider { } const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippets({ + getAllSnippetsWithoutRace({ helper, ide: this.ide, getDefinitionsFromLsp: this.getDefinitionsFromLsp, @@ -258,6 +264,10 @@ export class CompletionProvider { ...helper.options, }; + if (options.experimental_enableStaticContextualization) { + outcome.enabledStaticContextualization = true; + } + ////////// // Save to cache diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index f521d292a..e7e9e60a4 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -2,16 +2,19 @@ import { IDE } from "../.."; import { AutocompleteCodeSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; +import { StaticContextService } from "./static-context/StaticContextService"; export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; + private staticContextService: StaticContextService; constructor(private readonly ide: IDE) { this.importDefinitionsService = new ImportDefinitionsService(this.ide); @@ -19,6 +22,7 @@ export class ContextRetrievalService { this.importDefinitionsService, this.ide, ); + this.staticContextService = new StaticContextService(this.ide); } public async getSnippetsFromImportDefinitions( @@ -71,6 +75,12 @@ export class ContextRetrievalService { ); } + public async getStaticContextSnippets( + helper: HelperVars, + ): Promise { + return this.staticContextService.getContext(helper); + } + /** * Initialize the import definitions cache for a file. * This is normally done automatically when the active text editor changes, diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts new file mode 100644 index 000000000..b955a38ff --- /dev/null +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -0,0 +1,888 @@ +import * as fs from "fs/promises"; +import path from "path"; +import { pathToFileURL } from "url"; +import Parser from "web-tree-sitter"; +import { IDE, Position } from "../../.."; +import { localPathOrUriToPath } from "../../../util/pathToUri"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import { + AutocompleteSnippetType, + AutocompleteStaticSnippet, +} from "../../snippets/types"; +import { getAst } from "../../util/ast"; +import { HelperVars } from "../../util/HelperVars"; +import { + extractFunctionTypeFromDecl, + extractTopLevelDecls, + findEnclosingTypeDeclaration, + unwrapToBaseType, +} from "./tree-sitter-utils"; +import { + HoleContext, + RelevantHeaders, + RelevantTypes, + StaticContext, + TypeSpanAndSourceFile, + TypeSpanAndSourceFileAndAst, +} from "./types"; + +export class StaticContextService { + private readonly ide: IDE; + + constructor(ide: IDE) { + this.ide = ide; + } + + public logAutocompleteStaticSnippet( + ctx: StaticContext, + label = "Static Snippet", + ) { + console.log(`=== ${label} ===`); + console.log("Hole Type:", ctx.holeType); + + console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`); + ctx.relevantTypes.forEach((types, filepath) => { + console.log(` 📁 ${filepath}`); + types.forEach((type) => console.log(` • ${type}`)); + }); + + console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`); + ctx.relevantHeaders.forEach((headers, filepath) => { + console.log(` 📁 ${filepath}`); + headers.forEach((header) => console.log(` • ${header}`)); + }); + } + + public static formatAutocompleteStaticSnippet(ctx: StaticContext): string { + let output = `AutocompleteStaticSnippet:\n`; + output += ` holeType: ${ctx.holeType}\n`; + + output += ` relevantTypes:\n`; + if (ctx.relevantTypes.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantTypes.forEach((types, filepath) => { + output += ` ${filepath}: [${types.join(", ")}]\n`; + }); + } + + output += ` relevantHeaders:\n`; + if (ctx.relevantHeaders.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantHeaders.forEach((headers, filepath) => { + output += ` ${filepath}: [${headers.join(", ")}]\n`; + }); + } + + return output; + } + + public async getContext( + helper: HelperVars, + ): Promise { + const start = Date.now(); + const tsFiles = await this.getTypeScriptFilesFromWorkspaces( + helper.workspaceUris, + ); + // Get the three contexts holeContext, relevantTypes, relevantHeaders. + const holeContext = await this.getHoleContext( + helper.fileContents, + helper.filepath, + helper.pos, + ); + + const relevantTypes = await this.extractRelevantTypes( + holeContext.fullHoverResult, + holeContext.functionName, + holeContext.range.start.line, + holeContext.source, + new Map(), + ); + + // if (this.language === "typescript") { + // repo = getAllTSFiles(this.repoPath); + // } else if (this.language === "ocaml") { + // repo = getAllOCamlFiles(this.repoPath); + // } + // + + const relevantHeaders = await this.extractRelevantHeaders( + tsFiles, + relevantTypes, + holeContext.functionTypeSpan, + helper.pos, + holeContext.returnTypeIsAny, + ); + + const relevantTypesToReturn: Map = new Map< + string, + string[] + >(); + relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => { + if (relevantTypesToReturn.has(src)) { + const updated = relevantTypesToReturn.get(src)!; + updated.push(v); + relevantTypesToReturn.set(src, updated); + } else { + relevantTypesToReturn.set(src, [v]); + } + }); + + const relevantHeadersToReturn: Map = new Map< + string, + string[] + >(); + relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => { + if (relevantHeadersToReturn.has(src)) { + const updated = relevantHeadersToReturn.get(src)!; + if (!updated.includes(v)) { + updated.push(v); + } + relevantHeadersToReturn.set(src, updated); + } else { + relevantHeadersToReturn.set(src, [v]); + } + }); + + const ctx = { + holeType: holeContext.functionTypeSpan, + relevantTypes: relevantTypesToReturn, + relevantHeaders: relevantHeadersToReturn, + }; + const end = Date.now(); + + this.logAutocompleteStaticSnippet(ctx); + + // console.log(end - start); + + const snippets: AutocompleteStaticSnippet[] = []; + + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(holeContext.source)).toString(), + content: holeContext.fullHoverResult, + }); + + for (const [filepath, typs] of ctx.relevantTypes.entries()) { + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: typs.join("\n"), + }); + } + + for (const [filepath, headers] of ctx.relevantHeaders.entries()) { + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: headers.join("\n"), + }); + } + + return snippets; + } + + private async getHoleContext( + sketchFileContent: string, + sketchFilePath: string, + cursorPosition: Position, + ): Promise { + // We need to inject the hole @ to trigger a treesitter error node. + sketchFilePath = localPathOrUriToPath(sketchFilePath); + // const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); + const injectedContent = this.insertAtPosition( + sketchFileContent, + cursorPosition, + "@;", + ); + + // The hole's position is cursorPosition. + + // Use treesitter to parse. + const ast = await getAst(sketchFilePath, injectedContent); + if (!ast) { + throw new Error("failed to get ast"); + } + const language = getFullLanguageName(sketchFilePath); + const query = await getQueryForFile( + sketchFilePath, + `static-context-queries/hole-queries/${language}.scm`, + ); + if (!query) { + throw new Error( + `getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`, + ); + } + + const captures = query.captures(ast.rootNode); + const res: HoleContext = { + fullHoverResult: "", + functionName: "", + functionTypeSpan: "", + returnTypeIsAny: false, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + source: `file://${sketchFilePath}`, + }; + let paramsTypes = ""; + for (const c of captures) { + const { name, node } = c; + // console.log(`${name} →`, node.text, node.startPosition, node.endPosition); + + switch (name) { + case "function.decl": { + res.fullHoverResult = node.text; + break; + } + case "function.name": { + res.functionName = node.text; + break; + } + case "function.params": { + paramsTypes = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + break; + } + case "function.type": { + res.functionTypeSpan = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + break; + } + } + } + + if (res.functionTypeSpan === "") { + res.functionTypeSpan = `${paramsTypes} => any`; + res.returnTypeIsAny = true; + } + + return res; + } + + private async extractRelevantTypes( + declText: string, + typeName: string, + startLine: number, + currentFile: string, + foundContents: Map, // uri -> contents + ): Promise { + const foundSoFar = new Map(); // identifier -> [full hover result, source] + + await this.extractRelevantTypesHelper( + declText, + typeName, + startLine, + foundSoFar, + currentFile, + foundContents, + ); + + return foundSoFar; + } + + private async extractRelevantTypesHelper( + declText: string, + typeName: string, + startLine: number, + foundSoFar: Map, // identifier -> [full hover result, source] + currentFile: string, + foundContents: Map, // uri -> contents + ) { + if (!foundSoFar.has(typeName)) { + const ast = await getAst(currentFile, declText); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + foundSoFar.set(typeName, { + typeSpan: declText, + sourceFile: currentFile.slice(7), + ast: ast, + }); + + const language = getFullLanguageName(currentFile); + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + + const identifiers = query.captures(ast.rootNode); + + for (const { name, node } of identifiers) { + if (foundSoFar.has(node.text)) continue; + + try { + const typeDefinitionResult = await this.ide.gotoTypeDefinition({ + filepath: currentFile, + position: { + character: node.startPosition.column, + line: startLine + node.startPosition.row, + }, + }); + + if (typeDefinitionResult.length > 0) { + const tdLocation = typeDefinitionResult[0]; + + let content = ""; + + if (foundContents.has(tdLocation.filepath)) { + content = foundContents.get(tdLocation.filepath)!; + } else { + content = await fs.readFile( + localPathOrUriToPath(tdLocation.filepath), + "utf8", + ); + foundContents.set(tdLocation.filepath, content); + } + + const ast = await getAst(tdLocation.filepath, content); + if (!ast) { + throw new Error( + `failed to get ast for file ${tdLocation.filepath}`, + ); + } + const decl = findEnclosingTypeDeclaration( + content, + tdLocation.range.start.line, + tdLocation.range.start.character, + ast, + ); + if (!decl) { + // throw new Error(`failed to get decl for file ${tdLocation.uri}`); + console.error( + `failed to get decl for file ${tdLocation.filepath}`, + ); + } + + if (decl) { + await this.extractRelevantTypesHelper( + decl.fullText, + node.text, + tdLocation.range.start.line, + foundSoFar, + tdLocation.filepath, + foundContents, + ); + } else { + // console.log("decl not found"); + } + } else { + // console.log("td not found"); + } + } catch (err) { + console.log(err); + } + } + } + } + + private async extractRelevantHeaders( + sources: string[], + relevantTypes: Map, + holeType: string, + cursorPosition: Position, + returnTypeIsAny: boolean, + ): Promise { + const relevantContext = new Set(); + if (returnTypeIsAny) return relevantContext; + // NOTE: This is necessary because TypeScript sucks. + // There is no way to compare objects by value, + // so sets of objects starts to accumulate tons of duplicates. + const relevantContextMap = new Map(); + const foundNormalForms = new Map(); + + const targetTypes = await this.generateTargetTypes(relevantTypes, holeType); + + for (const source of sources) { + const topLevelDecls = await extractTopLevelDecls(source); + for (const tld of topLevelDecls) { + // pattern 0 is let/const, 1 is var, 2 is fun + // if (!seenDecls.has(JSON.stringify()) { + const originalDeclText = + tld.pattern === 2 + ? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text + : tld.captures.find((d) => d.name === "top.var.decl")!.node.text; + + if (tld.pattern === 2) { + // build a type span + // TODO: this fails sometimes with Cannot read properties of undefined (reading 'text') + // most likely due to my scm query and how I'm not attaching param name along with param type + let funcType = ""; + try { + funcType = extractFunctionTypeFromDecl(tld); + } catch (err) { + // Most likely is the case that there is no explicit return type annotation. + const sigHelp = await this.ide.getSignatureHelp({ + filepath: source, + position: cursorPosition, + }); + if (!sigHelp) continue; + funcType = sigHelp.signatures[0].label; + + // TODO: This only works for TypeScript. + function convertToArrowType(signature: string): string { + // Handle various function declaration formats. + const patterns = [ + // Standard: functionName(params): returnType. + /^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + // With generics: functionName(params): returnType. + /^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/, + // With modifiers: export function functionName(params): returnType. + /^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + ]; + + for (const pattern of patterns) { + const match = signature.match(pattern); + if (match) { + const [, , parameters, returnType] = match; + return `(${parameters}) => ${returnType}`; + } + } + + return signature; + } + + funcType = convertToArrowType(funcType); + } + const wrapped = `type __TMP = ${funcType};`; + + const ast = await getAst("file.ts", wrapped); + if (!ast) { + throw new Error(`failed to generate ast for ${wrapped}`); + } + + // console.log(ast.rootNode); + const alias = ast.rootNode.namedChild(0); + // console.log(alias); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error( + "extractRelevantHeaders: Failed to parse type alias", + ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + + await this.extractRelevantHeadersHelper( + originalDeclText, + baseNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } else { + const varTypNode = tld.captures.find( + (d) => d.name === "top.var.type", + )!.node; + await this.extractRelevantHeadersHelper( + originalDeclText, + varTypNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + + for (const v of relevantContextMap.values()) { + relevantContext.add(v); + } + + return relevantContext; + } + + private async extractRelevantHeadersHelper( + originalDeclText: string, + node: Parser.SyntaxNode, + targetTypes: Set, + relevantTypes: Map, + relevantContext: Set, + relevantContextMap: Map, + foundNormalForms: Map, + source: string, + ) { + for (const typ of targetTypes) { + if ( + await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms) + ) { + const ctx = { typeSpan: originalDeclText, sourceFile: source }; + relevantContextMap.set(JSON.stringify(ctx), ctx); + } + + if (node.type === "function_type") { + const retTypeNode = node.namedChildren.find( + (c) => c && c.type === "return_type", + ); + if (retTypeNode) { + await this.extractRelevantHeadersHelper( + originalDeclText, + retTypeNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } else if (node.type === "tuple_type") { + for (const c of node.namedChildren) { + await this.extractRelevantHeadersHelper( + originalDeclText, + c!, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + } + + private async generateTargetTypes( + relevantTypes: Map, + holeType: string, + ) { + const targetTypes = new Set(); + // const ast = relevantTypes.get(holeIdentifier)!.ast; + const ast = await getAst("file.ts", `type T = ${holeType};`); + if (!ast) { + throw new Error(`failed to generate ast for ${holeType}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error("generateTargetTypes: Failed to parse type alias"); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + targetTypes.add(baseNode); + await this.generateTargetTypesHelper( + relevantTypes, + holeType, + targetTypes, + baseNode, + ); + + return targetTypes; + } + + private async generateTargetTypesHelper( + relevantTypes: Map, + currType: string, + targetTypes: Set, + node: Parser.SyntaxNode | null, + ): Promise { + if (!node) return; + + if (node.type === "function_type") { + const returnType = node.childForFieldName("return_type"); + if (returnType) { + targetTypes.add(returnType); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + returnType, + ); + } + } + + if (node.type === "tuple_type") { + for (const child of node.namedChildren) { + if (child) { + targetTypes.add(child); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + child, + ); + } + } + } + + if (relevantTypes.has(node.text)) { + // const ast = relevantTypes.get(node.text)!.ast; + const typeSpan = relevantTypes.get(node.text)?.typeSpan; + + // const ast = await getAst("file.ts", `type T = ${typeSpan}`); + const ast = await getAst("file.ts", typeSpan!); + if (!ast) { + throw new Error(`failed to generate ast for ${typeSpan}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + console.error("generateTargetTypesHelper: Failed to parse type alias"); + return; + // throw new Error( + // "generateTargetTypesHelper: Failed to parse type alias", + // ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + baseNode, + ); + } + + // if (node.type === "type_identifier" || node.type === "predefined_type") { + // return [node.text]; + // } + + return; + } + + private async isTypeEquivalent( + node: Parser.SyntaxNode, + typ: Parser.SyntaxNode, + relevantTypes: Map, + foundNormalForms: Map, + ): Promise { + if (!node || !typ) { + return false; + } + let normT1 = ""; + let normT2 = ""; + if (foundNormalForms.has(node.text)) { + // console.log("found t1", true) + normT1 = foundNormalForms.get(node.text)!; + } else { + // console.log("not found t1", false) + normT1 = await this.normalize(node, relevantTypes); + foundNormalForms.set(node.text, normT1); + } + if (foundNormalForms.has(typ.text)) { + // console.log("found t2", true) + normT2 = foundNormalForms.get(typ.text)!; + } else { + // console.log("not found t2", false) + normT2 = await this.normalize(typ, relevantTypes); + foundNormalForms.set(typ.text, normT2); + } + // const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes); + // const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes); + // console.log(`normal forms: ${normT1} {}{} ${normT2}`) + return normT1 === normT2; + } + + private async normalize( + node: Parser.SyntaxNode, + relevantTypes: Map, + ): Promise { + if (!node) return ""; + + switch (node.type) { + case "function_type": { + const params = node.child(0); // formal_parameters + const returnType = + node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return + + const paramTypes = + params?.namedChildren + .map((param) => + this.normalize( + param!.childForFieldName("type")! || + param!.namedChildren.at(-1), + relevantTypes, + ), + ) + .join(", ") || ""; + + const ret = this.normalize(returnType!, relevantTypes); + return `(${paramTypes}) => ${ret}`; + } + + case "tuple_type": { + const elements = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return `[${elements.join(", ")}]`; + } + + case "union_type": { + const parts = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return parts.join(" | "); + } + + case "type_identifier": { + const alias = relevantTypes.get(node.text); + if (!alias) return node.text; + + // Parse the alias's type span + const wrapped = `type __TMP = ${alias};`; + const tree = await getAst("file.ts", wrapped); + const valueNode = tree!.rootNode + .descendantsOfType("type_alias_declaration")[0] + ?.childForFieldName("value"); + + return this.normalize(valueNode!, relevantTypes); + } + + case "predefined_type": + case "number": + case "string": + return node.text; + + default: + // Fallback for types like array, etc. + return node.text; + } + } + + private insertAtPosition = ( + contents: string, + cursorPosition: { line: number; character: number }, + insertText: string, + ): string => { + const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings + const { line, character } = cursorPosition; + + if (line < 0 || line >= lines.length) { + throw new Error("Invalid line number"); + } + + const targetLine = lines[line]; + if (character < 0 || character > targetLine.length) { + throw new Error("Invalid character index"); + } + + // Insert the text + lines[line] = + targetLine.slice(0, character) + insertText + targetLine.slice(character); + + return lines.join("\n"); // Reconstruct the file + }; + + private async getTypeScriptFilesFromWorkspaces( + workspaceUris: string[], + ): Promise { + const tsExtensions = [".ts"]; + const allTsFiles: string[] = []; + + for (const workspaceUri of workspaceUris) { + try { + // Convert URI to file path + const folderPath = workspaceUri.startsWith("file://") + ? new URL(workspaceUri).pathname + : workspaceUri; + + const tsFiles = await this.scanDirectoryForTypeScriptFiles( + folderPath, + tsExtensions, + ); + allTsFiles.push(...tsFiles); + } catch (error) { + console.error(`Error scanning workspace ${workspaceUri}:`, error); + } + } + + return allTsFiles; + } + + private async scanDirectoryForTypeScriptFiles( + dirPath: string, + tsExtensions: string[], + ): Promise { + const tsFiles: string[] = []; + + const shouldSkipDirectory = (dirName: string): boolean => { + const skipDirs = [ + "node_modules", + ".git", + ".vscode", + "dist", + "build", + "out", + ".next", + "coverage", + ".nyc_output", + "tmp", + "temp", + ".cache", + ]; + + return skipDirs.includes(dirName) || dirName.startsWith("."); + }; + + async function scanRecursively(currentPath: string): Promise { + try { + const entries = await fs.readdir(currentPath, { + withFileTypes: true, + }); + + for (const entry of entries) { + const fullPath = localPathOrUriToPath( + path.join(currentPath, entry.name), + ); + + if (entry.isDirectory()) { + // Skip common directories that typically don't contain source files + if (!shouldSkipDirectory(entry.name)) { + await scanRecursively(fullPath); + } + } else if (entry.isFile()) { + const extension = path.extname(entry.name).toLowerCase(); + if (tsExtensions.includes(extension)) { + tsFiles.push(fullPath); + } + } + } + } catch (error) { + console.error(`Error reading directory ${currentPath}:`, error); + } + } + + await scanRecursively(dirPath); + return tsFiles; + } +} diff --git a/core/autocomplete/context/static-context/tree-sitter-utils.ts b/core/autocomplete/context/static-context/tree-sitter-utils.ts new file mode 100644 index 000000000..6e751f547 --- /dev/null +++ b/core/autocomplete/context/static-context/tree-sitter-utils.ts @@ -0,0 +1,222 @@ +import * as fs from "fs/promises"; +import Parser from "web-tree-sitter"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import { getAst } from "../../util/ast"; + +export interface TypeDeclarationResult { + name: string; + fullText: string; + startLine: number; + startColumn: number; + endLine: number; + endColumn: number; + kind: string; +} + +export function findEnclosingTypeDeclaration( + sourceCode: string, + cursorLine: number, + cursorColumn: number, + ast: Parser.Tree, +): TypeDeclarationResult | null { + const point = { row: cursorLine, column: cursorColumn }; + let node = ast.rootNode.descendantForPosition(point); + + while ( + node && + ![ + "type_alias_declaration", + "interface_declaration", + "enum_declaration", + ].includes(node.type) + ) { + if (!node.parent) return null; + node = node.parent; + } + + if (!node) return null; + + const nameNode = node.childForFieldName("name"); + const name = nameNode?.text ?? ""; + const fullText = sourceCode.slice(node.startIndex, node.endIndex); + + return { + name, + fullText, + startLine: node.startPosition.row, + startColumn: node.startPosition.column, + endLine: node.endPosition.row, + endColumn: node.endPosition.column, + kind: node.type, + }; +} + +export async function extractTopLevelDecls( + currentFile: string, + givenParser?: Parser, +) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + return query.matches(ast.rootNode); +} + +export async function extractTopLevelDeclsWithFormatting( + currentFile: string, + givenParser?: Parser, +) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + const matches = query.matches(ast.rootNode); + + const results = []; + + for (const match of matches) { + const item: { + declaration: string; + nodeType: string; + name: string; + declaredType: string; + returnType?: string; + } = { + declaration: "", + nodeType: "", + name: "", + declaredType: "", + }; + + for (const { name, node } of match.captures) { + if (name === "top.var.decl") { + item.nodeType = "variable"; + item.declaration = node.text; + + // Attempt to get the declared type (e.g., const x: string = ...) + const typeNode = node.descendantsOfType("type_annotation")[0]; + if (typeNode) { + item.declaredType = typeNode.text.replace(/^:\s*/, ""); + } + } else if (name === "top.var.name" || name === "top.fn.name") { + item.name = node.text; + } else if (name === "top.fn.decl") { + item.nodeType = "function"; + item.declaration = node.text; + + // Get the return type (e.g., function foo(): string) + const returnTypeNode = node.childForFieldName("return_type"); + if (returnTypeNode) { + item.returnType = returnTypeNode.text.replace(/^:\s*/, ""); + } + + // Get declaredType if needed (TypeScript style) + const nameNode = node.childForFieldName("name"); + if (nameNode && nameNode.nextSibling?.type === "type_annotation") { + item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, ""); + } + } + } + + if (item.name && item.declaration) { + results.push(item); + } + } + + return results; +} + +export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string { + let paramsNode: Parser.SyntaxNode | undefined = undefined; + let returnNode: Parser.SyntaxNode | undefined = undefined; + + for (const capture of match.captures) { + if (capture.name === "top.fn.param.type") { + paramsNode = capture.node; + } else if (capture.name === "top.fn.type") { + returnNode = capture.node; + } + } + + if (!paramsNode) { + console.error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); + } + + if (!returnNode) { + console.error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); + } + + return `(${paramsNode!.text}) => ${returnNode!.text}`; +} + +export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode { + if ( + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(node.type) + ) { + return node; + } + + for (const child of node.namedChildren) { + const unwrapped = unwrapToBaseType(child!); + if ( + unwrapped !== child || + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(unwrapped.type) + ) { + return unwrapped; + } + } + + return node; +} diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts new file mode 100644 index 000000000..1aa8b473d --- /dev/null +++ b/core/autocomplete/context/static-context/types.ts @@ -0,0 +1,33 @@ +import { Tree } from "web-tree-sitter"; +import { Range } from "../../.."; + +export interface TypeSpanAndSourceFile { + typeSpan: string; + sourceFile: string; +} + +export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { + ast: Tree; +} + +export interface HoleContext { + fullHoverResult: string; + functionName: string; + functionTypeSpan: string; + returnTypeIsAny: boolean; + range: Range; + source: string; +} + +export type RelevantTypes = Map; +export type RelevantHeaders = Set; + +export type Filepath = string; +export type RelevantType = string; +export type RelevantHeader = string; + +export interface StaticContext { + holeType: string; + relevantTypes: Map; + relevantHeaders: Map; +} diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 702356198..079127abc 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -11,6 +11,7 @@ import { AutocompleteCodeSnippet, AutocompleteDiffSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "./types"; const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled @@ -24,6 +25,7 @@ export interface SnippetPayload { diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; recentlyOpenedFileSnippets: AutocompleteCodeSnippet[]; + staticSnippet: AutocompleteStaticSnippet[]; } function racePromise(promise: Promise, timeout = 100): Promise { @@ -185,6 +187,7 @@ export const getAllSnippets = async ({ diffSnippets, clipboardSnippets, recentlyOpenedFileSnippets, + staticSnippet, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -196,6 +199,9 @@ export const getAllSnippets = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete + helper.options.experimental_enableStaticContextualization + ? racePromise(contextRetrievalService.getStaticContextSnippets(helper)) + : [], ]); return { @@ -207,6 +213,7 @@ export const getAllSnippets = async ({ clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, recentlyOpenedFileSnippets, + staticSnippet, }; }; @@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyOpenedFileSnippets, + staticSnippet, ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), @@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), getSnippetsFromRecentlyOpenedFiles(helper, ide), + helper.options.experimental_enableStaticContextualization + ? contextRetrievalService.getStaticContextSnippets(helper) + : [], ]); return { @@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({ clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, recentlyOpenedFileSnippets, + staticSnippet, }; }; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index e43b59862..be820609b 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -2,6 +2,7 @@ export enum AutocompleteSnippetType { Code = "code", Diff = "diff", Clipboard = "clipboard", + Static = "static", } interface BaseAutocompleteSnippet { @@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { copiedAt: string; } +export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Static; + filepath: string; +} + export type AutocompleteSnippet = | AutocompleteCodeSnippet | AutocompleteDiffSnippet - | AutocompleteClipboardSnippet; + | AutocompleteClipboardSnippet + | AutocompleteStaticSnippet; diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index 2abb98c7d..94fe312e2 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -4,6 +4,7 @@ import { AutocompleteCodeSnippet, AutocompleteSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; import { formatOpenedFilesContext } from "./formatOpenedFilesContext"; @@ -32,9 +33,9 @@ const shuffleArray = (array: T[]): T[] => { }; function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteCodeSnippet[], + snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[], caretWindow: string, -): AutocompleteCodeSnippet[] { +): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] { return snippets.filter( (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()), ); @@ -52,7 +53,11 @@ export const getSnippets = ( recentlyOpenedFiles: payload.recentlyOpenedFileSnippets, base: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), @@ -107,7 +112,11 @@ export const getSnippets = ( defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override snippets: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts index 2a91ad438..583873c2d 100644 --- a/core/autocomplete/templating/formatting.ts +++ b/core/autocomplete/templating/formatting.ts @@ -5,6 +5,7 @@ import { AutocompleteDiffSnippet, AutocompleteSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; @@ -51,6 +52,12 @@ const formatDiffSnippet = ( return snippet; }; +const formatStaticSnippet = ( + snippet: AutocompleteStaticSnippet, +): AutocompleteStaticSnippet => { + return snippet; +}; + const commentifySnippet = ( helper: HelperVars, snippet: AutocompleteSnippet, @@ -81,6 +88,8 @@ export const formatSnippets = ( return formatDiffSnippet(snippet); case AutocompleteSnippetType.Clipboard: return formatClipboardSnippet(snippet, workspaceDirs); + case AutocompleteSnippetType.Static: + return formatStaticSnippet(snippet); } }) .map((item) => { diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 2e4d19844..58b3d2d0d 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -105,24 +105,27 @@ export class AutocompleteLoggingService { }); const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: getUriFileExtension(restOfOutcome.filepath), - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - numLines: restOfOutcome.numLines, - }, - true, - ); + const toLog = { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: getUriFileExtension(restOfOutcome.filepath), + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + numLines: restOfOutcome.numLines, + }; + + outcome.enabledStaticContextualization + ? void Telemetry.capture("autocomplete", { + ...toLog, + enabledStaticContextualization: true, + }) + : void Telemetry.capture("autocomplete", toLog); } } diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index bd385fb47..4f669fc63 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { completionId: string; uniqueId: string; timestamp: string; + enabledStaticContextualization?: boolean; } diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index c720f4272..568a30af8 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -22,6 +22,7 @@ export const sharedConfigSchema = z optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), + enableStaticContextualization: z.boolean(), // `ui` in `ContinueConfig` showSessionTabs: z.boolean(), @@ -188,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; } + if (sharedConfig.enableStaticContextualization !== undefined) { + configCopy.experimental.enableStaticContextualization = + sharedConfig.enableStaticContextualization; + } return configCopy; } diff --git a/core/index.d.ts b/core/index.d.ts index c2bc7487b..b37807e1f 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -871,6 +871,8 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; // TODO: add to jetbrains + getSignatureHelp(location: Location): Promise; // TODO: add to jetbrains // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -1209,6 +1211,7 @@ export interface TabAutocompleteOptions { experimental_includeRecentlyVisitedRanges: boolean | number; experimental_includeRecentlyEditedRanges: boolean | number; experimental_includeDiff: boolean | number; + experimental_enableStaticContextualization: boolean; } export interface StdioOptions { @@ -1408,6 +1411,68 @@ export interface RangeInFileWithNextEditInfo { export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; +/** + * Signature help represents the signature of something + * callable. There can be multiple signatures but only one + * active and only one active parameter. + */ +export class SignatureHelp { + /** + * One or more signatures. + */ + signatures: SignatureInformation[]; + + /** + * The active signature. + */ + activeSignature: number; + + /** + * The active parameter of the active signature. + */ + activeParameter: number; +} + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +export class SignatureInformation { + /** + * The label of this signature. Will be shown in + * the UI. + */ + label: string; + + /** + * The parameters of this signature. + */ + parameters: ParameterInformation[]; + + /** + * The index of the active parameter. + * + * If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}. + */ + activeParameter?: number; +} + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +export class ParameterInformation { + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * {@link SignatureInformation.label signature label}. *Note*: A label of type string must be + * a substring of its containing signature information's {@link SignatureInformation.label label}. + */ + label: string | [number, number]; +} + /** * Represents the configuration for a quick action in the Code Lens. * Quick actions are custom commands that can be added to function and class declarations. @@ -1478,6 +1543,12 @@ export interface ExperimentalConfig { * instead of embeddings, FTS, recently edited files, etc. */ codebaseToolCallingOnly?: boolean; + + /** + * If enabled, static contextualization will be used to + * gather context for the model where necessary. + */ + enableStaticContextualization?: boolean; } export interface AnalyticsConfig { diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ba4cf4f88..c67b8c94a 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -10,6 +10,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../"; @@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { getFileStats: [{ files: string[] }, FileStatsMap]; gotoDefinition: [{ location: Location }, RangeInFile[]]; + gotoTypeDefinition: [{ location: Location }, RangeInFile[]]; + getSignatureHelp: [{ location: Location }, SignatureHelp | null]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 30d9b8177..2365117c0 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -13,6 +13,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../.."; @@ -45,6 +46,14 @@ export class MessageIde implements IDE { return this.request("gotoDefinition", { location }); } + async gotoTypeDefinition(location: Location): Promise { + return this.request("gotoTypeDefinition", { location }); + } + + async getSignatureHelp(location: Location): Promise { + return this.request("getSignatureHelp", { location }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 1926f578d..72c66740f 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -13,6 +13,7 @@ import { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, ToastType, @@ -44,6 +45,14 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + gotoTypeDefinition(location: Location): Promise { + return Promise.resolve([]); + } + + getSignatureHelp(location: Location): Promise { + return Promise.resolve(null); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index cadbe9a47..147c3979a 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { experimental_includeRecentlyVisitedRanges: true, experimental_includeRecentlyEditedRanges: true, experimental_includeDiff: true, + experimental_enableStaticContextualization: false, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index d6980afb8..1639e38fd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -594,6 +594,14 @@ class IntelliJIDE( throw NotImplementedError("gotoDefinition not implemented yet") } + override suspend fun gotoTypeDefinition(location: Location): List { + throw NotImplementedError("gotoTypeDefinition not implemented yet") + } + + override suspend fun getSignatureHelp(location: Location): SignatureHelp? { + throw NotImplementedError("getSignatureHelp not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index b7680fceb..7cb10be71 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -64,6 +64,68 @@ data class RangeInFileWithContents( val contents: String ) +/** + * Signature help represents the signature of something + * callable. There can be multiple signatures but only one + * active and only one active parameter. + */ +data class SignatureHelp( + /** + * One or more signatures. + */ + val signatures: List, + + /** + * The active signature. + */ + val activeSignature: Int, + + /** + * The active parameter of the active signature. + */ + val activeParameter: Int +) + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +data class SignatureInformation( + /** + * The label of this signature. Will be shown in + * the UI. + */ + val label: String, + + /** + * The parameters of this signature. + */ + val parameters: List, + + /** + * The index of the active parameter. + * + * If provided, this is used in place of [SignatureHelp.activeParameter]. + */ + val activeParameter: Int? = null +) + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +data class ParameterInformation( + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * [SignatureInformation.label] signature label. *Note*: A label of type string must be + * a substring of its containing signature information's [SignatureInformation.label] label. + */ + val label: String // Note: Kotlin doesn't have union types, so this represents the string case +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -192,6 +254,8 @@ interface IDE { // LSP suspend fun gotoDefinition(location: Location): List + suspend fun gotoTypeDefinition(location: Location): List + suspend fun getSignatureHelp(location: Location): SignatureHelp? // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index f620cd457..a8ce254ad 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -6,7 +6,10 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; +import { + executeGotoProvider, + executeSignatureHelpProvider, +} from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; import { VsCodeIdeUtils } from "./util/ideUtils"; @@ -24,6 +27,7 @@ import type { Location, Problem, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "core"; @@ -87,6 +91,28 @@ class VsCodeIde implements IDE { return result; } + async gotoTypeDefinition(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeTypeDefinitionProvider", + }); + + return result; + } + + async getSignatureHelp(location: Location): Promise { + const result = await executeSignatureHelpProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeSignatureHelpProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index a6900291a..c3d5c11a4 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; +import type { + IDE, + Range, + RangeInFile, + RangeInFileWithContents, + SignatureHelp, +} from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -23,6 +29,8 @@ type GotoProviderName = | "vscode.executeImplementationProvider" | "vscode.executeReferenceProvider"; +type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider"; + interface GotoInput { uri: vscode.Uri; line: number; @@ -33,8 +41,19 @@ function gotoInputKey(input: GotoInput) { return `${input.name}${input.uri.toString()}${input.line}${input.character}`; } +interface SignatureHelpInput { + uri: vscode.Uri; + line: number; + character: number; + name: SignatureHelpProviderName; +} +function signatureHelpKey(input: SignatureHelpInput) { + return `${input.name}${input.uri.toString()}${input.line}${input.character}`; +} + const MAX_CACHE_SIZE = 500; const gotoCache = new Map(); +const signatureHelpCache = new Map(); export async function executeGotoProvider( input: GotoInput, @@ -382,3 +401,36 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( return []; } }; + +export async function executeSignatureHelpProvider( + input: SignatureHelpInput, +): Promise { + const cacheKey = signatureHelpKey(input); + const cached = signatureHelpCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const definitions = (await vscode.commands.executeCommand( + input.name, + input.uri, + new vscode.Position(input.line, input.character), + )) as SignatureHelp; + + // Add to cache + if (signatureHelpCache.size >= MAX_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = signatureHelpCache.keys().next().value; + if (oldestKey) { + signatureHelpCache.delete(oldestKey); + } + } + signatureHelpCache.set(cacheKey, definitions); + + return definitions; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return null; + } +} diff --git a/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm new file mode 100644 index 000000000..02de34466 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm @@ -0,0 +1,59 @@ +;; Capture the variable/function name +(variable_declarator + name: (identifier) @function.name + type: (type_annotation + (function_type) @function.type)) + +;; Capture the full parameter list +(function_type + parameters: (formal_parameters) @function.params) + +;; Capture the type identifiers used in the parameters +(formal_parameters + (required_parameter + type: (type_annotation + (type_identifier) @param.type)) + (required_parameter + type: (type_annotation + (type_identifier) @param.type))) + +;; Capture the return type of the function +(function_type + return_type: (type_identifier) @return.type) + +;; Capture any parse errors (e.g., the `@`) +(ERROR) @error.node + +;; Capture the entire function declaration line +(lexical_declaration) @function.decl + +;; Matches import declarations like: import { A, B } from "module"; +(import_statement + (import_clause + (named_imports + (import_specifier + name: (identifier) @import.name))) + source: (string) @import.source) + +;; Capture standalone function declarations +(function_declaration + name: (identifier) @function.name) @function.decl + +;; Capture the function signature including parameters and return type +(function_declaration + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) + +;; For function expressions or arrow functions +(function_type + parameters: (formal_parameters) @function.params) @function.decl + +;; For arrow functions +(arrow_function + parameters: (formal_parameters) @function.params) @function.decl + +;; For function signatures without a body (like in your example) +(function_signature + name: (identifier) @function.name + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) @function.decl diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm new file mode 100644 index 000000000..02b0bda77 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm @@ -0,0 +1,22 @@ +;; Match top-level `var`, `let`, or `const` declarations +(lexical_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +(variable_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +;; Match function declarations +(function_declaration + name: (identifier) @top.fn.name + parameters: (formal_parameters + (required_parameter + pattern: (identifier) @top.fn.param.name + type: (type_annotation (_) @top.fn.param.type)))* + + return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm new file mode 100644 index 000000000..b5051cb77 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm @@ -0,0 +1,10 @@ +;; Capture the type alias name (left-hand side) +; (type_alias_declaration +; name: (type_identifier) @type.name) + +;; Capture all identifiers on the right-hand side (value), recursively +; (type_alias_declaration +; value: (_) @type.value) + +;; Match all identifiers inside the type value — deeply nested +(type_identifier) @type.identifier diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm new file mode 100644 index 000000000..b26180e05 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm @@ -0,0 +1,11 @@ +(type_alias_declaration + name: (type_identifier) @type.identifier + value: (_) @type.value) + +(interface_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) + +(enum_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) diff --git a/gui/src/pages/config/ContinueFeaturesMenu.tsx b/gui/src/pages/config/ContinueFeaturesMenu.tsx index 3f08499dd..5d8d05687 100644 --- a/gui/src/pages/config/ContinueFeaturesMenu.tsx +++ b/gui/src/pages/config/ContinueFeaturesMenu.tsx @@ -2,11 +2,15 @@ import ToggleSwitch from "../../components/gui/Switch"; interface ContinueFeaturesMenuProps { optInNextEditFeature: boolean; handleOptInNextEditToggle: (value: boolean) => void; + enableStaticContextualization: boolean; + handleEnableStaticContextualizationToggle: (value: boolean) => void; } export function ContinueFeaturesMenu({ optInNextEditFeature, handleOptInNextEditToggle, + enableStaticContextualization, + handleEnableStaticContextualizationToggle, }: ContinueFeaturesMenuProps) { return (
@@ -19,6 +23,16 @@ export function ContinueFeaturesMenu({ onToggle={() => handleOptInNextEditToggle(!optInNextEditFeature)} text="Enable Next Edit Over Autocomplete" /> + + + handleEnableStaticContextualizationToggle( + !enableStaticContextualization, + ) + } + text="Use Static Contextualization" + />
); diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 9eea8003b..d507ef133 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -71,6 +71,10 @@ export function UserSettingsForm() { handleUpdate({ optInNextEditFeature: value }); }; + const handleEnableStaticContextualizationToggle = (value: boolean) => { + handleUpdate({ enableStaticContextualization: value }); + }; + useEffect(() => { // Necessary so that reformatted/trimmed values don't cause dirty state setFormPromptPath(promptPath); @@ -92,6 +96,8 @@ export function UserSettingsForm() { config.experimental?.optInNextEditFeature ?? false; const codebaseToolCallingOnly = config.experimental?.codebaseToolCallingOnly ?? false; + const enableStaticContextualization = + config.experimental?.enableStaticContextualization ?? false; const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; const disableIndexing = config.disableIndexing ?? false; @@ -433,6 +439,12 @@ export function UserSettingsForm() { )} diff --git a/packages/config-yaml/src/schemas/data/autocomplete/index.ts b/packages/config-yaml/src/schemas/data/autocomplete/index.ts index 458473c3b..db2186e0f 100644 --- a/packages/config-yaml/src/schemas/data/autocomplete/index.ts +++ b/packages/config-yaml/src/schemas/data/autocomplete/index.ts @@ -36,6 +36,9 @@ export const autocompleteEventAllSchema = baseDevDataAllSchema.extend({ uniqueId: z.string(), timestamp: z.string(), + // For static contextualization. + enabledStaticContextualization: z.boolean().optional(), + // DEPRECATED - no more nested objects after v0.1.0, all flat values completionOptions: completionOptionsSchema.optional(), disableInFiles: z.array(z.string()).optional(), diff --git a/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts b/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts index 5866b9865..123a05b75 100644 --- a/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts @@ -38,6 +38,9 @@ export const autocompleteEventSchema_0_2_0 = autocompleteEventAllSchema.pick({ completionId: true, uniqueId: true, + // For static contextualization. + enabledStaticContextualization: true, + // Note objects (completionOptions and disableInfiles) removed from 0.1.0 => 0.2.0 });