Elffuss BraidHub

kikocis/continue public

Merge pull request #6581 from continuedev/jacob/feature/static

feat: Test static contextualization
Changeset81b34840d2fe3ddaa5a2313aceff58b598c1d6b803d8bf10f3b06ec4a2aeef73
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-07-21 21:53 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-21 21:53 -07:00
Parents7cf5e158954e, d08440b043ec

Browse the files at this changeset

29 files changed

modified core/autocomplete/CompletionProvider.ts +12 −2
@@ -10,7 +10,7 @@
1010 import { CompletionStreamer } from "./generation/CompletionStreamer.js";
1111 import { postprocessCompletion } from "./postprocessing/index.js";
1212 import { shouldPrefilter } from "./prefiltering/index.js";
13-import { getAllSnippets } from "./snippets/index.js";
13+import { getAllSnippetsWithoutRace } from "./snippets/index.js";
1414 import { renderPrompt } from "./templating/index.js";
1515 import { GetLspDefinitionsFunction } from "./types.js";
1616 import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
@@ -121,6 +121,12 @@
121121 ...config?.tabAutocompleteOptions,
122122 ...llm.autocompleteOptions,
123123 };
124+
125+ // Enable static contextualization if defined.
126+ if (config?.experimental?.enableStaticContextualization) {
127+ options.experimental_enableStaticContextualization = true;
128+ }
129+
124130 return options;
125131 }
126132
@@ -171,7 +177,7 @@
171177 }
172178
173179 const [snippetPayload, workspaceDirs] = await Promise.all([
174- getAllSnippets({
180+ getAllSnippetsWithoutRace({
175181 helper,
176182 ide: this.ide,
177183 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@@ -258,6 +264,10 @@
258264 ...helper.options,
259265 };
260266
267+ if (options.experimental_enableStaticContextualization) {
268+ outcome.enabledStaticContextualization = true;
269+ }
270+
261271 //////////
262272
263273 // Save to cache
modified core/autocomplete/context/ContextRetrievalService.ts +10 −0
@@ -2,16 +2,19 @@
22 import {
33 AutocompleteCodeSnippet,
44 AutocompleteSnippetType,
5+ AutocompleteStaticSnippet,
56 } from "../snippets/types";
67 import { HelperVars } from "../util/HelperVars";
78
89 import { ImportDefinitionsService } from "./ImportDefinitionsService";
910 import { getSymbolsForSnippet } from "./ranking";
1011 import { RootPathContextService } from "./root-path-context/RootPathContextService";
12+import { StaticContextService } from "./static-context/StaticContextService";
1113
1214 export class ContextRetrievalService {
1315 private importDefinitionsService: ImportDefinitionsService;
1416 private rootPathContextService: RootPathContextService;
17+ private staticContextService: StaticContextService;
1518
1619 constructor(private readonly ide: IDE) {
1720 this.importDefinitionsService = new ImportDefinitionsService(this.ide);
@@ -19,6 +22,7 @@
1922 this.importDefinitionsService,
2023 this.ide,
2124 );
25+ this.staticContextService = new StaticContextService(this.ide);
2226 }
2327
2428 public async getSnippetsFromImportDefinitions(
@@ -71,6 +75,12 @@
7175 );
7276 }
7377
78+ public async getStaticContextSnippets(
79+ helper: HelperVars,
80+ ): Promise<AutocompleteStaticSnippet[]> {
81+ return this.staticContextService.getContext(helper);
82+ }
83+
7484 /**
7585 * Initialize the import definitions cache for a file.
7686 * This is normally done automatically when the active text editor changes,
added core/autocomplete/context/static-context/StaticContextService.ts +888 −0
@@ -0,0 +1,888 @@
1+import * as fs from "fs/promises";
2+import path from "path";
3+import { pathToFileURL } from "url";
4+import Parser from "web-tree-sitter";
5+import { IDE, Position } from "../../..";
6+import { localPathOrUriToPath } from "../../../util/pathToUri";
7+import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
8+import {
9+ AutocompleteSnippetType,
10+ AutocompleteStaticSnippet,
11+} from "../../snippets/types";
12+import { getAst } from "../../util/ast";
13+import { HelperVars } from "../../util/HelperVars";
14+import {
15+ extractFunctionTypeFromDecl,
16+ extractTopLevelDecls,
17+ findEnclosingTypeDeclaration,
18+ unwrapToBaseType,
19+} from "./tree-sitter-utils";
20+import {
21+ HoleContext,
22+ RelevantHeaders,
23+ RelevantTypes,
24+ StaticContext,
25+ TypeSpanAndSourceFile,
26+ TypeSpanAndSourceFileAndAst,
27+} from "./types";
28+
29+export class StaticContextService {
30+ private readonly ide: IDE;
31+
32+ constructor(ide: IDE) {
33+ this.ide = ide;
34+ }
35+
36+ public logAutocompleteStaticSnippet(
37+ ctx: StaticContext,
38+ label = "Static Snippet",
39+ ) {
40+ console.log(`=== ${label} ===`);
41+ console.log("Hole Type:", ctx.holeType);
42+
43+ console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
44+ ctx.relevantTypes.forEach((types, filepath) => {
45+ console.log(` 📁 ${filepath}`);
46+ types.forEach((type) => console.log(` • ${type}`));
47+ });
48+
49+ console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
50+ ctx.relevantHeaders.forEach((headers, filepath) => {
51+ console.log(` 📁 ${filepath}`);
52+ headers.forEach((header) => console.log(` • ${header}`));
53+ });
54+ }
55+
56+ public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
57+ let output = `AutocompleteStaticSnippet:\n`;
58+ output += ` holeType: ${ctx.holeType}\n`;
59+
60+ output += ` relevantTypes:\n`;
61+ if (ctx.relevantTypes.size === 0) {
62+ output += ` (none)\n`;
63+ } else {
64+ ctx.relevantTypes.forEach((types, filepath) => {
65+ output += ` ${filepath}: [${types.join(", ")}]\n`;
66+ });
67+ }
68+
69+ output += ` relevantHeaders:\n`;
70+ if (ctx.relevantHeaders.size === 0) {
71+ output += ` (none)\n`;
72+ } else {
73+ ctx.relevantHeaders.forEach((headers, filepath) => {
74+ output += ` ${filepath}: [${headers.join(", ")}]\n`;
75+ });
76+ }
77+
78+ return output;
79+ }
80+
81+ public async getContext(
82+ helper: HelperVars,
83+ ): Promise<AutocompleteStaticSnippet[]> {
84+ const start = Date.now();
85+ const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
86+ helper.workspaceUris,
87+ );
88+ // Get the three contexts holeContext, relevantTypes, relevantHeaders.
89+ const holeContext = await this.getHoleContext(
90+ helper.fileContents,
91+ helper.filepath,
92+ helper.pos,
93+ );
94+
95+ const relevantTypes = await this.extractRelevantTypes(
96+ holeContext.fullHoverResult,
97+ holeContext.functionName,
98+ holeContext.range.start.line,
99+ holeContext.source,
100+ new Map<string, string>(),
101+ );
102+
103+ // if (this.language === "typescript") {
104+ // repo = getAllTSFiles(this.repoPath);
105+ // } else if (this.language === "ocaml") {
106+ // repo = getAllOCamlFiles(this.repoPath);
107+ // }
108+ //
109+
110+ const relevantHeaders = await this.extractRelevantHeaders(
111+ tsFiles,
112+ relevantTypes,
113+ holeContext.functionTypeSpan,
114+ helper.pos,
115+ holeContext.returnTypeIsAny,
116+ );
117+
118+ const relevantTypesToReturn: Map<string, string[]> = new Map<
119+ string,
120+ string[]
121+ >();
122+ relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
123+ if (relevantTypesToReturn.has(src)) {
124+ const updated = relevantTypesToReturn.get(src)!;
125+ updated.push(v);
126+ relevantTypesToReturn.set(src, updated);
127+ } else {
128+ relevantTypesToReturn.set(src, [v]);
129+ }
130+ });
131+
132+ const relevantHeadersToReturn: Map<string, string[]> = new Map<
133+ string,
134+ string[]
135+ >();
136+ relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
137+ if (relevantHeadersToReturn.has(src)) {
138+ const updated = relevantHeadersToReturn.get(src)!;
139+ if (!updated.includes(v)) {
140+ updated.push(v);
141+ }
142+ relevantHeadersToReturn.set(src, updated);
143+ } else {
144+ relevantHeadersToReturn.set(src, [v]);
145+ }
146+ });
147+
148+ const ctx = {
149+ holeType: holeContext.functionTypeSpan,
150+ relevantTypes: relevantTypesToReturn,
151+ relevantHeaders: relevantHeadersToReturn,
152+ };
153+ const end = Date.now();
154+
155+ this.logAutocompleteStaticSnippet(ctx);
156+
157+ // console.log(end - start);
158+
159+ const snippets: AutocompleteStaticSnippet[] = [];
160+
161+ snippets.push({
162+ type: AutocompleteSnippetType.Static,
163+ filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
164+ content: holeContext.fullHoverResult,
165+ });
166+
167+ for (const [filepath, typs] of ctx.relevantTypes.entries()) {
168+ snippets.push({
169+ type: AutocompleteSnippetType.Static,
170+ filepath: pathToFileURL(path.resolve(filepath)).toString(),
171+ content: typs.join("\n"),
172+ });
173+ }
174+
175+ for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
176+ snippets.push({
177+ type: AutocompleteSnippetType.Static,
178+ filepath: pathToFileURL(path.resolve(filepath)).toString(),
179+ content: headers.join("\n"),
180+ });
181+ }
182+
183+ return snippets;
184+ }
185+
186+ private async getHoleContext(
187+ sketchFileContent: string,
188+ sketchFilePath: string,
189+ cursorPosition: Position,
190+ ): Promise<HoleContext> {
191+ // We need to inject the hole @ to trigger a treesitter error node.
192+ sketchFilePath = localPathOrUriToPath(sketchFilePath);
193+ // const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
194+ const injectedContent = this.insertAtPosition(
195+ sketchFileContent,
196+ cursorPosition,
197+ "@;",
198+ );
199+
200+ // The hole's position is cursorPosition.
201+
202+ // Use treesitter to parse.
203+ const ast = await getAst(sketchFilePath, injectedContent);
204+ if (!ast) {
205+ throw new Error("failed to get ast");
206+ }
207+ const language = getFullLanguageName(sketchFilePath);
208+ const query = await getQueryForFile(
209+ sketchFilePath,
210+ `static-context-queries/hole-queries/${language}.scm`,
211+ );
212+ if (!query) {
213+ throw new Error(
214+ `getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
215+ );
216+ }
217+
218+ const captures = query.captures(ast.rootNode);
219+ const res: HoleContext = {
220+ fullHoverResult: "",
221+ functionName: "",
222+ functionTypeSpan: "",
223+ returnTypeIsAny: false,
224+ range: {
225+ start: { line: 0, character: 0 },
226+ end: { line: 0, character: 0 },
227+ },
228+ source: `file://${sketchFilePath}`,
229+ };
230+ let paramsTypes = "";
231+ for (const c of captures) {
232+ const { name, node } = c;
233+ // console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
234+
235+ switch (name) {
236+ case "function.decl": {
237+ res.fullHoverResult = node.text;
238+ break;
239+ }
240+ case "function.name": {
241+ res.functionName = node.text;
242+ break;
243+ }
244+ case "function.params": {
245+ paramsTypes = node.text;
246+ res.range = {
247+ start: {
248+ line: node.startPosition.row,
249+ character: node.startPosition.column,
250+ },
251+ end: {
252+ line: node.endPosition.row,
253+ character: node.endPosition.column,
254+ },
255+ };
256+ break;
257+ }
258+ case "function.type": {
259+ res.functionTypeSpan = node.text;
260+ res.range = {
261+ start: {
262+ line: node.startPosition.row,
263+ character: node.startPosition.column,
264+ },
265+ end: {
266+ line: node.endPosition.row,
267+ character: node.endPosition.column,
268+ },
269+ };
270+ break;
271+ }
272+ }
273+ }
274+
275+ if (res.functionTypeSpan === "") {
276+ res.functionTypeSpan = `${paramsTypes} => any`;
277+ res.returnTypeIsAny = true;
278+ }
279+
280+ return res;
281+ }
282+
283+ private async extractRelevantTypes(
284+ declText: string,
285+ typeName: string,
286+ startLine: number,
287+ currentFile: string,
288+ foundContents: Map<string, string>, // uri -> contents
289+ ): Promise<RelevantTypes> {
290+ const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
291+
292+ await this.extractRelevantTypesHelper(
293+ declText,
294+ typeName,
295+ startLine,
296+ foundSoFar,
297+ currentFile,
298+ foundContents,
299+ );
300+
301+ return foundSoFar;
302+ }
303+
304+ private async extractRelevantTypesHelper(
305+ declText: string,
306+ typeName: string,
307+ startLine: number,
308+ foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
309+ currentFile: string,
310+ foundContents: Map<string, string>, // uri -> contents
311+ ) {
312+ if (!foundSoFar.has(typeName)) {
313+ const ast = await getAst(currentFile, declText);
314+ if (!ast) {
315+ throw new Error(`failed to get ast for file ${currentFile}`);
316+ }
317+ foundSoFar.set(typeName, {
318+ typeSpan: declText,
319+ sourceFile: currentFile.slice(7),
320+ ast: ast,
321+ });
322+
323+ const language = getFullLanguageName(currentFile);
324+ const query = await getQueryForFile(
325+ currentFile,
326+ `static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
327+ );
328+ if (!query) {
329+ throw new Error(
330+ `failed to get query for file ${currentFile} and language ${language}`,
331+ );
332+ }
333+
334+ const identifiers = query.captures(ast.rootNode);
335+
336+ for (const { name, node } of identifiers) {
337+ if (foundSoFar.has(node.text)) continue;
338+
339+ try {
340+ const typeDefinitionResult = await this.ide.gotoTypeDefinition({
341+ filepath: currentFile,
342+ position: {
343+ character: node.startPosition.column,
344+ line: startLine + node.startPosition.row,
345+ },
346+ });
347+
348+ if (typeDefinitionResult.length > 0) {
349+ const tdLocation = typeDefinitionResult[0];
350+
351+ let content = "";
352+
353+ if (foundContents.has(tdLocation.filepath)) {
354+ content = foundContents.get(tdLocation.filepath)!;
355+ } else {
356+ content = await fs.readFile(
357+ localPathOrUriToPath(tdLocation.filepath),
358+ "utf8",
359+ );
360+ foundContents.set(tdLocation.filepath, content);
361+ }
362+
363+ const ast = await getAst(tdLocation.filepath, content);
364+ if (!ast) {
365+ throw new Error(
366+ `failed to get ast for file ${tdLocation.filepath}`,
367+ );
368+ }
369+ const decl = findEnclosingTypeDeclaration(
370+ content,
371+ tdLocation.range.start.line,
372+ tdLocation.range.start.character,
373+ ast,
374+ );
375+ if (!decl) {
376+ // throw new Error(`failed to get decl for file ${tdLocation.uri}`);
377+ console.error(
378+ `failed to get decl for file ${tdLocation.filepath}`,
379+ );
380+ }
381+
382+ if (decl) {
383+ await this.extractRelevantTypesHelper(
384+ decl.fullText,
385+ node.text,
386+ tdLocation.range.start.line,
387+ foundSoFar,
388+ tdLocation.filepath,
389+ foundContents,
390+ );
391+ } else {
392+ // console.log("decl not found");
393+ }
394+ } else {
395+ // console.log("td not found");
396+ }
397+ } catch (err) {
398+ console.log(err);
399+ }
400+ }
401+ }
402+ }
403+
404+ private async extractRelevantHeaders(
405+ sources: string[],
406+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
407+ holeType: string,
408+ cursorPosition: Position,
409+ returnTypeIsAny: boolean,
410+ ): Promise<RelevantHeaders> {
411+ const relevantContext = new Set<TypeSpanAndSourceFile>();
412+ if (returnTypeIsAny) return relevantContext;
413+ // NOTE: This is necessary because TypeScript sucks.
414+ // There is no way to compare objects by value,
415+ // so sets of objects starts to accumulate tons of duplicates.
416+ const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
417+ const foundNormalForms = new Map<string, string>();
418+
419+ const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
420+
421+ for (const source of sources) {
422+ const topLevelDecls = await extractTopLevelDecls(source);
423+ for (const tld of topLevelDecls) {
424+ // pattern 0 is let/const, 1 is var, 2 is fun
425+ // if (!seenDecls.has(JSON.stringify()) {
426+ const originalDeclText =
427+ tld.pattern === 2
428+ ? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
429+ : tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
430+
431+ if (tld.pattern === 2) {
432+ // build a type span
433+ // TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
434+ // most likely due to my scm query and how I'm not attaching param name along with param type
435+ let funcType = "";
436+ try {
437+ funcType = extractFunctionTypeFromDecl(tld);
438+ } catch (err) {
439+ // Most likely is the case that there is no explicit return type annotation.
440+ const sigHelp = await this.ide.getSignatureHelp({
441+ filepath: source,
442+ position: cursorPosition,
443+ });
444+ if (!sigHelp) continue;
445+ funcType = sigHelp.signatures[0].label;
446+
447+ // TODO: This only works for TypeScript.
448+ function convertToArrowType(signature: string): string {
449+ // Handle various function declaration formats.
450+ const patterns = [
451+ // Standard: functionName(params): returnType.
452+ /^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
453+ // With generics: functionName<T>(params): returnType.
454+ /^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
455+ // With modifiers: export function functionName(params): returnType.
456+ /^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
457+ ];
458+
459+ for (const pattern of patterns) {
460+ const match = signature.match(pattern);
461+ if (match) {
462+ const [, , parameters, returnType] = match;
463+ return `(${parameters}) => ${returnType}`;
464+ }
465+ }
466+
467+ return signature;
468+ }
469+
470+ funcType = convertToArrowType(funcType);
471+ }
472+ const wrapped = `type __TMP = ${funcType};`;
473+
474+ const ast = await getAst("file.ts", wrapped);
475+ if (!ast) {
476+ throw new Error(`failed to generate ast for ${wrapped}`);
477+ }
478+
479+ // console.log(ast.rootNode);
480+ const alias = ast.rootNode.namedChild(0);
481+ // console.log(alias);
482+ if (!alias || alias.type !== "type_alias_declaration") {
483+ throw new Error(
484+ "extractRelevantHeaders: Failed to parse type alias",
485+ );
486+ }
487+
488+ const valueNode = alias.childForFieldName("value");
489+ if (!valueNode) throw new Error("No type value found");
490+
491+ const baseNode = unwrapToBaseType(valueNode);
492+
493+ await this.extractRelevantHeadersHelper(
494+ originalDeclText,
495+ baseNode,
496+ targetTypes,
497+ relevantTypes,
498+ relevantContext,
499+ relevantContextMap,
500+ foundNormalForms,
501+ source,
502+ );
503+ } else {
504+ const varTypNode = tld.captures.find(
505+ (d) => d.name === "top.var.type",
506+ )!.node;
507+ await this.extractRelevantHeadersHelper(
508+ originalDeclText,
509+ varTypNode,
510+ targetTypes,
511+ relevantTypes,
512+ relevantContext,
513+ relevantContextMap,
514+ foundNormalForms,
515+ source,
516+ );
517+ }
518+ }
519+ }
520+
521+ for (const v of relevantContextMap.values()) {
522+ relevantContext.add(v);
523+ }
524+
525+ return relevantContext;
526+ }
527+
528+ private async extractRelevantHeadersHelper(
529+ originalDeclText: string,
530+ node: Parser.SyntaxNode,
531+ targetTypes: Set<Parser.SyntaxNode>,
532+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
533+ relevantContext: Set<TypeSpanAndSourceFile>,
534+ relevantContextMap: Map<string, TypeSpanAndSourceFile>,
535+ foundNormalForms: Map<string, string>,
536+ source: string,
537+ ) {
538+ for (const typ of targetTypes) {
539+ if (
540+ await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
541+ ) {
542+ const ctx = { typeSpan: originalDeclText, sourceFile: source };
543+ relevantContextMap.set(JSON.stringify(ctx), ctx);
544+ }
545+
546+ if (node.type === "function_type") {
547+ const retTypeNode = node.namedChildren.find(
548+ (c) => c && c.type === "return_type",
549+ );
550+ if (retTypeNode) {
551+ await this.extractRelevantHeadersHelper(
552+ originalDeclText,
553+ retTypeNode,
554+ targetTypes,
555+ relevantTypes,
556+ relevantContext,
557+ relevantContextMap,
558+ foundNormalForms,
559+ source,
560+ );
561+ }
562+ } else if (node.type === "tuple_type") {
563+ for (const c of node.namedChildren) {
564+ await this.extractRelevantHeadersHelper(
565+ originalDeclText,
566+ c!,
567+ targetTypes,
568+ relevantTypes,
569+ relevantContext,
570+ relevantContextMap,
571+ foundNormalForms,
572+ source,
573+ );
574+ }
575+ }
576+ }
577+ }
578+
579+ private async generateTargetTypes(
580+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
581+ holeType: string,
582+ ) {
583+ const targetTypes = new Set<Parser.SyntaxNode>();
584+ // const ast = relevantTypes.get(holeIdentifier)!.ast;
585+ const ast = await getAst("file.ts", `type T = ${holeType};`);
586+ if (!ast) {
587+ throw new Error(`failed to generate ast for ${holeType}`);
588+ }
589+
590+ const alias = ast.rootNode.namedChild(0);
591+ if (!alias || alias.type !== "type_alias_declaration") {
592+ throw new Error("generateTargetTypes: Failed to parse type alias");
593+ }
594+
595+ const valueNode = alias.childForFieldName("value");
596+ if (!valueNode) throw new Error("No type value found");
597+
598+ const baseNode = unwrapToBaseType(valueNode);
599+ targetTypes.add(baseNode);
600+ await this.generateTargetTypesHelper(
601+ relevantTypes,
602+ holeType,
603+ targetTypes,
604+ baseNode,
605+ );
606+
607+ return targetTypes;
608+ }
609+
610+ private async generateTargetTypesHelper(
611+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
612+ currType: string,
613+ targetTypes: Set<Parser.SyntaxNode>,
614+ node: Parser.SyntaxNode | null,
615+ ): Promise<void> {
616+ if (!node) return;
617+
618+ if (node.type === "function_type") {
619+ const returnType = node.childForFieldName("return_type");
620+ if (returnType) {
621+ targetTypes.add(returnType);
622+ await this.generateTargetTypesHelper(
623+ relevantTypes,
624+ currType,
625+ targetTypes,
626+ returnType,
627+ );
628+ }
629+ }
630+
631+ if (node.type === "tuple_type") {
632+ for (const child of node.namedChildren) {
633+ if (child) {
634+ targetTypes.add(child);
635+ await this.generateTargetTypesHelper(
636+ relevantTypes,
637+ currType,
638+ targetTypes,
639+ child,
640+ );
641+ }
642+ }
643+ }
644+
645+ if (relevantTypes.has(node.text)) {
646+ // const ast = relevantTypes.get(node.text)!.ast;
647+ const typeSpan = relevantTypes.get(node.text)?.typeSpan;
648+
649+ // const ast = await getAst("file.ts", `type T = ${typeSpan}`);
650+ const ast = await getAst("file.ts", typeSpan!);
651+ if (!ast) {
652+ throw new Error(`failed to generate ast for ${typeSpan}`);
653+ }
654+
655+ const alias = ast.rootNode.namedChild(0);
656+ if (!alias || alias.type !== "type_alias_declaration") {
657+ console.error("generateTargetTypesHelper: Failed to parse type alias");
658+ return;
659+ // throw new Error(
660+ // "generateTargetTypesHelper: Failed to parse type alias",
661+ // );
662+ }
663+
664+ const valueNode = alias.childForFieldName("value");
665+ if (!valueNode) throw new Error("No type value found");
666+
667+ const baseNode = unwrapToBaseType(valueNode);
668+ await this.generateTargetTypesHelper(
669+ relevantTypes,
670+ currType,
671+ targetTypes,
672+ baseNode,
673+ );
674+ }
675+
676+ // if (node.type === "type_identifier" || node.type === "predefined_type") {
677+ // return [node.text];
678+ // }
679+
680+ return;
681+ }
682+
683+ private async isTypeEquivalent(
684+ node: Parser.SyntaxNode,
685+ typ: Parser.SyntaxNode,
686+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
687+ foundNormalForms: Map<string, string>,
688+ ): Promise<boolean> {
689+ if (!node || !typ) {
690+ return false;
691+ }
692+ let normT1 = "";
693+ let normT2 = "";
694+ if (foundNormalForms.has(node.text)) {
695+ // console.log("found t1", true)
696+ normT1 = foundNormalForms.get(node.text)!;
697+ } else {
698+ // console.log("not found t1", false)
699+ normT1 = await this.normalize(node, relevantTypes);
700+ foundNormalForms.set(node.text, normT1);
701+ }
702+ if (foundNormalForms.has(typ.text)) {
703+ // console.log("found t2", true)
704+ normT2 = foundNormalForms.get(typ.text)!;
705+ } else {
706+ // console.log("not found t2", false)
707+ normT2 = await this.normalize(typ, relevantTypes);
708+ foundNormalForms.set(typ.text, normT2);
709+ }
710+ // const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
711+ // const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
712+ // console.log(`normal forms: ${normT1} {}{} ${normT2}`)
713+ return normT1 === normT2;
714+ }
715+
716+ private async normalize(
717+ node: Parser.SyntaxNode,
718+ relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
719+ ): Promise<string> {
720+ if (!node) return "";
721+
722+ switch (node.type) {
723+ case "function_type": {
724+ const params = node.child(0); // formal_parameters
725+ const returnType =
726+ node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
727+
728+ const paramTypes =
729+ params?.namedChildren
730+ .map((param) =>
731+ this.normalize(
732+ param!.childForFieldName("type")! ||
733+ param!.namedChildren.at(-1),
734+ relevantTypes,
735+ ),
736+ )
737+ .join(", ") || "";
738+
739+ const ret = this.normalize(returnType!, relevantTypes);
740+ return `(${paramTypes}) => ${ret}`;
741+ }
742+
743+ case "tuple_type": {
744+ const elements = node.namedChildren.map((c) =>
745+ this.normalize(c!, relevantTypes),
746+ );
747+ return `[${elements.join(", ")}]`;
748+ }
749+
750+ case "union_type": {
751+ const parts = node.namedChildren.map((c) =>
752+ this.normalize(c!, relevantTypes),
753+ );
754+ return parts.join(" | ");
755+ }
756+
757+ case "type_identifier": {
758+ const alias = relevantTypes.get(node.text);
759+ if (!alias) return node.text;
760+
761+ // Parse the alias's type span
762+ const wrapped = `type __TMP = ${alias};`;
763+ const tree = await getAst("file.ts", wrapped);
764+ const valueNode = tree!.rootNode
765+ .descendantsOfType("type_alias_declaration")[0]
766+ ?.childForFieldName("value");
767+
768+ return this.normalize(valueNode!, relevantTypes);
769+ }
770+
771+ case "predefined_type":
772+ case "number":
773+ case "string":
774+ return node.text;
775+
776+ default:
777+ // Fallback for types like array, etc.
778+ return node.text;
779+ }
780+ }
781+
782+ private insertAtPosition = (
783+ contents: string,
784+ cursorPosition: { line: number; character: number },
785+ insertText: string,
786+ ): string => {
787+ const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
788+ const { line, character } = cursorPosition;
789+
790+ if (line < 0 || line >= lines.length) {
791+ throw new Error("Invalid line number");
792+ }
793+
794+ const targetLine = lines[line];
795+ if (character < 0 || character > targetLine.length) {
796+ throw new Error("Invalid character index");
797+ }
798+
799+ // Insert the text
800+ lines[line] =
801+ targetLine.slice(0, character) + insertText + targetLine.slice(character);
802+
803+ return lines.join("\n"); // Reconstruct the file
804+ };
805+
806+ private async getTypeScriptFilesFromWorkspaces(
807+ workspaceUris: string[],
808+ ): Promise<string[]> {
809+ const tsExtensions = [".ts"];
810+ const allTsFiles: string[] = [];
811+
812+ for (const workspaceUri of workspaceUris) {
813+ try {
814+ // Convert URI to file path
815+ const folderPath = workspaceUri.startsWith("file://")
816+ ? new URL(workspaceUri).pathname
817+ : workspaceUri;
818+
819+ const tsFiles = await this.scanDirectoryForTypeScriptFiles(
820+ folderPath,
821+ tsExtensions,
822+ );
823+ allTsFiles.push(...tsFiles);
824+ } catch (error) {
825+ console.error(`Error scanning workspace ${workspaceUri}:`, error);
826+ }
827+ }
828+
829+ return allTsFiles;
830+ }
831+
832+ private async scanDirectoryForTypeScriptFiles(
833+ dirPath: string,
834+ tsExtensions: string[],
835+ ): Promise<string[]> {
836+ const tsFiles: string[] = [];
837+
838+ const shouldSkipDirectory = (dirName: string): boolean => {
839+ const skipDirs = [
840+ "node_modules",
841+ ".git",
842+ ".vscode",
843+ "dist",
844+ "build",
845+ "out",
846+ ".next",
847+ "coverage",
848+ ".nyc_output",
849+ "tmp",
850+ "temp",
851+ ".cache",
852+ ];
853+
854+ return skipDirs.includes(dirName) || dirName.startsWith(".");
855+ };
856+
857+ async function scanRecursively(currentPath: string): Promise<void> {
858+ try {
859+ const entries = await fs.readdir(currentPath, {
860+ withFileTypes: true,
861+ });
862+
863+ for (const entry of entries) {
864+ const fullPath = localPathOrUriToPath(
865+ path.join(currentPath, entry.name),
866+ );
867+
868+ if (entry.isDirectory()) {
869+ // Skip common directories that typically don't contain source files
870+ if (!shouldSkipDirectory(entry.name)) {
871+ await scanRecursively(fullPath);
872+ }
873+ } else if (entry.isFile()) {
874+ const extension = path.extname(entry.name).toLowerCase();
875+ if (tsExtensions.includes(extension)) {
876+ tsFiles.push(fullPath);
877+ }
878+ }
879+ }
880+ } catch (error) {
881+ console.error(`Error reading directory ${currentPath}:`, error);
882+ }
883+ }
884+
885+ await scanRecursively(dirPath);
886+ return tsFiles;
887+ }
888+}
added core/autocomplete/context/static-context/tree-sitter-utils.ts +222 −0
@@ -0,0 +1,222 @@
1+import * as fs from "fs/promises";
2+import Parser from "web-tree-sitter";
3+import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
4+import { getAst } from "../../util/ast";
5+
6+export interface TypeDeclarationResult {
7+ name: string;
8+ fullText: string;
9+ startLine: number;
10+ startColumn: number;
11+ endLine: number;
12+ endColumn: number;
13+ kind: string;
14+}
15+
16+export function findEnclosingTypeDeclaration(
17+ sourceCode: string,
18+ cursorLine: number,
19+ cursorColumn: number,
20+ ast: Parser.Tree,
21+): TypeDeclarationResult | null {
22+ const point = { row: cursorLine, column: cursorColumn };
23+ let node = ast.rootNode.descendantForPosition(point);
24+
25+ while (
26+ node &&
27+ ![
28+ "type_alias_declaration",
29+ "interface_declaration",
30+ "enum_declaration",
31+ ].includes(node.type)
32+ ) {
33+ if (!node.parent) return null;
34+ node = node.parent;
35+ }
36+
37+ if (!node) return null;
38+
39+ const nameNode = node.childForFieldName("name");
40+ const name = nameNode?.text ?? "<anonymous>";
41+ const fullText = sourceCode.slice(node.startIndex, node.endIndex);
42+
43+ return {
44+ name,
45+ fullText,
46+ startLine: node.startPosition.row,
47+ startColumn: node.startPosition.column,
48+ endLine: node.endPosition.row,
49+ endColumn: node.endPosition.column,
50+ kind: node.type,
51+ };
52+}
53+
54+export async function extractTopLevelDecls(
55+ currentFile: string,
56+ givenParser?: Parser,
57+) {
58+ const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
59+ if (!ast) {
60+ throw new Error(`failed to get ast for file ${currentFile}`);
61+ }
62+ let language;
63+ if (givenParser) {
64+ language = givenParser.getLanguage();
65+ } else {
66+ language = getFullLanguageName(currentFile);
67+ }
68+
69+ const query = await getQueryForFile(
70+ currentFile,
71+ `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
72+ );
73+ if (!query) {
74+ throw new Error(
75+ `failed to get query for file ${currentFile} and language ${language}`,
76+ );
77+ }
78+ return query.matches(ast.rootNode);
79+}
80+
81+export async function extractTopLevelDeclsWithFormatting(
82+ currentFile: string,
83+ givenParser?: Parser,
84+) {
85+ const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
86+ if (!ast) {
87+ throw new Error(`failed to get ast for file ${currentFile}`);
88+ }
89+ let language;
90+ if (givenParser) {
91+ language = givenParser.getLanguage();
92+ } else {
93+ language = getFullLanguageName(currentFile);
94+ }
95+
96+ const query = await getQueryForFile(
97+ currentFile,
98+ `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
99+ );
100+ if (!query) {
101+ throw new Error(
102+ `failed to get query for file ${currentFile} and language ${language}`,
103+ );
104+ }
105+ const matches = query.matches(ast.rootNode);
106+
107+ const results = [];
108+
109+ for (const match of matches) {
110+ const item: {
111+ declaration: string;
112+ nodeType: string;
113+ name: string;
114+ declaredType: string;
115+ returnType?: string;
116+ } = {
117+ declaration: "",
118+ nodeType: "",
119+ name: "",
120+ declaredType: "",
121+ };
122+
123+ for (const { name, node } of match.captures) {
124+ if (name === "top.var.decl") {
125+ item.nodeType = "variable";
126+ item.declaration = node.text;
127+
128+ // Attempt to get the declared type (e.g., const x: string = ...)
129+ const typeNode = node.descendantsOfType("type_annotation")[0];
130+ if (typeNode) {
131+ item.declaredType = typeNode.text.replace(/^:\s*/, "");
132+ }
133+ } else if (name === "top.var.name" || name === "top.fn.name") {
134+ item.name = node.text;
135+ } else if (name === "top.fn.decl") {
136+ item.nodeType = "function";
137+ item.declaration = node.text;
138+
139+ // Get the return type (e.g., function foo(): string)
140+ const returnTypeNode = node.childForFieldName("return_type");
141+ if (returnTypeNode) {
142+ item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
143+ }
144+
145+ // Get declaredType if needed (TypeScript style)
146+ const nameNode = node.childForFieldName("name");
147+ if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
148+ item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
149+ }
150+ }
151+ }
152+
153+ if (item.name && item.declaration) {
154+ results.push(item);
155+ }
156+ }
157+
158+ return results;
159+}
160+
161+export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
162+ let paramsNode: Parser.SyntaxNode | undefined = undefined;
163+ let returnNode: Parser.SyntaxNode | undefined = undefined;
164+
165+ for (const capture of match.captures) {
166+ if (capture.name === "top.fn.param.type") {
167+ paramsNode = capture.node;
168+ } else if (capture.name === "top.fn.type") {
169+ returnNode = capture.node;
170+ }
171+ }
172+
173+ if (!paramsNode) {
174+ console.error(
175+ `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
176+ );
177+ throw new Error(
178+ `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
179+ );
180+ }
181+
182+ if (!returnNode) {
183+ console.error(
184+ `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
185+ );
186+ throw new Error(
187+ `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
188+ );
189+ }
190+
191+ return `(${paramsNode!.text}) => ${returnNode!.text}`;
192+}
193+
194+export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
195+ if (
196+ [
197+ "function_type",
198+ "tuple_type",
199+ "type_identifier",
200+ "predefined_type",
201+ ].includes(node.type)
202+ ) {
203+ return node;
204+ }
205+
206+ for (const child of node.namedChildren) {
207+ const unwrapped = unwrapToBaseType(child!);
208+ if (
209+ unwrapped !== child ||
210+ [
211+ "function_type",
212+ "tuple_type",
213+ "type_identifier",
214+ "predefined_type",
215+ ].includes(unwrapped.type)
216+ ) {
217+ return unwrapped;
218+ }
219+ }
220+
221+ return node;
222+}
added core/autocomplete/context/static-context/types.ts +33 −0
@@ -0,0 +1,33 @@
1+import { Tree } from "web-tree-sitter";
2+import { Range } from "../../..";
3+
4+export interface TypeSpanAndSourceFile {
5+ typeSpan: string;
6+ sourceFile: string;
7+}
8+
9+export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
10+ ast: Tree;
11+}
12+
13+export interface HoleContext {
14+ fullHoverResult: string;
15+ functionName: string;
16+ functionTypeSpan: string;
17+ returnTypeIsAny: boolean;
18+ range: Range;
19+ source: string;
20+}
21+
22+export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
23+export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
24+
25+export type Filepath = string;
26+export type RelevantType = string;
27+export type RelevantHeader = string;
28+
29+export interface StaticContext {
30+ holeType: string;
31+ relevantTypes: Map<Filepath, RelevantType[]>;
32+ relevantHeaders: Map<Filepath, RelevantHeader[]>;
33+}
modified core/autocomplete/snippets/getAllSnippets.ts +12 −0
@@ -11,6 +11,7 @@
1111 AutocompleteCodeSnippet,
1212 AutocompleteDiffSnippet,
1313 AutocompleteSnippetType,
14+ AutocompleteStaticSnippet,
1415 } from "./types";
1516
1617 const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
@@ -24,6 +25,7 @@
2425 diffSnippets: AutocompleteDiffSnippet[];
2526 clipboardSnippets: AutocompleteClipboardSnippet[];
2627 recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
28+ staticSnippet: AutocompleteStaticSnippet[];
2729 }
2830
2931 function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@@ -185,6 +187,7 @@
185187 diffSnippets,
186188 clipboardSnippets,
187189 recentlyOpenedFileSnippets,
190+ staticSnippet,
188191 ] = await Promise.all([
189192 racePromise(contextRetrievalService.getRootPathSnippets(helper)),
190193 racePromise(
@@ -196,6 +199,9 @@
196199 [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
197200 racePromise(getClipboardSnippets(ide)),
198201 racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
202+ helper.options.experimental_enableStaticContextualization
203+ ? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
204+ : [],
199205 ]);
200206
201207 return {
@@ -207,6 +213,7 @@
207213 clipboardSnippets,
208214 recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
209215 recentlyOpenedFileSnippets,
216+ staticSnippet,
210217 };
211218 };
212219
@@ -231,6 +238,7 @@
231238 diffSnippets,
232239 clipboardSnippets,
233240 recentlyOpenedFileSnippets,
241+ staticSnippet,
234242 ] = await Promise.all([
235243 contextRetrievalService.getRootPathSnippets(helper),
236244 contextRetrievalService.getSnippetsFromImportDefinitions(helper),
@@ -240,6 +248,9 @@
240248 [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
241249 getClipboardSnippets(ide),
242250 getSnippetsFromRecentlyOpenedFiles(helper, ide),
251+ helper.options.experimental_enableStaticContextualization
252+ ? contextRetrievalService.getStaticContextSnippets(helper)
253+ : [],
243254 ]);
244255
245256 return {
@@ -251,5 +262,6 @@
251262 clipboardSnippets,
252263 recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
253264 recentlyOpenedFileSnippets,
265+ staticSnippet,
254266 };
255267 };
modified core/autocomplete/snippets/types.ts +8 −1
@@ -2,6 +2,7 @@
22 Code = "code",
33 Diff = "diff",
44 Clipboard = "clipboard",
5+ Static = "static",
56 }
67
78 interface BaseAutocompleteSnippet {
@@ -23,7 +24,13 @@
2324 copiedAt: string;
2425 }
2526
27+export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
28+ type: AutocompleteSnippetType.Static;
29+ filepath: string;
30+}
31+
2632 export type AutocompleteSnippet =
2733 | AutocompleteCodeSnippet
2834 | AutocompleteDiffSnippet
29- | AutocompleteClipboardSnippet;
35+ | AutocompleteClipboardSnippet
36+ | AutocompleteStaticSnippet;
modified core/autocomplete/templating/filtering.ts +13 −4
@@ -4,6 +4,7 @@
44 AutocompleteCodeSnippet,
55 AutocompleteSnippet,
66 AutocompleteSnippetType,
7+ AutocompleteStaticSnippet,
78 } from "../snippets/types";
89 import { HelperVars } from "../util/HelperVars";
910 import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
@@ -32,9 +33,9 @@
3233 };
3334
3435 function filterSnippetsAlreadyInCaretWindow(
35- snippets: AutocompleteCodeSnippet[],
36+ snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
3637 caretWindow: string,
37-): AutocompleteCodeSnippet[] {
38+): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
3839 return snippets.filter(
3940 (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
4041 );
@@ -52,7 +53,11 @@
5253 recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
5354 base: shuffleArray(
5455 filterSnippetsAlreadyInCaretWindow(
55- [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
56+ [
57+ ...payload.rootPathSnippets,
58+ ...payload.importDefinitionSnippets,
59+ ...payload.staticSnippet,
60+ ],
5661 helper.prunedCaretWindow,
5762 ),
5863 ),
@@ -107,7 +112,11 @@
107112 defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
108113 snippets: shuffleArray(
109114 filterSnippetsAlreadyInCaretWindow(
110- [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
115+ [
116+ ...payload.rootPathSnippets,
117+ ...payload.importDefinitionSnippets,
118+ ...payload.staticSnippet,
119+ ],
111120 helper.prunedCaretWindow,
112121 ),
113122 ),
modified core/autocomplete/templating/formatting.ts +9 −0
@@ -5,6 +5,7 @@
55 AutocompleteDiffSnippet,
66 AutocompleteSnippet,
77 AutocompleteSnippetType,
8+ AutocompleteStaticSnippet,
89 } from "../snippets/types";
910 import { HelperVars } from "../util/HelperVars";
1011
@@ -51,6 +52,12 @@
5152 return snippet;
5253 };
5354
55+const formatStaticSnippet = (
56+ snippet: AutocompleteStaticSnippet,
57+): AutocompleteStaticSnippet => {
58+ return snippet;
59+};
60+
5461 const commentifySnippet = (
5562 helper: HelperVars,
5663 snippet: AutocompleteSnippet,
@@ -81,6 +88,8 @@
8188 return formatDiffSnippet(snippet);
8289 case AutocompleteSnippetType.Clipboard:
8390 return formatClipboardSnippet(snippet, workspaceDirs);
91+ case AutocompleteSnippetType.Static:
92+ return formatStaticSnippet(snippet);
8493 }
8594 })
8695 .map((item) => {
modified core/autocomplete/util/AutocompleteLoggingService.ts +22 −19
@@ -105,24 +105,27 @@
105105 });
106106
107107 const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
108- void Telemetry.capture(
109- "autocomplete",
110- {
111- accepted: restOfOutcome.accepted,
112- cacheHit: restOfOutcome.cacheHit,
113- completionId: restOfOutcome.completionId,
114- completionOptions: restOfOutcome.completionOptions,
115- debounceDelay: restOfOutcome.debounceDelay,
116- fileExtension: getUriFileExtension(restOfOutcome.filepath),
117- maxPromptTokens: restOfOutcome.maxPromptTokens,
118- modelName: restOfOutcome.modelName,
119- modelProvider: restOfOutcome.modelProvider,
120- multilineCompletions: restOfOutcome.multilineCompletions,
121- time: restOfOutcome.time,
122- useRecentlyEdited: restOfOutcome.useRecentlyEdited,
123- numLines: restOfOutcome.numLines,
124- },
125- true,
126- );
108+ const toLog = {
109+ accepted: restOfOutcome.accepted,
110+ cacheHit: restOfOutcome.cacheHit,
111+ completionId: restOfOutcome.completionId,
112+ completionOptions: restOfOutcome.completionOptions,
113+ debounceDelay: restOfOutcome.debounceDelay,
114+ fileExtension: getUriFileExtension(restOfOutcome.filepath),
115+ maxPromptTokens: restOfOutcome.maxPromptTokens,
116+ modelName: restOfOutcome.modelName,
117+ modelProvider: restOfOutcome.modelProvider,
118+ multilineCompletions: restOfOutcome.multilineCompletions,
119+ time: restOfOutcome.time,
120+ useRecentlyEdited: restOfOutcome.useRecentlyEdited,
121+ numLines: restOfOutcome.numLines,
122+ };
123+
124+ outcome.enabledStaticContextualization
125+ ? void Telemetry.capture("autocomplete", {
126+ ...toLog,
127+ enabledStaticContextualization: true,
128+ })
129+ : void Telemetry.capture("autocomplete", toLog);
127130 }
128131 }
modified core/autocomplete/util/types.ts +1 −0
@@ -42,4 +42,5 @@
4242 completionId: string;
4343 uniqueId: string;
4444 timestamp: string;
45+ enabledStaticContextualization?: boolean;
4546 }
modified core/config/sharedConfig.ts +5 −0
@@ -22,6 +22,7 @@
2222 optInNextEditFeature: z.boolean(),
2323 enableExperimentalTools: z.boolean(),
2424 codebaseToolCallingOnly: z.boolean(),
25+ enableStaticContextualization: z.boolean(),
2526
2627 // `ui` in `ContinueConfig`
2728 showSessionTabs: z.boolean(),
@@ -188,6 +189,10 @@
188189 configCopy.experimental.codebaseToolCallingOnly =
189190 sharedConfig.codebaseToolCallingOnly;
190191 }
192+ if (sharedConfig.enableStaticContextualization !== undefined) {
193+ configCopy.experimental.enableStaticContextualization =
194+ sharedConfig.enableStaticContextualization;
195+ }
191196
192197 return configCopy;
193198 }
modified core/index.d.ts +71 −0
@@ -871,6 +871,8 @@
871871
872872 // LSP
873873 gotoDefinition(location: Location): Promise<RangeInFile[]>;
874+ gotoTypeDefinition(location: Location): Promise<RangeInFile[]>; // TODO: add to jetbrains
875+ getSignatureHelp(location: Location): Promise<SignatureHelp | null>; // TODO: add to jetbrains
874876
875877 // Callbacks
876878 onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
@@ -1209,6 +1211,7 @@
12091211 experimental_includeRecentlyVisitedRanges: boolean | number;
12101212 experimental_includeRecentlyEditedRanges: boolean | number;
12111213 experimental_includeDiff: boolean | number;
1214+ experimental_enableStaticContextualization: boolean;
12121215 }
12131216
12141217 export interface StdioOptions {
@@ -1408,6 +1411,68 @@
14081411
14091412 export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
14101413
1414+/**
1415+ * Signature help represents the signature of something
1416+ * callable. There can be multiple signatures but only one
1417+ * active and only one active parameter.
1418+ */
1419+export class SignatureHelp {
1420+ /**
1421+ * One or more signatures.
1422+ */
1423+ signatures: SignatureInformation[];
1424+
1425+ /**
1426+ * The active signature.
1427+ */
1428+ activeSignature: number;
1429+
1430+ /**
1431+ * The active parameter of the active signature.
1432+ */
1433+ activeParameter: number;
1434+}
1435+
1436+/**
1437+ * Represents the signature of something callable. A signature
1438+ * can have a label, like a function-name, a doc-comment, and
1439+ * a set of parameters.
1440+ */
1441+export class SignatureInformation {
1442+ /**
1443+ * The label of this signature. Will be shown in
1444+ * the UI.
1445+ */
1446+ label: string;
1447+
1448+ /**
1449+ * The parameters of this signature.
1450+ */
1451+ parameters: ParameterInformation[];
1452+
1453+ /**
1454+ * The index of the active parameter.
1455+ *
1456+ * If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
1457+ */
1458+ activeParameter?: number;
1459+}
1460+
1461+/**
1462+ * Represents a parameter of a callable-signature. A parameter can
1463+ * have a label and a doc-comment.
1464+ */
1465+export class ParameterInformation {
1466+ /**
1467+ * The label of this signature.
1468+ *
1469+ * Either a string or inclusive start and exclusive end offsets within its containing
1470+ * {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
1471+ * a substring of its containing signature information's {@link SignatureInformation.label label}.
1472+ */
1473+ label: string | [number, number];
1474+}
1475+
14111476 /**
14121477 * Represents the configuration for a quick action in the Code Lens.
14131478 * Quick actions are custom commands that can be added to function and class declarations.
@@ -1478,6 +1543,12 @@
14781543 * instead of embeddings, FTS, recently edited files, etc.
14791544 */
14801545 codebaseToolCallingOnly?: boolean;
1546+
1547+ /**
1548+ * If enabled, static contextualization will be used to
1549+ * gather context for the model where necessary.
1550+ */
1551+ enableStaticContextualization?: boolean;
14811552 }
14821553
14831554 export interface AnalyticsConfig {
modified core/protocol/ide.ts +3 −0
@@ -10,6 +10,7 @@
1010 Problem,
1111 Range,
1212 RangeInFile,
13+ SignatureHelp,
1314 TerminalOptions,
1415 Thread,
1516 } from "../";
@@ -82,6 +83,8 @@
8283 getFileStats: [{ files: string[] }, FileStatsMap];
8384
8485 gotoDefinition: [{ location: Location }, RangeInFile[]];
86+ gotoTypeDefinition: [{ location: Location }, RangeInFile[]];
87+ getSignatureHelp: [{ location: Location }, SignatureHelp | null];
8588
8689 getControlPlaneSessionInfo: [
8790 { silent: boolean; useOnboarding: boolean },
modified core/protocol/messenger/messageIde.ts +9 −0
@@ -13,6 +13,7 @@
1313 Problem,
1414 Range,
1515 RangeInFile,
16+ SignatureHelp,
1617 TerminalOptions,
1718 Thread,
1819 } from "../..";
@@ -45,6 +46,14 @@
4546 return this.request("gotoDefinition", { location });
4647 }
4748
49+ async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
50+ return this.request("gotoTypeDefinition", { location });
51+ }
52+
53+ async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
54+ return this.request("getSignatureHelp", { location });
55+ }
56+
4857 onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
4958 this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
5059 }
modified core/util/filesystem.ts +9 −0
@@ -13,6 +13,7 @@
1313 Problem,
1414 Range,
1515 RangeInFile,
16+ SignatureHelp,
1617 TerminalOptions,
1718 Thread,
1819 ToastType,
@@ -44,6 +45,14 @@
4445 return Promise.resolve([]);
4546 }
4647
48+ gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
49+ return Promise.resolve([]);
50+ }
51+
52+ getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
53+ return Promise.resolve(null);
54+ }
55+
4756 onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
4857 return;
4958 }
modified core/util/parameters.ts +1 −0
@@ -24,6 +24,7 @@
2424 experimental_includeRecentlyVisitedRanges: true,
2525 experimental_includeRecentlyEditedRanges: true,
2626 experimental_includeDiff: true,
27+ experimental_enableStaticContextualization: false,
2728 };
2829
2930 export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +8 −0
@@ -594,6 +594,14 @@
594594 throw NotImplementedError("gotoDefinition not implemented yet")
595595 }
596596
597+ override suspend fun gotoTypeDefinition(location: Location): List<RangeInFile> {
598+ throw NotImplementedError("gotoTypeDefinition not implemented yet")
599+ }
600+
601+ override suspend fun getSignatureHelp(location: Location): SignatureHelp? {
602+ throw NotImplementedError("getSignatureHelp not implemented yet")
603+ }
604+
597605 override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) {
598606 throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet")
599607 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +64 −0
@@ -64,6 +64,68 @@
6464 val contents: String
6565 )
6666
67+/**
68+ * Signature help represents the signature of something
69+ * callable. There can be multiple signatures but only one
70+ * active and only one active parameter.
71+ */
72+data class SignatureHelp(
73+ /**
74+ * One or more signatures.
75+ */
76+ val signatures: List<SignatureInformation>,
77+
78+ /**
79+ * The active signature.
80+ */
81+ val activeSignature: Int,
82+
83+ /**
84+ * The active parameter of the active signature.
85+ */
86+ val activeParameter: Int
87+)
88+
89+/**
90+ * Represents the signature of something callable. A signature
91+ * can have a label, like a function-name, a doc-comment, and
92+ * a set of parameters.
93+ */
94+data class SignatureInformation(
95+ /**
96+ * The label of this signature. Will be shown in
97+ * the UI.
98+ */
99+ val label: String,
100+
101+ /**
102+ * The parameters of this signature.
103+ */
104+ val parameters: List<ParameterInformation>,
105+
106+ /**
107+ * The index of the active parameter.
108+ *
109+ * If provided, this is used in place of [SignatureHelp.activeParameter].
110+ */
111+ val activeParameter: Int? = null
112+)
113+
114+/**
115+ * Represents a parameter of a callable-signature. A parameter can
116+ * have a label and a doc-comment.
117+ */
118+data class ParameterInformation(
119+ /**
120+ * The label of this signature.
121+ *
122+ * Either a string or inclusive start and exclusive end offsets within its containing
123+ * [SignatureInformation.label] signature label. *Note*: A label of type string must be
124+ * a substring of its containing signature information's [SignatureInformation.label] label.
125+ */
126+ val label: String // Note: Kotlin doesn't have union types, so this represents the string case
127+)
128+
67129 data class ControlPlaneSessionInfo(
68130 val accessToken: String,
69131 val account: Account
@@ -192,6 +254,8 @@
192254
193255 // LSP
194256 suspend fun gotoDefinition(location: Location): List<RangeInFile>
257+ suspend fun gotoTypeDefinition(location: Location): List<RangeInFile>
258+ suspend fun getSignatureHelp(location: Location): SignatureHelp?
195259
196260 // Callbacks
197261 fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit)
modified extensions/vscode/src/VsCodeIde.ts +27 −1
@@ -6,7 +6,10 @@
66 import * as URI from "uri-js";
77 import * as vscode from "vscode";
88
9-import { executeGotoProvider } from "./autocomplete/lsp";
9+import {
10+ executeGotoProvider,
11+ executeSignatureHelpProvider,
12+} from "./autocomplete/lsp";
1013 import { Repository } from "./otherExtensions/git";
1114 import { SecretStorage } from "./stubs/SecretStorage";
1215 import { VsCodeIdeUtils } from "./util/ideUtils";
@@ -24,6 +27,7 @@
2427 Location,
2528 Problem,
2629 RangeInFile,
30+ SignatureHelp,
2731 TerminalOptions,
2832 Thread,
2933 } from "core";
@@ -87,6 +91,28 @@
8791 return result;
8892 }
8993
94+ async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
95+ const result = await executeGotoProvider({
96+ uri: vscode.Uri.parse(location.filepath),
97+ line: location.position.line,
98+ character: location.position.character,
99+ name: "vscode.executeTypeDefinitionProvider",
100+ });
101+
102+ return result;
103+ }
104+
105+ async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
106+ const result = await executeSignatureHelpProvider({
107+ uri: vscode.Uri.parse(location.filepath),
108+ line: location.position.line,
109+ character: location.position.character,
110+ name: "vscode.executeSignatureHelpProvider",
111+ });
112+
113+ return result;
114+ }
115+
90116 onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
91117 vscode.window.onDidChangeActiveTextEditor((editor) => {
92118 if (editor) {
modified extensions/vscode/src/autocomplete/lsp.ts +53 −1
@@ -13,7 +13,13 @@
1313 import * as URI from "uri-js";
1414 import * as vscode from "vscode";
1515
16-import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
16+import type {
17+ IDE,
18+ Range,
19+ RangeInFile,
20+ RangeInFileWithContents,
21+ SignatureHelp,
22+} from "core";
1723 import type Parser from "web-tree-sitter";
1824
1925 type GotoProviderName =
@@ -23,6 +29,8 @@
2329 | "vscode.executeImplementationProvider"
2430 | "vscode.executeReferenceProvider";
2531
32+type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider";
33+
2634 interface GotoInput {
2735 uri: vscode.Uri;
2836 line: number;
@@ -33,8 +41,19 @@
3341 return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
3442 }
3543
44+interface SignatureHelpInput {
45+ uri: vscode.Uri;
46+ line: number;
47+ character: number;
48+ name: SignatureHelpProviderName;
49+}
50+function signatureHelpKey(input: SignatureHelpInput) {
51+ return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
52+}
53+
3654 const MAX_CACHE_SIZE = 500;
3755 const gotoCache = new Map<string, RangeInFile[]>();
56+const signatureHelpCache = new Map<string, vscode.SignatureHelp>();
3857
3958 export async function executeGotoProvider(
4059 input: GotoInput,
@@ -382,3 +401,36 @@
382401 return [];
383402 }
384403 };
404+
405+export async function executeSignatureHelpProvider(
406+ input: SignatureHelpInput,
407+): Promise<SignatureHelp | null> {
408+ const cacheKey = signatureHelpKey(input);
409+ const cached = signatureHelpCache.get(cacheKey);
410+ if (cached) {
411+ return cached;
412+ }
413+
414+ try {
415+ const definitions = (await vscode.commands.executeCommand(
416+ input.name,
417+ input.uri,
418+ new vscode.Position(input.line, input.character),
419+ )) as SignatureHelp;
420+
421+ // Add to cache
422+ if (signatureHelpCache.size >= MAX_CACHE_SIZE) {
423+ // Remove the oldest item from the cache
424+ const oldestKey = signatureHelpCache.keys().next().value;
425+ if (oldestKey) {
426+ signatureHelpCache.delete(oldestKey);
427+ }
428+ }
429+ signatureHelpCache.set(cacheKey, definitions);
430+
431+ return definitions;
432+ } catch (e) {
433+ console.warn(`Error executing ${input.name}:`, e);
434+ return null;
435+ }
436+}
added extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm +59 −0
@@ -0,0 +1,59 @@
1+;; Capture the variable/function name
2+(variable_declarator
3+ name: (identifier) @function.name
4+ type: (type_annotation
5+ (function_type) @function.type))
6+
7+;; Capture the full parameter list
8+(function_type
9+ parameters: (formal_parameters) @function.params)
10+
11+;; Capture the type identifiers used in the parameters
12+(formal_parameters
13+ (required_parameter
14+ type: (type_annotation
15+ (type_identifier) @param.type))
16+ (required_parameter
17+ type: (type_annotation
18+ (type_identifier) @param.type)))
19+
20+;; Capture the return type of the function
21+(function_type
22+ return_type: (type_identifier) @return.type)
23+
24+;; Capture any parse errors (e.g., the `@`)
25+(ERROR) @error.node
26+
27+;; Capture the entire function declaration line
28+(lexical_declaration) @function.decl
29+
30+;; Matches import declarations like: import { A, B } from "module";
31+(import_statement
32+ (import_clause
33+ (named_imports
34+ (import_specifier
35+ name: (identifier) @import.name)))
36+ source: (string) @import.source)
37+
38+;; Capture standalone function declarations
39+(function_declaration
40+ name: (identifier) @function.name) @function.decl
41+
42+;; Capture the function signature including parameters and return type
43+(function_declaration
44+ parameters: (formal_parameters) @function.params
45+ return_type: (type_annotation)? @function.type)
46+
47+;; For function expressions or arrow functions
48+(function_type
49+ parameters: (formal_parameters) @function.params) @function.decl
50+
51+;; For arrow functions
52+(arrow_function
53+ parameters: (formal_parameters) @function.params) @function.decl
54+
55+;; For function signatures without a body (like in your example)
56+(function_signature
57+ name: (identifier) @function.name
58+ parameters: (formal_parameters) @function.params
59+ return_type: (type_annotation)? @function.type) @function.decl
added extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm +22 −0
@@ -0,0 +1,22 @@
1+;; Match top-level `var`, `let`, or `const` declarations
2+(lexical_declaration
3+ (variable_declarator
4+ name: (identifier) @top.var.name
5+ type: (type_annotation
6+ (_) @top.var.type))) @top.var.decl
7+
8+(variable_declaration
9+ (variable_declarator
10+ name: (identifier) @top.var.name
11+ type: (type_annotation
12+ (_) @top.var.type))) @top.var.decl
13+
14+;; Match function declarations
15+(function_declaration
16+ name: (identifier) @top.fn.name
17+ parameters: (formal_parameters
18+ (required_parameter
19+ pattern: (identifier) @top.fn.param.name
20+ type: (type_annotation (_) @top.fn.param.type)))*
21+
22+ return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl
added extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm +10 −0
@@ -0,0 +1,10 @@
1+;; Capture the type alias name (left-hand side)
2+; (type_alias_declaration
3+; name: (type_identifier) @type.name)
4+
5+;; Capture all identifiers on the right-hand side (value), recursively
6+; (type_alias_declaration
7+; value: (_) @type.value)
8+
9+;; Match all identifiers inside the type value — deeply nested
10+(type_identifier) @type.identifier
added extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm +11 −0
@@ -0,0 +1,11 @@
1+(type_alias_declaration
2+ name: (type_identifier) @type.identifier
3+ value: (_) @type.value)
4+
5+(interface_declaration
6+ name: (type_identifier) @type.identifier
7+ body: (_) @type.value)
8+
9+(enum_declaration
10+ name: (type_identifier) @type.identifier
11+ body: (_) @type.value)
modified gui/src/pages/config/ContinueFeaturesMenu.tsx +14 −0
@@ -2,11 +2,15 @@
22 interface ContinueFeaturesMenuProps {
33 optInNextEditFeature: boolean;
44 handleOptInNextEditToggle: (value: boolean) => void;
5+ enableStaticContextualization: boolean;
6+ handleEnableStaticContextualizationToggle: (value: boolean) => void;
57 }
68
79 export function ContinueFeaturesMenu({
810 optInNextEditFeature,
911 handleOptInNextEditToggle,
12+ enableStaticContextualization,
13+ handleEnableStaticContextualizationToggle,
1014 }: ContinueFeaturesMenuProps) {
1115 return (
1216 <div className="flex w-full flex-col gap-y-4">
@@ -19,6 +23,16 @@
1923 onToggle={() => handleOptInNextEditToggle(!optInNextEditFeature)}
2024 text="Enable Next Edit Over Autocomplete"
2125 />
26+
27+ <ToggleSwitch
28+ isToggled={enableStaticContextualization}
29+ onToggle={() =>
30+ handleEnableStaticContextualizationToggle(
31+ !enableStaticContextualization,
32+ )
33+ }
34+ text="Use Static Contextualization"
35+ />
2236 </div>
2337 </div>
2438 );
modified gui/src/pages/config/UserSettingsForm.tsx +12 −0
@@ -71,6 +71,10 @@
7171 handleUpdate({ optInNextEditFeature: value });
7272 };
7373
74+ const handleEnableStaticContextualizationToggle = (value: boolean) => {
75+ handleUpdate({ enableStaticContextualization: value });
76+ };
77+
7478 useEffect(() => {
7579 // Necessary so that reformatted/trimmed values don't cause dirty state
7680 setFormPromptPath(promptPath);
@@ -92,6 +96,8 @@
9296 config.experimental?.optInNextEditFeature ?? false;
9397 const codebaseToolCallingOnly =
9498 config.experimental?.codebaseToolCallingOnly ?? false;
99+ const enableStaticContextualization =
100+ config.experimental?.enableStaticContextualization ?? false;
95101
96102 const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
97103 const disableIndexing = config.disableIndexing ?? false;
@@ -433,6 +439,12 @@
433439 <ContinueFeaturesMenu
434440 optInNextEditFeature={optInNextEditFeature}
435441 handleOptInNextEditToggle={handleOptInNextEditToggle}
442+ enableStaticContextualization={
443+ enableStaticContextualization
444+ }
445+ handleEnableStaticContextualizationToggle={
446+ handleEnableStaticContextualizationToggle
447+ }
436448 />
437449 )}
438450 </div>
modified packages/config-yaml/src/schemas/data/autocomplete/index.ts +3 −0
@@ -36,6 +36,9 @@
3636 uniqueId: z.string(),
3737 timestamp: z.string(),
3838
39+ // For static contextualization.
40+ enabledStaticContextualization: z.boolean().optional(),
41+
3942 // DEPRECATED - no more nested objects after v0.1.0, all flat values
4043 completionOptions: completionOptionsSchema.optional(),
4144 disableInFiles: z.array(z.string()).optional(),
modified packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts +3 −0
@@ -38,6 +38,9 @@
3838 completionId: true,
3939 uniqueId: true,
4040
41+ // For static contextualization.
42+ enabledStaticContextualization: true,
43+
4144 // Note objects (completionOptions and disableInfiles) removed from 0.1.0 => 0.2.0
4245 });
4346