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