add initial fplab static contextualization code

This commit is contained in:
Jacob Kim 2025-06-28 15:37:07 -07:00
parent 13db7fe9a5
commit 30bfaa0904
10 changed files with 362 additions and 0 deletions

View file

@ -0,0 +1,181 @@
import * as fs from "fs/promises";
import { IDE, Position } from "../../..";
import { AutocompleteCodeSnippet, AutocompleteStaticSnippet } from "../../snippets/types";
import { HelperVars } from "../../util/HelperVars";
import { HoleContext, RelevantHeaders, RelevantTypes } from "./types";
import { getAst } from "../../util/ast";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import path from "path";
export class StaticContextService {
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
}
public async getContext(
helper: HelperVars
): Promise<AutocompleteStaticSnippet> {
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
const holeContext = await this.getHoleContext(helper.filepath, helper.pos);
const relevantTypes = await this.extractRelevantTypes(
holeContext.fullHoverResult,
holeContext.functionName,
holeContext.range.start.line,
new Map<string, TypeSpanAndSourceFileAndAst>(),
holeContext.source,
new Map<string, string>(),
);
let repo: string[] = [];
if (this.language === "typescript") {
repo = getAllTSFiles(this.repoPath);
} else if (this.language === "ocaml") {
repo = getAllOCamlFiles(this.repoPath);
}
const relevantHeaders = await this.extractRelevantHeaders(
repo,
relevantTypes,
holeContext.functionTypeSpan,
holeContext.functionName,
this.repoPath
);
const relevantTypesToReturn: Map<string, string[]> = 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<string, string[]> = 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]);
}
})
return {
holeType: ""
relevantTypes: ""
relevantHeaders: ""
};
}
private async getHoleContext(
sketchFilePath: string,
cursorPosition: Position
): Promise<HoleContext> {
// We need to inject the hole @ to trigger a treesitter error node.
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,
path.join(`./queries/hole-queries/${language}.scm`)
);
if (!query) {
throw new Error(
`failed to get query for file ${sketchFilePath} and language ${language}`
);
}
const captures = query.captures(ast.rootNode);
const res: HoleContext = {
fullHoverResult: "",
functionName: "",
functionTypeSpan: "",
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 52 },
},
source: `file://${sketchFilePath}`,
};
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;
}
case "function.name": {
res.functionName = node.text;
}
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,
},
};
}
}
}
return res;
}
private async extractRelevantTypes(): Promise<RelevantTypes> {
}
private async extractRelevantHeaders(): Promise<RelevantHeaders> {
}
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
}
}

View file

@ -0,0 +1,36 @@
;; 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)

View file

@ -0,0 +1,36 @@
export const TYPESCRIPT_HOLE_QUERY = `;; 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)`;

View file

@ -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

View file

@ -0,0 +1,22 @@
export const TYPESCRIPT_GET_TOPLEVEL_HEADERS = `;; 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`

View file

@ -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

View file

@ -0,0 +1,10 @@
export const TYPESCRIPT_EXTRACT_IDENTIFIERS = `;; 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`;

View file

@ -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)

View file

@ -0,0 +1,11 @@
export const TYPESCRIPT_FIND_TYPEDECL_GIVEN_TYPEIDENTIFIER = `(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)`;

View file

@ -0,0 +1,23 @@
import { Tree } from "web-tree-sitter";
import { Range } from "../../..";
interface TypeSpanAndSourceFile {
typeSpan: string,
sourceFile: string,
}
interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
ast: Tree
}
export interface HoleContext {
fullHoverResult: string;
functionName: string;
functionTypeSpan: string;
range: Range;
source: string;
}
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;