types.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /**
  2. * Reference Resolution Types
  3. *
  4. * Types for the reference resolution system.
  5. */
  6. import { Language, Node, ReferenceKind } from '../types';
  7. /**
  8. * An unresolved reference from extraction
  9. */
  10. export interface UnresolvedRef {
  11. /** ID of the source node containing the reference */
  12. fromNodeId: string;
  13. /** The name being referenced */
  14. referenceName: string;
  15. /** Type of reference */
  16. referenceKind: ReferenceKind;
  17. /** Line where reference occurs */
  18. line: number;
  19. /** Column where reference occurs */
  20. column: number;
  21. /** File path where reference occurs */
  22. filePath: string;
  23. /** Language of the source file */
  24. language: Language;
  25. /** Possible qualified names it might resolve to */
  26. candidates?: string[];
  27. }
  28. /**
  29. * A resolved reference
  30. */
  31. export interface ResolvedRef {
  32. /** Original unresolved reference */
  33. original: UnresolvedRef;
  34. /** ID of the target node */
  35. targetNodeId: string;
  36. /** Confidence score (0-1) */
  37. confidence: number;
  38. /** How it was resolved */
  39. resolvedBy: 'exact-match' | 'import' | 'qualified-name' | 'framework' | 'fuzzy' | 'instance-method' | 'file-path' | 'function-ref';
  40. }
  41. /**
  42. * Result of resolution attempt
  43. */
  44. export interface ResolutionResult {
  45. /** Successfully resolved references */
  46. resolved: ResolvedRef[];
  47. /** References that couldn't be resolved */
  48. unresolved: UnresolvedRef[];
  49. /** Statistics */
  50. stats: {
  51. total: number;
  52. resolved: number;
  53. unresolved: number;
  54. byMethod: Record<string, number>;
  55. };
  56. }
  57. /**
  58. * Context for resolution - provides access to the graph
  59. */
  60. export interface ResolutionContext {
  61. /** Get all nodes in a file */
  62. getNodesInFile(filePath: string): Node[];
  63. /** Get all nodes by name */
  64. getNodesByName(name: string): Node[];
  65. /** Get all nodes by qualified name */
  66. getNodesByQualifiedName(qualifiedName: string): Node[];
  67. /** Get all nodes of a kind */
  68. getNodesByKind(kind: Node['kind']): Node[];
  69. /** Check if a file exists */
  70. fileExists(filePath: string): boolean;
  71. /** Read file content */
  72. readFile(filePath: string): string | null;
  73. /**
  74. * `readFile(filePath)` split into lines, LRU-cached per file. Receiver-type
  75. * inference scans source lines for EVERY `receiver.method()` ref; splitting
  76. * the whole file per ref made that O(refs-in-file × file-size) — ~20% of
  77. * total index CPU on a Java-heavy repo and a driver of the #1122 watchdog
  78. * kill on large ones. Optional so external/test contexts compile without it;
  79. * callers fall back to splitting `readFile` themselves.
  80. */
  81. getFileLines?(filePath: string): string[] | null;
  82. /**
  83. * The method-definition nodes matching `typeName::methodName` in `language` —
  84. * exactly `resolveMethodOnType`'s kind/language/qualifiedName-suffix filter,
  85. * LRU-cached per (language, type, method). The uncached path re-fetches every
  86. * node sharing the METHOD name (unbounded — tens of thousands on a collision-
  87. * heavy Java repo) and re-scans it per ref, the dominant term in the #1122
  88. * watchdog kill. Cached entries hold only the small filtered result; per-ref
  89. * disambiguation (import FQN, call-site file) stays in the caller so a cached
  90. * entry is valid from any call site. Optional for external/test contexts.
  91. */
  92. getMethodMatches?(typeName: string, methodName: string, language: Language): Node[];
  93. /** Get project root */
  94. getProjectRoot(): string;
  95. /** Get all files */
  96. getAllFiles(): string[];
  97. /** Get nodes by lowercase name (O(1) lookup for fuzzy matching) */
  98. getNodesByLowerName(lowerName: string): Node[];
  99. /**
  100. * Direct supertypes of the type named `typeName` (same language): the classes
  101. * it extends and the interfaces / protocols / traits it implements/conforms to,
  102. * by simple name. Backed by the resolved `implements`/`extends` edges, so it is
  103. * EMPTY during the first resolution pass (edges aren't built yet) and populated
  104. * afterward — the conformance pass uses it to resolve a chained method defined
  105. * on a supertype the receiver type conforms to (e.g. a protocol-extension
  106. * method). Optional so external/test contexts compile without it.
  107. */
  108. getSupertypes?(typeName: string, language: Language): string[];
  109. /**
  110. * Look up a node by its id. Lets matchers derive the FROM-symbol's
  111. * enclosing-class scope (Swift implicit-self method scoping, `this.X`
  112. * member resolution). Optional so external/test contexts compile
  113. * without it.
  114. */
  115. getNodeById?(id: string): Node | null;
  116. /** Get cached import mappings for a file */
  117. getImportMappings(filePath: string, language: Language): ImportMapping[];
  118. /**
  119. * Project import-path aliases (tsconfig/jsconfig `paths`). Returns
  120. * `null` when the project doesn't define any. Cached per resolver
  121. * instance — safe to call from any resolver code path. Optional so
  122. * existing test fixtures and external context implementations
  123. * compile without modification; production resolver implements it.
  124. */
  125. getProjectAliases?(): import('./path-aliases').AliasMap | null;
  126. /**
  127. * Go module info from `go.mod` at the project root. Returns `null`
  128. * when the project has no `go.mod` (non-Go projects, pre-modules
  129. * Go code, or projects whose modules live in subdirectories). Used
  130. * by the Go branch of import resolution to distinguish in-module
  131. * cross-package imports from third-party packages.
  132. */
  133. getGoModule?(): import('./go-module').GoModule | null;
  134. /**
  135. * Monorepo workspace member packages, keyed by declared package name.
  136. * Returns `null` for single-package repos (no `workspaces` field).
  137. * Lets the resolver treat `@scope/ui/sub` as a local import into the
  138. * member's directory instead of an external npm package (#629).
  139. */
  140. getWorkspacePackages?(): import('./workspace-packages').WorkspacePackages | null;
  141. /**
  142. * Re-exports declared by a file (`export { x } from './other'`,
  143. * `export * from './other'`). Empty array when the file has none.
  144. * Optional so older callers compile; the import resolver follows
  145. * re-export chains when this is provided.
  146. */
  147. getReExports?(filePath: string, language: Language): ReExport[];
  148. /**
  149. * List immediate subdirectories of `relativePath` (relative to the
  150. * project root). Returns an empty array when the path doesn't exist
  151. * or isn't a directory. Used by framework resolvers that need to
  152. * walk build-system metadata (e.g. Cargo workspace globs). Optional
  153. * so external context implementations and test fixtures compile
  154. * without modification.
  155. */
  156. listDirectories?(relativePath: string): string[];
  157. /**
  158. * C/C++ include search directories (relative to project root),
  159. * extracted from compile_commands.json or discovered by heuristic.
  160. * Used by resolveCppIncludePath to search -I directories when
  161. * relative resolution fails. Optional so existing callers compile.
  162. */
  163. getCppIncludeDirs?(): string[];
  164. }
  165. /**
  166. * Result of framework-specific file extraction.
  167. */
  168. export interface FrameworkExtractionResult {
  169. /** Framework-specific nodes (e.g. routes) */
  170. nodes: Node[];
  171. /** Framework-specific unresolved references (e.g. route -> handler) */
  172. references: UnresolvedRef[];
  173. }
  174. /**
  175. * Framework-specific resolver
  176. */
  177. export interface FrameworkResolver {
  178. /** Framework name */
  179. name: string;
  180. /** Languages this framework applies to. If omitted, applies to all languages. */
  181. languages?: Language[];
  182. /** Detect if project uses this framework (project-level, called once at startup) */
  183. detect(context: ResolutionContext): boolean;
  184. /** Resolve a reference using framework-specific patterns */
  185. resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null;
  186. /**
  187. * Opt a reference NAME through the resolver's name-exists pre-filter, even when
  188. * no node is named that. Needed for dynamic dispatch where the call target is
  189. * an attribute/descriptor, not a declared symbol (e.g. Django's
  190. * `self._iterable_class(...)`, React effect callbacks). Returning true lets the
  191. * ref reach `resolve()` instead of being dropped for having no name match.
  192. */
  193. claimsReference?(name: string): boolean;
  194. /**
  195. * Extract framework-specific nodes and references from a file.
  196. *
  197. * Returns route nodes, middleware nodes, etc., plus unresolved references
  198. * that link those nodes to handlers (view classes, controller methods,
  199. * included modules). Unresolved references flow into the normal resolution
  200. * pipeline; the framework's own `resolve()` is one of the strategies tried.
  201. */
  202. extract?(filePath: string, content: string): FrameworkExtractionResult;
  203. /**
  204. * Cross-file finalization pass, called once after all per-file extraction
  205. * completes (and again on every incremental sync). Used by frameworks where
  206. * a symbol's final representation depends on a sibling file the per-file
  207. * `extract()` never saw — e.g. NestJS's `RouterModule.register([...])`
  208. * sets route prefixes for controllers declared elsewhere.
  209. *
  210. * Implementations return route/etc. nodes with mutated fields (typically
  211. * `name`); the orchestrator persists each via `updateNode`. The node `id`
  212. * MUST be preserved so existing edges (route → handler, etc.) stay intact;
  213. * `qualifiedName` SHOULD be preserved so the pass stays idempotent — a
  214. * second run can recover the original in-file form from `qualifiedName`.
  215. */
  216. postExtract?(context: ResolutionContext): Node[];
  217. }
  218. /**
  219. * Import mapping from a file
  220. */
  221. export interface ImportMapping {
  222. /** Local name used in the file */
  223. localName: string;
  224. /** Original exported name (may differ due to aliasing) */
  225. exportedName: string;
  226. /** Source module/path */
  227. source: string;
  228. /** Whether it's a default import */
  229. isDefault: boolean;
  230. /** Whether it's a namespace import (import * as X) */
  231. isNamespace: boolean;
  232. /** Resolved file path (if local) */
  233. resolvedPath?: string;
  234. }
  235. /**
  236. * Re-export from a file: `export { x } from './other'` or
  237. * `export * from './other'`. Used by the resolver to chase
  238. * symbols through barrel files.
  239. */
  240. export type ReExport =
  241. | {
  242. kind: 'named';
  243. /** Name as exported by THIS file. */
  244. exportedName: string;
  245. /** Name in the upstream module (differs when renamed: `as`). */
  246. originalName: string;
  247. /** Module specifier of the upstream module. */
  248. source: string;
  249. }
  250. | {
  251. kind: 'wildcard';
  252. /** Module specifier of the upstream module. */
  253. source: string;
  254. };