index.ts 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. /**
  2. * Reference Resolution Orchestrator
  3. *
  4. * Coordinates all reference resolution strategies.
  5. */
  6. import * as fs from 'fs';
  7. import * as path from 'path';
  8. import { Language, Node, UnresolvedReference, Edge } from '../types';
  9. import { QueryBuilder } from '../db/queries';
  10. import {
  11. UnresolvedRef,
  12. ResolvedRef,
  13. ResolutionResult,
  14. ResolutionContext,
  15. FrameworkResolver,
  16. ImportMapping,
  17. } from './types';
  18. import { matchReference, matchFunctionRef, matchDottedCallChain, matchScopedCallChain, sameLanguageFamily, crossesKnownFamily } from './name-matcher';
  19. import { resolveViaImport, resolveJvmImport, extractImportMappings, extractReExports, loadCppIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef } from './import-resolver';
  20. import { detectFrameworks } from './frameworks';
  21. import { synthesizeCallbackEdges } from './callback-synthesizer';
  22. import { createYielder, type MaybeYield } from './cooperative-yield';
  23. import { loadProjectAliases, type AliasMap } from './path-aliases';
  24. import { loadGoModule, type GoModule } from './go-module';
  25. import { loadWorkspacePackages, type WorkspacePackages } from './workspace-packages';
  26. import { logDebug } from '../errors';
  27. import type { ReExport } from './types';
  28. import { LRUCache } from './lru-cache';
  29. /** Node kinds that can declare supertypes (extends/implements). */
  30. const SUPERTYPE_BEARING_KINDS = new Set<Node['kind']>([
  31. 'class', 'struct', 'interface', 'trait', 'protocol', 'enum',
  32. ]);
  33. /**
  34. * Languages whose chained static-factory/fluent calls defer to the conformance
  35. * second pass. Dotted-receiver languages resolve via matchDottedCallChain; the
  36. * `::`-receiver ones (Rust) via matchScopedCallChain.
  37. */
  38. const CHAIN_LANGUAGES = new Set(['java', 'kotlin', 'csharp', 'swift', 'rust', 'go', 'scala', 'dart', 'objc', 'pascal']);
  39. const SCOPED_CHAIN_LANGUAGES = new Set(['rust']);
  40. /** The extractor's chained-receiver encoding: `<inner>().<method>`. */
  41. const CHAIN_SHAPE = /^(.+)\(\)\.(\w+)$/;
  42. /**
  43. * Cache size limits. Each per-resolver cache is bounded so memory
  44. * stays flat on large codebases (20k+ files). Sizes were chosen to
  45. * cover the working set for typical resolution batches without
  46. * exceeding a few hundred MB worst-case. Override via the env var
  47. * `CODEGRAPH_RESOLVER_CACHE_SIZE` (single integer applied to all
  48. * caches) when tuning for very large or very small projects.
  49. */
  50. const DEFAULT_CACHE_LIMIT = 5_000;
  51. function resolveCacheLimit(): number {
  52. const raw = process.env.CODEGRAPH_RESOLVER_CACHE_SIZE;
  53. if (!raw) return DEFAULT_CACHE_LIMIT;
  54. const parsed = Number.parseInt(raw, 10);
  55. if (Number.isFinite(parsed) && parsed > 0) return parsed;
  56. return DEFAULT_CACHE_LIMIT;
  57. }
  58. // Re-export types
  59. export * from './types';
  60. // Pre-built Sets for O(1) built-in lookups (allocated once, shared across all instances)
  61. const JS_BUILT_INS = new Set([
  62. 'console', 'window', 'document', 'global', 'process',
  63. 'Promise', 'Array', 'Object', 'String', 'Number', 'Boolean',
  64. 'Date', 'Math', 'JSON', 'RegExp', 'Error', 'Map', 'Set',
  65. 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval',
  66. 'fetch', 'require', 'module', 'exports', '__dirname', '__filename',
  67. ]);
  68. const REACT_HOOKS = new Set([
  69. 'useState', 'useEffect', 'useContext', 'useReducer', 'useCallback',
  70. 'useMemo', 'useRef', 'useLayoutEffect', 'useImperativeHandle', 'useDebugValue',
  71. ]);
  72. const PYTHON_BUILT_INS = new Set([
  73. 'print', 'len', 'range', 'str', 'int', 'float', 'list', 'dict', 'set', 'tuple',
  74. 'open', 'input', 'type', 'isinstance', 'hasattr', 'getattr', 'setattr',
  75. 'super', 'self', 'cls', 'None', 'True', 'False',
  76. ]);
  77. const PYTHON_BUILT_IN_TYPES = new Set([
  78. 'list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'bool',
  79. 'bytes', 'bytearray', 'frozenset', 'object', 'super',
  80. ]);
  81. const PYTHON_BUILT_IN_METHODS = new Set([
  82. 'append', 'extend', 'insert', 'remove', 'pop', 'clear', 'sort', 'reverse', 'copy',
  83. 'update', 'keys', 'values', 'items', 'get',
  84. 'add', 'discard', 'union', 'intersection', 'difference',
  85. 'split', 'join', 'strip', 'lstrip', 'rstrip', 'replace', 'lower', 'upper',
  86. 'startswith', 'endswith', 'find', 'index', 'count', 'encode', 'decode',
  87. 'format', 'isdigit', 'isalpha', 'isalnum',
  88. 'read', 'write', 'readline', 'readlines', 'close', 'flush', 'seek',
  89. ]);
  90. const GO_STDLIB_PACKAGES = new Set([
  91. 'fmt', 'os', 'io', 'net', 'http', 'log', 'math', 'sort', 'sync',
  92. 'time', 'path', 'bytes', 'strings', 'strconv', 'errors', 'context',
  93. 'json', 'xml', 'csv', 'html', 'template', 'regexp', 'reflect',
  94. 'runtime', 'testing', 'flag', 'bufio', 'crypto', 'encoding',
  95. 'filepath', 'hash', 'mime', 'rand', 'signal', 'sql', 'syscall',
  96. 'unicode', 'unsafe', 'atomic', 'binary', 'debug', 'exec', 'heap',
  97. 'ring', 'scanner', 'tar', 'zip', 'gzip', 'zlib', 'tls', 'url',
  98. 'user', 'pprof', 'trace', 'ast', 'build', 'parser', 'printer',
  99. 'token', 'types', 'cgo', 'plugin', 'race', 'ioutil',
  100. // Kubernetes-common stdlib aliases
  101. 'utilruntime', 'utilwait', 'utilnet',
  102. ]);
  103. const GO_BUILT_INS = new Set([
  104. 'make', 'new', 'len', 'cap', 'append', 'copy', 'delete', 'close',
  105. 'panic', 'recover', 'print', 'println', 'complex', 'real', 'imag',
  106. 'error', 'nil', 'true', 'false', 'iota',
  107. 'int', 'int8', 'int16', 'int32', 'int64',
  108. 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'uintptr',
  109. 'float32', 'float64', 'complex64', 'complex128',
  110. 'string', 'bool', 'byte', 'rune', 'any',
  111. ]);
  112. const PASCAL_UNIT_PREFIXES = [
  113. 'System.', 'Winapi.', 'Vcl.', 'Fmx.', 'Data.', 'Datasnap.',
  114. 'Soap.', 'Xml.', 'Web.', 'REST.', 'FireDAC.', 'IBX.',
  115. 'IdHTTP', 'IdTCP', 'IdSSL',
  116. ];
  117. const PASCAL_BUILT_INS = new Set([
  118. 'System', 'SysUtils', 'Classes', 'Types', 'Variants', 'StrUtils',
  119. 'Math', 'DateUtils', 'IOUtils', 'Generics.Collections', 'Generics.Defaults',
  120. 'Rtti', 'TypInfo', 'SyncObjs', 'RegularExpressions',
  121. 'SysInit', 'Windows', 'Messages', 'Graphics', 'Controls', 'Forms',
  122. 'Dialogs', 'StdCtrls', 'ExtCtrls', 'ComCtrls', 'Menus', 'ActnList',
  123. 'WriteLn', 'Write', 'ReadLn', 'Read', 'Inc', 'Dec', 'Ord', 'Chr',
  124. 'Length', 'SetLength', 'High', 'Low', 'Assigned', 'FreeAndNil',
  125. 'Format', 'IntToStr', 'StrToInt', 'FloatToStr', 'StrToFloat',
  126. 'Trim', 'UpperCase', 'LowerCase', 'Pos', 'Copy', 'Delete', 'Insert',
  127. 'Now', 'Date', 'Time', 'DateToStr', 'StrToDate',
  128. 'Raise', 'Exit', 'Break', 'Continue', 'Abort',
  129. 'True', 'False', 'nil', 'Self', 'Result',
  130. 'Create', 'Destroy', 'Free',
  131. 'TObject', 'TComponent', 'TPersistent', 'TInterfacedObject',
  132. 'TList', 'TStringList', 'TStrings', 'TStream', 'TMemoryStream', 'TFileStream',
  133. 'Exception', 'EAbort', 'EConvertError', 'EAccessViolation',
  134. 'IInterface', 'IUnknown',
  135. ]);
  136. const C_BUILT_INS = new Set([
  137. // Standard C library functions
  138. 'printf', 'fprintf', 'sprintf', 'snprintf', 'scanf', 'fscanf', 'sscanf',
  139. 'malloc', 'calloc', 'realloc', 'free',
  140. 'memcpy', 'memmove', 'memset', 'memcmp', 'memchr',
  141. 'strlen', 'strcpy', 'strncpy', 'strcat', 'strncat', 'strcmp', 'strncmp',
  142. 'strstr', 'strchr', 'strrchr', 'strtok', 'strdup',
  143. 'fopen', 'fclose', 'fread', 'fwrite', 'fgets', 'fputs', 'fputc', 'fgetc',
  144. 'feof', 'ferror', 'fflush', 'fseek', 'ftell', 'rewind',
  145. 'exit', 'abort', 'atexit', 'atoi', 'atol', 'atof', 'strtol', 'strtoul', 'strtod',
  146. 'qsort', 'bsearch',
  147. 'abs', 'labs', 'rand', 'srand',
  148. 'sin', 'cos', 'tan', 'sqrt', 'pow', 'log', 'log10', 'exp', 'ceil', 'floor', 'fabs',
  149. 'time', 'clock', 'difftime', 'mktime', 'localtime', 'gmtime', 'strftime', 'asctime',
  150. 'assert', 'errno',
  151. 'perror', 'remove', 'rename', 'tmpfile', 'tmpnam',
  152. 'getenv', 'system',
  153. 'signal', 'raise',
  154. 'setjmp', 'longjmp',
  155. 'va_start', 'va_end', 'va_arg', 'va_copy',
  156. 'NULL', 'EOF', 'BUFSIZ', 'FILENAME_MAX', 'RAND_MAX', 'EXIT_SUCCESS', 'EXIT_FAILURE',
  157. 'size_t', 'ptrdiff_t', 'wchar_t', 'intptr_t', 'uintptr_t',
  158. 'int8_t', 'int16_t', 'int32_t', 'int64_t',
  159. 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t',
  160. 'FILE',
  161. // POSIX additions commonly seen
  162. 'stat', 'lstat', 'fstat', 'open', 'close', 'read', 'write', 'pipe',
  163. 'fork', 'exec', 'waitpid', 'getpid', 'getppid', 'kill', 'sleep', 'usleep',
  164. 'pthread_create', 'pthread_join', 'pthread_mutex_lock', 'pthread_mutex_unlock',
  165. 'dlopen', 'dlsym', 'dlclose',
  166. ]);
  167. const CPP_BUILT_INS = new Set([
  168. // iostream objects (often used without std:: prefix via using)
  169. 'cout', 'cin', 'cerr', 'clog', 'endl', 'flush', 'ws',
  170. 'std', // the namespace itself when used as std::something
  171. // Common C++ keywords that leak as references
  172. 'nullptr', 'true', 'false', 'this', 'sizeof', 'alignof', 'typeid',
  173. 'static_cast', 'dynamic_cast', 'reinterpret_cast', 'const_cast',
  174. 'make_unique', 'make_shared', 'make_pair',
  175. 'move', 'forward', 'swap',
  176. ]);
  177. /**
  178. * Reference Resolver
  179. *
  180. * Orchestrates reference resolution using multiple strategies.
  181. */
  182. export class ReferenceResolver {
  183. private projectRoot: string;
  184. private queries: QueryBuilder;
  185. private context: ResolutionContext;
  186. private frameworks: FrameworkResolver[] = [];
  187. // Chained static-factory/fluent call refs the first pass couldn't resolve,
  188. // collected in-memory (the batched resolver deletes unresolved refs from the
  189. // DB, so they can't be re-read). Drained by resolveChainedCallsViaConformance
  190. // once implements/extends edges exist, to resolve methods on a supertype the
  191. // receiver conforms to (#750).
  192. private deferredChainRefs: UnresolvedRef[] = [];
  193. // `this.<member>` function-as-value refs whose member is NOT on the
  194. // enclosing class itself — possibly inherited. Collected in-memory for the
  195. // same reason as deferredChainRefs and drained by
  196. // resolveDeferredThisMemberRefs once implements/extends edges exist (#808).
  197. private deferredThisMemberRefs: UnresolvedRef[] = [];
  198. // Per-`.razor`/`.cshtml`-file `@using` namespace set (own directives + folder
  199. // `_Imports.razor`, cascading to the project root). Used to disambiguate a
  200. // markup type ref to the right C# namespace.
  201. private razorUsingsCache = new Map<string, string[]>();
  202. // All per-resolver caches are LRU-bounded. Previously these were
  203. // unbounded Maps that grew with every distinct lookup and OOM'd on
  204. // codebases with 20k+ files (see issue: unbounded cache growth).
  205. private nodeCache: LRUCache<string, Node[]>; // per-file node cache
  206. private fileCache: LRUCache<string, string | null>; // per-file content cache
  207. private importMappingCache: LRUCache<string, ImportMapping[]>;
  208. private reExportCache: LRUCache<string, ReExport[]>;
  209. private nameCache: LRUCache<string, Node[]>; // name → nodes cache
  210. private lowerNameCache: LRUCache<string, Node[]>; // lower(name) → nodes cache
  211. private qualifiedNameCache: LRUCache<string, Node[]>; // qualified_name → nodes cache
  212. private fileLinesCache: LRUCache<string, string[] | null>; // file → split lines cache
  213. private methodMatchCache: LRUCache<string, Node[]>; // lang\0Type::method → matching method nodes
  214. private knownNames: Set<string> | null = null; // all known symbol names for fast pre-filtering
  215. private knownFiles: Set<string> | null = null;
  216. private cachesWarmed = false;
  217. // tsconfig/jsconfig path-alias map. `undefined` = not yet computed,
  218. // `null` = computed and absent. Treated as immutable for the
  219. // resolver's lifetime; callers re-create the resolver if config changes.
  220. private projectAliases: AliasMap | null | undefined = undefined;
  221. // go.mod module path. Same lazy/immutable convention as projectAliases.
  222. private goModule: GoModule | null | undefined = undefined;
  223. // Monorepo workspace member packages. Same lazy/immutable convention.
  224. private workspacePackages: WorkspacePackages | null | undefined = undefined;
  225. constructor(projectRoot: string, queries: QueryBuilder) {
  226. this.projectRoot = projectRoot;
  227. this.queries = queries;
  228. const limit = resolveCacheLimit();
  229. // The content cache is heavier (full file text), so we give it a
  230. // smaller budget than the metadata caches.
  231. const contentLimit = Math.max(64, Math.floor(limit / 5));
  232. this.nodeCache = new LRUCache(limit);
  233. this.fileCache = new LRUCache(contentLimit);
  234. this.importMappingCache = new LRUCache(limit);
  235. this.reExportCache = new LRUCache(limit);
  236. this.nameCache = new LRUCache(limit);
  237. this.lowerNameCache = new LRUCache(limit);
  238. this.qualifiedNameCache = new LRUCache(limit);
  239. // Split-lines arrays are heavier than content strings; refs arrive
  240. // file-ordered, so a small cache still hits nearly always.
  241. this.fileLinesCache = new LRUCache(contentLimit);
  242. this.methodMatchCache = new LRUCache(limit);
  243. this.context = this.createContext();
  244. }
  245. /**
  246. * Initialize the resolver (detect frameworks, etc.)
  247. */
  248. initialize(): void {
  249. this.frameworks = detectFrameworks(this.context);
  250. this.clearCaches();
  251. }
  252. /**
  253. * Run each framework resolver's cross-file finalization pass and persist
  254. * the returned node updates. Idempotent — safe to call after every indexAll
  255. * and every incremental sync. Returns the number of nodes updated.
  256. *
  257. * Caches are cleared before/after so the post-extract pass sees fresh DB
  258. * state and downstream queries see the updated names.
  259. */
  260. runPostExtract(): number {
  261. let updated = 0;
  262. this.clearCaches();
  263. for (const fw of this.frameworks) {
  264. if (!fw.postExtract) continue;
  265. try {
  266. const nodes = fw.postExtract(this.context);
  267. for (const node of nodes) {
  268. this.queries.updateNode(node);
  269. updated++;
  270. }
  271. } catch (err) {
  272. logDebug(`Framework '${fw.name}' postExtract failed`, {
  273. error: err instanceof Error ? err.message : String(err),
  274. });
  275. }
  276. }
  277. if (updated > 0) this.clearCaches();
  278. return updated;
  279. }
  280. /**
  281. * Pre-build lightweight caches for resolution.
  282. * Node lookups are now handled by indexed SQLite queries instead of
  283. * loading all nodes into memory (which caused OOM on large codebases).
  284. * We cache the set of known symbol names for fast pre-filtering.
  285. */
  286. warmCaches(): void {
  287. if (this.cachesWarmed) return;
  288. // Only cache the set of known file paths (lightweight string set)
  289. this.knownFiles = new Set(this.queries.getAllFilePaths());
  290. // Cache all distinct symbol names for fast pre-filtering (just strings, not full nodes)
  291. this.knownNames = new Set(this.queries.getAllNodeNames());
  292. this.cachesWarmed = true;
  293. }
  294. /**
  295. * Clear internal caches
  296. */
  297. clearCaches(): void {
  298. this.nodeCache.clear();
  299. this.fileCache.clear();
  300. this.importMappingCache.clear();
  301. this.reExportCache.clear();
  302. this.nameCache.clear();
  303. this.lowerNameCache.clear();
  304. this.qualifiedNameCache.clear();
  305. this.fileLinesCache.clear();
  306. this.methodMatchCache.clear();
  307. this.knownNames = null;
  308. this.knownFiles = null;
  309. this.cachesWarmed = false;
  310. }
  311. /** `readFile` through the LRU content cache (null = read failed, also cached). */
  312. private readFileCached(filePath: string): string | null {
  313. if (this.fileCache.has(filePath)) {
  314. return this.fileCache.get(filePath)!;
  315. }
  316. const fullPath = path.join(this.projectRoot, filePath);
  317. try {
  318. const content = fs.readFileSync(fullPath, 'utf-8');
  319. this.fileCache.set(filePath, content);
  320. return content;
  321. } catch (error) {
  322. logDebug('Failed to read file for resolution', { filePath, error: String(error) });
  323. this.fileCache.set(filePath, null);
  324. return null;
  325. }
  326. }
  327. /**
  328. * Create the resolution context
  329. */
  330. private createContext(): ResolutionContext {
  331. return {
  332. getNodesInFile: (filePath: string) => {
  333. if (!this.nodeCache.has(filePath)) {
  334. this.nodeCache.set(filePath, this.queries.getNodesByFile(filePath));
  335. }
  336. return this.nodeCache.get(filePath)!;
  337. },
  338. getNodesByName: (name: string) => {
  339. const cached = this.nameCache.get(name);
  340. if (cached !== undefined) return cached;
  341. const result = this.queries.getNodesByName(name);
  342. this.nameCache.set(name, result);
  343. return result;
  344. },
  345. getMethodMatches: (typeName: string, methodName: string, language: Language) => {
  346. const key = `${language} ${typeName}::${methodName}`;
  347. const cached = this.methodMatchCache.get(key);
  348. if (cached !== undefined) return cached;
  349. let candidates = this.nameCache.get(methodName);
  350. if (candidates === undefined) {
  351. candidates = this.queries.getNodesByName(methodName);
  352. this.nameCache.set(methodName, candidates);
  353. }
  354. const want = `${typeName}::${methodName}`;
  355. const matches: Node[] = [];
  356. for (const m of candidates) {
  357. if (m.kind !== 'method') continue;
  358. if (m.language !== language) continue;
  359. const qn = m.qualifiedName;
  360. if (qn === want || qn.endsWith(`::${want}`)) matches.push(m);
  361. }
  362. this.methodMatchCache.set(key, matches);
  363. return matches;
  364. },
  365. getNodesByQualifiedName: (qualifiedName: string) => {
  366. const cached = this.qualifiedNameCache.get(qualifiedName);
  367. if (cached !== undefined) return cached;
  368. const result = this.queries.getNodesByQualifiedNameExact(qualifiedName);
  369. this.qualifiedNameCache.set(qualifiedName, result);
  370. return result;
  371. },
  372. getNodesByKind: (kind: Node['kind']) => {
  373. return this.queries.getNodesByKind(kind);
  374. },
  375. fileExists: (filePath: string) => {
  376. // Check pre-built known files set first (O(1))
  377. if (this.knownFiles) {
  378. const normalized = filePath.replace(/\\/g, '/');
  379. if (this.knownFiles.has(filePath) || this.knownFiles.has(normalized)) {
  380. return true;
  381. }
  382. }
  383. // Fall back to filesystem for files not yet indexed
  384. const fullPath = path.join(this.projectRoot, filePath);
  385. try {
  386. return fs.existsSync(fullPath);
  387. } catch (error) {
  388. logDebug('Error checking file existence', { filePath, error: String(error) });
  389. return false;
  390. }
  391. },
  392. readFile: (filePath: string) => this.readFileCached(filePath),
  393. getFileLines: (filePath: string) => {
  394. const cached = this.fileLinesCache.get(filePath);
  395. if (cached !== undefined) return cached;
  396. const source = this.readFileCached(filePath);
  397. const lines = source === null ? null : source.split(/\r?\n/);
  398. this.fileLinesCache.set(filePath, lines);
  399. return lines;
  400. },
  401. getProjectRoot: () => this.projectRoot,
  402. getAllFiles: () => {
  403. return this.queries.getAllFilePaths();
  404. },
  405. listDirectories: (relativePath: string) => {
  406. const target = relativePath === '.' || relativePath === ''
  407. ? this.projectRoot
  408. : path.join(this.projectRoot, relativePath);
  409. try {
  410. return fs
  411. .readdirSync(target, { withFileTypes: true })
  412. .filter((entry) => entry.isDirectory())
  413. .map((entry) => entry.name);
  414. } catch (error) {
  415. logDebug('Failed to list directory for resolution', {
  416. relativePath,
  417. error: String(error),
  418. });
  419. return [];
  420. }
  421. },
  422. getNodesByLowerName: (lowerName: string) => {
  423. const cached = this.lowerNameCache.get(lowerName);
  424. if (cached !== undefined) return cached;
  425. const result = this.queries.getNodesByLowerName(lowerName);
  426. this.lowerNameCache.set(lowerName, result);
  427. return result;
  428. },
  429. getNodeById: (id: string) => {
  430. return this.queries.getNodeById(id);
  431. },
  432. getSupertypes: (typeName: string, language) => {
  433. // Union the `implements`/`extends` targets of every same-named type node.
  434. // Matching by simple name (not id) reconciles a type declared in one node
  435. // (`KF::Builder`) with conformance declared in a separate extension node
  436. // (`KF.Builder: KFOptionSetter`) — both have name `Builder`.
  437. const typeNodes = this.context
  438. .getNodesByName(typeName)
  439. .filter((n) => SUPERTYPE_BEARING_KINDS.has(n.kind) && n.language === language);
  440. if (typeNodes.length === 0) return [];
  441. const supertypes = new Set<string>();
  442. for (const tn of typeNodes) {
  443. for (const edge of this.queries.getOutgoingEdges(tn.id, ['implements', 'extends'])) {
  444. const target = this.queries.getNodeById(edge.target);
  445. if (target?.name && target.name !== typeName) supertypes.add(target.name);
  446. }
  447. }
  448. return [...supertypes];
  449. },
  450. getImportMappings: (filePath: string, language) => {
  451. const cacheKey = filePath;
  452. const cached = this.importMappingCache.get(cacheKey);
  453. if (cached) return cached;
  454. const content = this.context.readFile(filePath);
  455. if (!content) {
  456. this.importMappingCache.set(cacheKey, []);
  457. return [];
  458. }
  459. const mappings = extractImportMappings(filePath, content, language);
  460. this.importMappingCache.set(cacheKey, mappings);
  461. return mappings;
  462. },
  463. getProjectAliases: () => {
  464. if (this.projectAliases === undefined) {
  465. this.projectAliases = loadProjectAliases(this.projectRoot);
  466. }
  467. return this.projectAliases;
  468. },
  469. getGoModule: () => {
  470. if (this.goModule === undefined) {
  471. this.goModule = loadGoModule(this.projectRoot);
  472. }
  473. return this.goModule;
  474. },
  475. getWorkspacePackages: () => {
  476. if (this.workspacePackages === undefined) {
  477. this.workspacePackages = loadWorkspacePackages(this.projectRoot);
  478. }
  479. return this.workspacePackages;
  480. },
  481. getReExports: (filePath: string, language) => {
  482. const cached = this.reExportCache.get(filePath);
  483. if (cached) return cached;
  484. const content = this.context.readFile(filePath);
  485. if (!content) {
  486. this.reExportCache.set(filePath, []);
  487. return [];
  488. }
  489. // Re-exports are a JS/TS-only construct, and what matters is the
  490. // BARREL file's own language — not the consuming reference's. A
  491. // `.svelte`/`.vue` consumer threads its own language down the
  492. // re-export chase, which would make extractReExports() bail on a
  493. // `.ts` index barrel and silently break the chain (#629). Re-key
  494. // the parse on the barrel's extension so the chase works no matter
  495. // what kind of file imports through it.
  496. const isJsFamily = /\.(?:d\.ts|[cm]?tsx?|[cm]?jsx?|ets)$/i.test(filePath);
  497. const reExports = extractReExports(content, isJsFamily ? 'typescript' : language);
  498. this.reExportCache.set(filePath, reExports);
  499. return reExports;
  500. },
  501. getCppIncludeDirs: () => {
  502. return loadCppIncludeDirs(this.projectRoot);
  503. },
  504. };
  505. }
  506. /**
  507. * Resolve all unresolved references
  508. */
  509. resolveAll(
  510. unresolvedRefs: UnresolvedReference[],
  511. onProgress?: (current: number, total: number) => void
  512. ): ResolutionResult {
  513. // Pre-load all nodes into memory for fast lookups
  514. this.warmCaches();
  515. const resolved: ResolvedRef[] = [];
  516. const unresolved: UnresolvedRef[] = [];
  517. const byMethod: Record<string, number> = {};
  518. // Convert to our internal format, using denormalized fields when available
  519. const refs: UnresolvedRef[] = unresolvedRefs.map((ref) => ({
  520. fromNodeId: ref.fromNodeId,
  521. referenceName: ref.referenceName,
  522. referenceKind: ref.referenceKind,
  523. line: ref.line,
  524. column: ref.column,
  525. filePath: ref.filePath || this.getFilePathFromNodeId(ref.fromNodeId),
  526. language: ref.language || this.getLanguageFromNodeId(ref.fromNodeId),
  527. }));
  528. const total = refs.length;
  529. let lastReportedPercent = -1;
  530. for (let i = 0; i < refs.length; i++) {
  531. const ref = refs[i]!; // Array index is guaranteed to be in bounds
  532. const result = this.resolveOne(ref);
  533. if (result) {
  534. resolved.push(result);
  535. byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
  536. } else {
  537. unresolved.push(ref);
  538. }
  539. // Report progress every 1% to avoid too many updates
  540. if (onProgress) {
  541. const currentPercent = Math.floor((i / total) * 100);
  542. if (currentPercent > lastReportedPercent) {
  543. lastReportedPercent = currentPercent;
  544. onProgress(i + 1, total);
  545. }
  546. }
  547. }
  548. // Final progress report
  549. if (onProgress && total > 0) {
  550. onProgress(total, total);
  551. }
  552. return {
  553. resolved,
  554. unresolved,
  555. stats: {
  556. total: refs.length,
  557. resolved: resolved.length,
  558. unresolved: unresolved.length,
  559. byMethod,
  560. },
  561. };
  562. }
  563. /**
  564. * Check if a reference name has any possible match in the codebase.
  565. * Uses the pre-built knownNames set to skip expensive resolution
  566. * for names that definitely don't exist as symbols.
  567. */
  568. private hasAnyPossibleMatch(name: string): boolean {
  569. if (!this.knownNames) return true; // no pre-filter available
  570. // Direct name match
  571. if (this.knownNames.has(name)) return true;
  572. // For qualified names like "obj.method" or "Class::method", check the parts
  573. const dotIdx = name.indexOf('.');
  574. if (dotIdx > 0) {
  575. const receiver = name.substring(0, dotIdx);
  576. const member = name.substring(dotIdx + 1);
  577. if (this.knownNames.has(receiver) || this.knownNames.has(member)) return true;
  578. // Also check capitalized receiver (instance-method resolution)
  579. const capitalized = receiver.charAt(0).toUpperCase() + receiver.slice(1);
  580. if (this.knownNames.has(capitalized)) return true;
  581. // JVM FQN: `com.example.foo.Bar` — the only useful segment is the
  582. // last one (`Bar`); the earlier check finds `example.foo.Bar` which
  583. // never matches a node name.
  584. const lastDot = name.lastIndexOf('.');
  585. if (lastDot > dotIdx) {
  586. const tail = name.substring(lastDot + 1);
  587. if (tail && this.knownNames.has(tail)) return true;
  588. }
  589. }
  590. const colonIdx = name.indexOf('::');
  591. if (colonIdx > 0) {
  592. const receiver = name.substring(0, colonIdx);
  593. const member = name.substring(colonIdx + 2);
  594. if (this.knownNames.has(receiver) || this.knownNames.has(member)) return true;
  595. // Multi-segment path `a::b::c` (a Rust/C++ module call like
  596. // `database::profiles::find`) — the only segment that names a symbol is
  597. // the last (`c`); `member` above is `b::c`, which never matches a node
  598. // name, so without this the pre-filter drops the ref before the Rust path
  599. // resolver ever sees it. Mirror the dotted-name leaf check above.
  600. const lastColon = name.lastIndexOf('::');
  601. if (lastColon > colonIdx) {
  602. const tail = name.substring(lastColon + 2);
  603. if (tail && this.knownNames.has(tail)) return true;
  604. }
  605. }
  606. // Lua/Luau method calls use a single `:` (`lg:log`); R uses `$` (`lg$log`).
  607. // Check the member (and receiver) around these separators too, so the ref
  608. // isn't dropped here before the method-call resolver ever sees it. The `:`
  609. // case is skipped when the name actually contains `::` (handled above).
  610. for (const sep of [':', '$']) {
  611. if (sep === ':' && name.includes('::')) continue;
  612. const sepIdx = name.indexOf(sep);
  613. if (sepIdx > 0) {
  614. const receiver = name.substring(0, sepIdx);
  615. const member = name.substring(sepIdx + 1);
  616. if (this.knownNames.has(member) || this.knownNames.has(receiver)) return true;
  617. const capitalized = receiver.charAt(0).toUpperCase() + receiver.slice(1);
  618. if (this.knownNames.has(capitalized)) return true;
  619. }
  620. }
  621. // For path-like references (e.g., "snippets/drawer-menu.liquid"), check the filename
  622. const slashIdx = name.lastIndexOf('/');
  623. if (slashIdx > 0) {
  624. const fileName = name.substring(slashIdx + 1);
  625. if (this.knownNames.has(fileName)) return true;
  626. }
  627. return false;
  628. }
  629. /**
  630. * Does `ref.referenceName` match an import declared in its containing
  631. * file? Used as a pre-filter escape so re-export chain resolution
  632. * still gets a chance when the name has no project-wide declaration.
  633. */
  634. private matchesAnyImport(ref: UnresolvedRef): boolean {
  635. const imports = this.context.getImportMappings(ref.filePath, ref.language);
  636. if (imports.length === 0) return false;
  637. for (const imp of imports) {
  638. if (
  639. imp.localName === ref.referenceName ||
  640. ref.referenceName.startsWith(imp.localName + '.')
  641. ) {
  642. return true;
  643. }
  644. }
  645. return false;
  646. }
  647. /**
  648. * Resolve a single reference
  649. */
  650. resolveOne(ref: UnresolvedRef): ResolvedRef | null {
  651. // Skip built-in/external references
  652. if (this.isBuiltInOrExternal(ref)) {
  653. return null;
  654. }
  655. // CFML component paths in inheritance (#1152): `extends="coldbox.system.web.
  656. // Controller"` names the supertype by its dot-separated path (or `extends=
  657. // "../base"` by relative file path) — the graph indexes the class under its
  658. // final segment only, so these die at the fast pre-filter below and never
  659. // resolved. Handled by a dedicated path-corroborated matcher, gated to
  660. // inheritance refs only (a dotted `calls` ref is a member-access chain, not
  661. // a component path). No fallthrough on miss: the full path string can only
  662. // ever mis-match downstream, and an unresolvable supertype usually lives in
  663. // an out-of-repo library (mxunit, testbox) — silent beats wrong.
  664. if (
  665. (ref.language === 'cfml' || ref.language === 'cfscript') &&
  666. (ref.referenceKind === 'extends' || ref.referenceKind === 'implements') &&
  667. (ref.referenceName.includes('.') || ref.referenceName.includes('/'))
  668. ) {
  669. return this.resolveCfmlComponentPath(ref);
  670. }
  671. // Fast pre-filter: skip if no symbol with this name exists anywhere
  672. // AND the name doesn't match a local import. The import escape is
  673. // necessary because re-export rename chains (`import { login }
  674. // from './barrel'` where the barrel has `export { signIn as login }
  675. // from './auth'`) intentionally call a name that has no
  676. // declaration anywhere — only the renamed upstream symbol does.
  677. // ArkTS chained-attribute refs carry a leading dot (`.titleStyle`) that
  678. // routes them to the decorator-gated matcher; the symbol itself is
  679. // indexed under the bare name, so the existence check strips the dot.
  680. // Nix static path imports (`import ./x.nix`) name a FILE, not a symbol —
  681. // they bypass the symbol-existence check and resolve via resolveViaImport.
  682. const existenceName =
  683. ref.language === 'arkts' && ref.referenceName.startsWith('.')
  684. ? ref.referenceName.slice(1)
  685. : ref.referenceName;
  686. if (
  687. !isNixPathImportRef(ref) &&
  688. !this.hasAnyPossibleMatch(existenceName) &&
  689. !this.matchesAnyImport(ref) &&
  690. !this.frameworks.some((f) => f.claimsReference?.(ref.referenceName))
  691. ) {
  692. return null;
  693. }
  694. // Function-as-value refs (#756) get a dedicated, strictly-gated path:
  695. // import-based resolution first (an imported callback resolves through its
  696. // import, the most precise cross-file signal), then matchFunctionRef
  697. // (same-file first, unique-only cross-file, function/method targets only).
  698. // They never reach the framework or fuzzy strategies below.
  699. if (ref.referenceKind === 'function_ref') {
  700. // `this.<member>` values (TS/JS) resolve ONLY against the enclosing
  701. // class's own members — never a same-named symbol elsewhere.
  702. if (ref.referenceName.startsWith('this.')) {
  703. return this.gateLanguage(this.resolveThisMemberFnRef(ref), ref);
  704. }
  705. const viaImport = this.gateLanguage(resolveViaImport(ref, this.context), ref);
  706. if (viaImport) {
  707. const target = this.queries.getNodeById(viaImport.targetNodeId);
  708. if (target && (target.kind === 'function' || target.kind === 'method')) {
  709. return viaImport;
  710. }
  711. }
  712. return this.gateLanguage(matchFunctionRef(ref, this.context), ref);
  713. }
  714. // JVM FQN imports skip framework/name-matcher: `import com.example.Bar`
  715. // resolves directly through the qualifiedName index, which is unambiguous
  716. // even when several `Bar` classes exist in different packages.
  717. const jvmImport = resolveJvmImport(ref, this.context);
  718. if (jvmImport) return jvmImport;
  719. // Razor/Blazor: a markup or `@code` type ref resolves through the file's
  720. // `@using` namespaces (incl. folder `_Imports.razor`). This precisely
  721. // disambiguates a simple name that exists in several namespaces — e.g.
  722. // `CatalogBrand` resolving to `BlazorShared.Models::CatalogBrand` (the DTO,
  723. // which the `.razor` `@using`s) rather than the same-named domain entity.
  724. if (ref.language === 'razor') {
  725. const razorResult = this.resolveRazorUsing(ref);
  726. if (razorResult) return razorResult;
  727. }
  728. const candidates: ResolvedRef[] = [];
  729. // Strategy 1: Try framework-specific resolution. Cross-language bridges
  730. // are deliberately preserved (Drupal `routing.yml` → PHP controller, RN
  731. // JS → native `calls`) — `gateFrameworkLanguage` only drops a type/import
  732. // edge between two KNOWN families (see its doc), never a `calls` bridge or
  733. // a config↔code edge.
  734. for (const framework of this.frameworks) {
  735. const result = this.gateFrameworkLanguage(framework.resolve(ref, this.context), ref);
  736. if (result) {
  737. if (result.confidence >= 0.9) return result; // High confidence, return immediately
  738. candidates.push(result);
  739. }
  740. }
  741. // Strategy 2: Try import-based resolution
  742. const importResult = this.gateLanguage(resolveViaImport(ref, this.context), ref);
  743. if (importResult) {
  744. if (importResult.confidence >= 0.9) return importResult;
  745. candidates.push(importResult);
  746. }
  747. // PHP include/require paths resolve to files via import resolution only.
  748. // If that didn't find the file, do NOT fall back to the symbol
  749. // name-matcher — it would mis-connect e.g. "inc/db.php" to an unrelated
  750. // db.php elsewhere in the tree (a wrong edge is worse than none, #660).
  751. // Terraform refs are directory-scoped by language semantics — the
  752. // framework resolver IS the whole rulebook (`var.X` can never legally
  753. // bind outside its module directory), so the name-matcher's
  754. // qualified-name fallback would only ever add wrong cross-module edges.
  755. // Nix static path imports are file references for the same reason —
  756. // falling through would let "./x.nix" name-match an unrelated node.
  757. if (isPhpIncludePathRef(ref) || isCobolCopybookRef(ref) || isNixPathImportRef(ref) || ref.language === 'terraform') {
  758. return candidates.length > 0
  759. ? candidates.reduce((best, curr) =>
  760. curr.confidence > best.confidence ? curr : best
  761. )
  762. : null;
  763. }
  764. // Strategy 3: Try name matching
  765. let nameResult = this.gateLanguage(matchReference(ref, this.context), ref);
  766. // Nix has no ambient cross-file namespace — a callee binds lexically
  767. // (same file) or through explicit import/callPackage wiring (the import
  768. // path above). A cross-file name match is wrong by construction: every
  769. // module `inherit (lib) mkOption`s the same nixpkgs helpers, so the
  770. // matcher would link each `mkOption` call to whichever file's inherit
  771. // binding it happened to pick. Same-file matches only.
  772. if (nameResult) {
  773. const target = this.queries.getNodeById(nameResult.targetNodeId);
  774. if (ref.language === 'nix') {
  775. if (!target || target.filePath !== ref.filePath) {
  776. nameResult = null;
  777. }
  778. } else if (target && target.language === 'nix') {
  779. // The reverse direction is just as impossible: no other language can
  780. // symbolically call into a .nix binding (interop is eval/CLI, never a
  781. // linkable symbol) — without this, a Python script's `split()` lands
  782. // on some module's `split = ...` binding as a low-confidence match.
  783. nameResult = null;
  784. }
  785. }
  786. if (nameResult) {
  787. candidates.push(nameResult);
  788. }
  789. if (candidates.length === 0) {
  790. // Defer a chained static-factory/fluent call the first pass couldn't
  791. // resolve — its method may live on a supertype the receiver conforms to,
  792. // resolvable once implements/extends edges exist (the conformance pass).
  793. if (
  794. ref.referenceKind === 'calls' &&
  795. CHAIN_LANGUAGES.has(ref.language) &&
  796. CHAIN_SHAPE.test(ref.referenceName)
  797. ) {
  798. this.deferredChainRefs.push(ref);
  799. }
  800. return null;
  801. }
  802. // Return highest confidence candidate
  803. return candidates.reduce((best, curr) =>
  804. curr.confidence > best.confidence ? curr : best
  805. );
  806. }
  807. /**
  808. * Create edges from resolved references
  809. */
  810. createEdges(resolved: ResolvedRef[]): Edge[] {
  811. return resolved.map((ref) => {
  812. // `function_ref` (#756) is internal-only: it persists as a `references`
  813. // edge (the registration site depends on the callback), distinguishable
  814. // by metadata.resolvedBy === 'function-ref'. callers/impact already
  815. // traverse `references`, so registration sites surface with no
  816. // graph-layer changes.
  817. let kind: Edge['kind'] =
  818. ref.original.referenceKind === 'function_ref' ? 'references' : ref.original.referenceKind;
  819. // Promote "extends" to "implements" when a class/struct targets an interface
  820. if (kind === 'extends') {
  821. const targetNode = this.queries.getNodeById(ref.targetNodeId);
  822. if (targetNode && (targetNode.kind === 'interface' || targetNode.kind === 'protocol')) {
  823. const sourceNode = this.queries.getNodeById(ref.original.fromNodeId);
  824. if (sourceNode && sourceNode.kind !== 'interface' && sourceNode.kind !== 'protocol') {
  825. kind = 'implements';
  826. }
  827. }
  828. }
  829. // Promote "calls" to "instantiates" when the resolved target is a
  830. // class/struct. Languages without a `new` keyword (Python, Ruby)
  831. // express instantiation as `Foo()` — extraction can't tell that
  832. // apart from a function call without symbol info, but resolution
  833. // can: if `Foo` resolves to a class, the call IS an instantiation.
  834. if (kind === 'calls') {
  835. const targetNode = this.queries.getNodeById(ref.targetNodeId);
  836. if (targetNode && (targetNode.kind === 'class' || targetNode.kind === 'struct')) {
  837. kind = 'instantiates';
  838. }
  839. }
  840. return {
  841. source: ref.original.fromNodeId,
  842. target: ref.targetNodeId,
  843. kind,
  844. line: ref.original.line,
  845. column: ref.original.column,
  846. metadata: {
  847. confidence: ref.confidence,
  848. resolvedBy: ref.resolvedBy,
  849. // Uniform marker for function-as-value edges (#756), regardless of
  850. // which strategy resolved them (import vs matchFunctionRef) — lets
  851. // tooling label "callback registration" and lets validation diff
  852. // exactly the edges this feature added.
  853. ...(ref.original.referenceKind === 'function_ref' ? { fnRef: true } : {}),
  854. },
  855. };
  856. });
  857. }
  858. /**
  859. * Resolve and persist edges to database
  860. */
  861. resolveAndPersist(
  862. unresolvedRefs: UnresolvedReference[],
  863. onProgress?: (current: number, total: number) => void
  864. ): ResolutionResult {
  865. const result = this.resolveAll(unresolvedRefs, onProgress);
  866. // Create edges from resolved references
  867. const edges = this.createEdges(result.resolved);
  868. // Insert edges into database
  869. if (edges.length > 0) {
  870. this.queries.insertEdges(edges);
  871. }
  872. // Clean up resolved refs from unresolved_refs table so metrics are accurate
  873. if (result.resolved.length > 0) {
  874. this.queries.deleteSpecificResolvedReferences(
  875. result.resolved.map((r) => ({
  876. fromNodeId: r.original.fromNodeId,
  877. referenceName: r.original.referenceName,
  878. referenceKind: r.original.referenceKind,
  879. }))
  880. );
  881. }
  882. return result;
  883. }
  884. /**
  885. * Second resolution pass for chained static-factory / fluent calls whose
  886. * chained method is defined on a SUPERTYPE the receiver's type conforms to —
  887. * a protocol-extension / inherited / default-interface method (#750). The
  888. * first pass can't resolve these because `implements`/`extends` edges aren't
  889. * built yet; this runs AFTER edges are persisted, so `context.getSupertypes`
  890. * (and the conformance fallback in resolveMethodOnType) can walk them.
  891. *
  892. * Operates only on the leftover unresolved refs that have the `inner().method`
  893. * chain shape, for the dotted-chain languages — a small set — and is idempotent
  894. * (re-resolving an already-resolved ref is a no-op since it's been deleted).
  895. * Returns the number of newly-created edges.
  896. */
  897. async resolveChainedCallsViaConformance(): Promise<number> {
  898. const deferred = this.deferredChainRefs;
  899. this.deferredChainRefs = [];
  900. if (deferred.length === 0) return 0;
  901. // Read fresh edges (the main pass built the implements/extends edges after
  902. // these refs were deferred). matchDottedCallChain now resolves a method on a
  903. // supertype via context.getSupertypes -> resolveMethodOnType's conformance walk.
  904. this.clearCaches();
  905. // This post-pass runs synchronously on the indexer's main thread; yield
  906. // periodically so the #850 liveness watchdog heartbeat can fire on a repo
  907. // with many deferred chained calls (#1091).
  908. const maybeYield = createYielder();
  909. const resolved: ResolvedRef[] = [];
  910. for (const ref of deferred) {
  911. // `::`-receiver languages (Rust) split on `::` (matchScopedCallChain);
  912. // dotted-receiver languages on `.` (matchDottedCallChain).
  913. const chainMatch = SCOPED_CHAIN_LANGUAGES.has(ref.language)
  914. ? matchScopedCallChain(ref, this.context)
  915. : matchDottedCallChain(ref, this.context);
  916. const match = this.gateLanguage(chainMatch, ref);
  917. if (match) resolved.push(match);
  918. await maybeYield();
  919. }
  920. if (resolved.length === 0) return 0;
  921. const edges = this.createEdges(resolved);
  922. if (edges.length > 0) {
  923. this.queries.insertEdges(edges);
  924. this.clearCaches();
  925. }
  926. return edges.length;
  927. }
  928. /**
  929. * Resolve one batch with a yield checkpoint between EVERY ref so the #850
  930. * liveness heartbeat can fire on a slow/dense batch (#1091). The checkpoint
  931. * granularity is per-ref — not per-N-refs — because per-ref cost is unbounded
  932. * in the worst case (a collision-heavy method name whose candidate set misses
  933. * the LRU re-fetches tens of thousands of rows): any fixed N multiplies that
  934. * worst case into the watchdog window, which is how v1.2.0 still got killed
  935. * at "Resolving refs" on large Java monorepos (#1122). `maybeYield()` is a
  936. * ~ns time check when under budget, so per-ref checkpoints cost nothing.
  937. * Behaviourally identical to `resolveAll(batch)`: `warmCaches()` is
  938. * idempotent (guarded) and `resolveOne` is independent per ref, so yielding
  939. * between refs changes only timing, never which edges get created.
  940. */
  941. private async resolveBatchYielding(
  942. batch: UnresolvedReference[],
  943. maybeYield: MaybeYield
  944. ): Promise<ResolutionResult> {
  945. this.warmCaches();
  946. const resolved: ResolvedRef[] = [];
  947. const unresolved: UnresolvedRef[] = [];
  948. const byMethod: Record<string, number> = {};
  949. for (const raw of batch) {
  950. const ref: UnresolvedRef = {
  951. fromNodeId: raw.fromNodeId,
  952. referenceName: raw.referenceName,
  953. referenceKind: raw.referenceKind,
  954. line: raw.line,
  955. column: raw.column,
  956. filePath: raw.filePath || this.getFilePathFromNodeId(raw.fromNodeId),
  957. language: raw.language || this.getLanguageFromNodeId(raw.fromNodeId),
  958. };
  959. const result = this.resolveOne(ref);
  960. if (result) {
  961. resolved.push(result);
  962. byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
  963. } else {
  964. unresolved.push(ref);
  965. }
  966. await maybeYield();
  967. }
  968. return {
  969. resolved,
  970. unresolved,
  971. stats: {
  972. total: batch.length,
  973. resolved: resolved.length,
  974. unresolved: unresolved.length,
  975. byMethod,
  976. },
  977. };
  978. }
  979. /**
  980. * Resolve and persist in batches to keep memory bounded.
  981. * Processes unresolved references in chunks, persisting edges and cleaning
  982. * up resolved refs after each batch to avoid accumulating large arrays.
  983. */
  984. async resolveAndPersistBatched(
  985. onProgress?: (current: number, total: number) => void,
  986. batchSize: number = 5000
  987. ): Promise<ResolutionResult> {
  988. this.warmCaches();
  989. // Resolution runs on the indexer's MAIN thread, and the #850 liveness
  990. // watchdog SIGKILLs a process whose event loop stalls past its window (60s
  991. // by default). A single dense batch's resolveAll — or the synthesis pass
  992. // below — can exceed that on a large repo, killing a VALID in-progress index
  993. // (#1091). A shared yielder lets both give the watchdog heartbeat a regular
  994. // window to fire; see ./cooperative-yield.
  995. const maybeYield = createYielder();
  996. const total = this.queries.getUnresolvedReferencesCount();
  997. let processed = 0;
  998. const aggregateStats = {
  999. total: 0,
  1000. resolved: 0,
  1001. unresolved: 0,
  1002. byMethod: {} as Record<string, number>,
  1003. };
  1004. // Process in batches. We always read from offset 0 because resolved refs
  1005. // are deleted after each batch, shifting the remaining rows forward.
  1006. let prevRemaining = Number.POSITIVE_INFINITY;
  1007. while (true) {
  1008. const batch = this.queries.getUnresolvedReferencesBatch(0, batchSize);
  1009. if (batch.length === 0) break;
  1010. const result = await this.resolveBatchYielding(batch, maybeYield);
  1011. // Persist edges immediately
  1012. const edges = this.createEdges(result.resolved);
  1013. if (edges.length > 0) {
  1014. this.queries.insertEdges(edges);
  1015. }
  1016. // Clean up resolved refs so they don't appear in the next batch
  1017. if (result.resolved.length > 0) {
  1018. this.queries.deleteSpecificResolvedReferences(
  1019. result.resolved.map((r) => ({
  1020. fromNodeId: r.original.fromNodeId,
  1021. referenceName: r.original.referenceName,
  1022. referenceKind: r.original.referenceKind,
  1023. }))
  1024. );
  1025. }
  1026. // Delete unresolvable refs from this batch to avoid re-processing them
  1027. if (result.unresolved.length > 0) {
  1028. this.queries.deleteSpecificResolvedReferences(
  1029. result.unresolved.map((r) => ({
  1030. fromNodeId: r.fromNodeId,
  1031. referenceName: r.referenceName,
  1032. referenceKind: r.referenceKind,
  1033. }))
  1034. );
  1035. }
  1036. // Aggregate stats
  1037. aggregateStats.total += result.stats.total;
  1038. aggregateStats.resolved += result.stats.resolved;
  1039. aggregateStats.unresolved += result.stats.unresolved;
  1040. for (const [method, count] of Object.entries(result.stats.byMethod)) {
  1041. aggregateStats.byMethod[method] = (aggregateStats.byMethod[method] || 0) + count;
  1042. }
  1043. processed += batch.length;
  1044. onProgress?.(processed, total);
  1045. // Yield so progress UI can render between batches
  1046. await new Promise(resolve => setImmediate(resolve));
  1047. // If nothing was resolved or removed in this batch, we'd loop forever
  1048. // on the same rows. Break to avoid infinite loop.
  1049. if (result.resolved.length === 0 && result.unresolved.length === batch.length) {
  1050. break;
  1051. }
  1052. // Non-progress guard (defense-in-depth). Because we re-read from offset 0
  1053. // each pass, the unresolved_refs table MUST shrink every iteration — both
  1054. // resolved and unresolved refs are deleted above. If it didn't shrink, a
  1055. // resolver returned a match whose `original.referenceName` differs from the
  1056. // stored row, so the keyed delete no-ops, and we'd re-read + re-resolve +
  1057. // re-insert the same rows forever (the runaway that grew a 99-file repo to
  1058. // 5M edges / 1.4 GB before the Go-fallback fix). Stop rather than grow the
  1059. // graph without bound.
  1060. const remaining = this.queries.getUnresolvedReferencesCount();
  1061. if (remaining >= prevRemaining) break;
  1062. prevRemaining = remaining;
  1063. }
  1064. // Dynamic-edge synthesis: now that all base `calls` edges are persisted,
  1065. // synthesize observer/callback dispatch edges (dispatcher → registered
  1066. // callbacks) that static parsing leaves out. Best-effort — never fail the
  1067. // index on it. See docs/design/callback-edge-synthesis.md.
  1068. try {
  1069. aggregateStats.byMethod['callback-synthesis'] = await synthesizeCallbackEdges(this.queries, this.context);
  1070. } catch {
  1071. // synthesis is additive and optional; ignore failures
  1072. }
  1073. return {
  1074. resolved: [],
  1075. unresolved: [],
  1076. stats: aggregateStats,
  1077. };
  1078. }
  1079. /**
  1080. * Get detected frameworks
  1081. */
  1082. getDetectedFrameworks(): string[] {
  1083. return this.frameworks.map((f) => f.name);
  1084. }
  1085. /**
  1086. * Check if reference is to a built-in or external symbol
  1087. */
  1088. private isBuiltInOrExternal(ref: UnresolvedRef): boolean {
  1089. const name = ref.referenceName;
  1090. const isJsTs = ref.language === 'typescript' || ref.language === 'javascript'
  1091. || ref.language === 'tsx' || ref.language === 'jsx' || ref.language === 'arkts';
  1092. // JavaScript/TypeScript built-ins
  1093. if (isJsTs && JS_BUILT_INS.has(name)) {
  1094. return true;
  1095. }
  1096. // ArkTS resource-reference intrinsics — `$r('app.string.x')` /
  1097. // `$rawfile('x.png')` are framework-provided and appear dozens of times
  1098. // per UI file; without this they can resolve to a stray same-named
  1099. // symbol (e.g. a checked-in hvigor wrapper's `$r`).
  1100. if (ref.language === 'arkts' && (name === '$r' || name === '$rawfile')) {
  1101. return true;
  1102. }
  1103. // Common JS/TS library calls (console.log, Math.floor, JSON.parse)
  1104. if (isJsTs && (name.startsWith('console.') || name.startsWith('Math.') || name.startsWith('JSON.'))) {
  1105. return true;
  1106. }
  1107. // React hooks from React itself
  1108. if (isJsTs && REACT_HOOKS.has(name)) {
  1109. return true;
  1110. }
  1111. // Python built-ins (bare calls only — dotted calls like console.print are method calls)
  1112. if (ref.language === 'python' && PYTHON_BUILT_INS.has(name)) {
  1113. return true;
  1114. }
  1115. // Python built-in method calls (e.g., list.extend, dict.update)
  1116. if (ref.language === 'python') {
  1117. const dotIdx = name.indexOf('.');
  1118. if (dotIdx > 0) {
  1119. const receiver = name.substring(0, dotIdx);
  1120. const method = name.substring(dotIdx + 1);
  1121. // Filter calls on built-in types (list.append, dict.update, etc.)
  1122. if (PYTHON_BUILT_IN_TYPES.has(receiver)) {
  1123. return true;
  1124. }
  1125. // Filter built-in methods on non-class receivers
  1126. // (e.g., items.append where items is a local list variable)
  1127. // But allow if the capitalized receiver matches a known codebase class
  1128. if (PYTHON_BUILT_IN_METHODS.has(method)) {
  1129. const capitalized = receiver.charAt(0).toUpperCase() + receiver.slice(1);
  1130. if (!this.knownNames?.has(capitalized)) {
  1131. return true;
  1132. }
  1133. }
  1134. }
  1135. // A bare name colliding with a builtin method (index, get, update, count…)
  1136. // is only a builtin when NOTHING in the codebase declares it. A declared
  1137. // symbol with that exact name — e.g. a Flask/FastAPI view `def index()` or
  1138. // `def get()` — is a real reference target. Mirrors the knownNames guard on
  1139. // the dotted branch above; without it, every handler named after a builtin
  1140. // method silently loses its route→handler edge.
  1141. if (PYTHON_BUILT_IN_METHODS.has(name) && !this.knownNames?.has(name)) {
  1142. return true;
  1143. }
  1144. }
  1145. // Go standard library packages — refs like "fmt.Println", "http.ListenAndServe", etc.
  1146. if (ref.language === 'go') {
  1147. const dotIdx = name.indexOf('.');
  1148. if (dotIdx > 0) {
  1149. const pkg = name.substring(0, dotIdx);
  1150. if (GO_STDLIB_PACKAGES.has(pkg)) {
  1151. return true;
  1152. }
  1153. }
  1154. if (GO_BUILT_INS.has(name)) {
  1155. return true;
  1156. }
  1157. }
  1158. // Pascal/Delphi built-ins and standard library units
  1159. if (ref.language === 'pascal') {
  1160. if (PASCAL_UNIT_PREFIXES.some((p) => name.startsWith(p))) {
  1161. return true;
  1162. }
  1163. if (PASCAL_BUILT_INS.has(name)) {
  1164. return true;
  1165. }
  1166. }
  1167. // C/C++ standard library symbols (printf, malloc, std::vector, etc.).
  1168. // Names that collide with user-defined symbols are NOT filtered —
  1169. // C and C++ projects routinely shadow stdlib names (custom allocators
  1170. // define `malloc`/`free`, stream wrappers define `read`/`write`/`open`,
  1171. // containers define `move`/`swap`, logging libs wrap `printf`). Killing
  1172. // those resolutions makes the graph wrong, not cleaner. We only filter
  1173. // when there's no user node with this name — then name-matching would
  1174. // produce zero edges anyway and the filter just short-circuits work.
  1175. if (ref.language === 'c' || ref.language === 'cpp') {
  1176. // C++ std:: namespace prefix — safe to filter unconditionally,
  1177. // since `std::foo` is never a user-defined qualified name in
  1178. // tree-sitter output.
  1179. if (name.startsWith('std::')) return true;
  1180. if (C_BUILT_INS.has(name) || CPP_BUILT_INS.has(name)) {
  1181. return !this.hasAnyPossibleMatch(name);
  1182. }
  1183. }
  1184. return false;
  1185. }
  1186. /**
  1187. * Get file path from node ID
  1188. */
  1189. private getFilePathFromNodeId(nodeId: string): string {
  1190. const node = this.queries.getNodeById(nodeId);
  1191. return node?.filePath || '';
  1192. }
  1193. /**
  1194. * Get language from node ID
  1195. */
  1196. private getLanguageFromNodeId(nodeId: string): UnresolvedRef['language'] {
  1197. const node = this.queries.getNodeById(nodeId);
  1198. return node?.language || 'unknown';
  1199. }
  1200. /**
  1201. * Drop an import/name-strategy resolution that crosses a language family.
  1202. * Two regimes (mirrors `applyLanguageGate`'s candidate filter):
  1203. * - `references` (type usage): STRICT — a `Type.member` static read names a
  1204. * same-family type, never a coincidentally same-named symbol in another
  1205. * language. Drops any non-same-family target.
  1206. * - `imports` (import binding / `#include`): both-known — a C++ `#include
  1207. * "X.h"` must not resolve to a same-named ObjC header on another platform
  1208. * (basename collision), but a singleton-family / SFC language (`vue` →
  1209. * `.ts`) importing across is left alone.
  1210. * Applies to the import (strategy 2) + name-match (strategy 3) results.
  1211. */
  1212. /**
  1213. * Collect the `@using` namespaces in scope for a `.razor`/`.cshtml` file: its
  1214. * own `@using` directives plus every `_Imports.razor` from the file's folder up
  1215. * to the project root (Razor `_Imports` cascade). Cached per file.
  1216. */
  1217. private getRazorUsings(filePath: string): string[] {
  1218. const cached = this.razorUsingsCache.get(filePath);
  1219. if (cached) return cached;
  1220. const usings = new Set<string>();
  1221. const addFrom = (src: string | null): void => {
  1222. if (!src) return;
  1223. for (const m of src.matchAll(/^\s*@using\s+(?:static\s+)?([A-Za-z_][\w.]*)/gm)) usings.add(m[1]!);
  1224. };
  1225. addFrom(this.context.readFile(filePath));
  1226. let dir = filePath.includes('/') ? filePath.slice(0, filePath.lastIndexOf('/')) : '';
  1227. // Walk up to the project root, reading each level's _Imports.razor.
  1228. for (;;) {
  1229. addFrom(this.context.readFile(dir ? `${dir}/_Imports.razor` : '_Imports.razor'));
  1230. if (!dir) break;
  1231. const slash = dir.lastIndexOf('/');
  1232. dir = slash >= 0 ? dir.slice(0, slash) : '';
  1233. }
  1234. const arr = [...usings];
  1235. this.razorUsingsCache.set(filePath, arr);
  1236. return arr;
  1237. }
  1238. /**
  1239. * Resolve a Razor/Blazor simple type ref through the file's `@using`
  1240. * namespaces: `CatalogBrand` + `@using BlazorShared.Models` → the node whose
  1241. * qualified name is `BlazorShared.Models::CatalogBrand`. Only resolves when the
  1242. * `@using` set yields exactly ONE type (otherwise it stays ambiguous and falls
  1243. * through to name-matching).
  1244. */
  1245. private resolveRazorUsing(ref: UnresolvedRef): ResolvedRef | null {
  1246. if (ref.referenceName.includes('.') || ref.referenceName.includes('::')) return null;
  1247. const usings = this.getRazorUsings(ref.filePath);
  1248. if (usings.length === 0) return null;
  1249. const found = new Map<string, Node>();
  1250. for (const ns of usings) {
  1251. for (const cand of this.context.getNodesByQualifiedName(`${ns}::${ref.referenceName}`)) {
  1252. found.set(cand.id, cand);
  1253. }
  1254. }
  1255. if (found.size !== 1) return null;
  1256. const target = found.values().next().value!;
  1257. return { original: ref, targetNodeId: target.id, confidence: 0.9, resolvedBy: 'import' };
  1258. }
  1259. /**
  1260. * Resolve a CFML inheritance reference written as a component path (#1152).
  1261. * Two forms exist in real code:
  1262. *
  1263. * - Dotted: `extends="coldbox.system.web.Controller"` — dots are directory
  1264. * separators from the webroot or a CFML mapping. Mappings live in server
  1265. * config / Application.cfc, so the leading segments may not exist in the
  1266. * repo at all (in the coldbox repo itself the path is `system/web/
  1267. * Controller.cfc` — the `coldbox.` root IS the repo). Matched by final
  1268. * segment (the class), corroborated right-to-left against the candidate's
  1269. * parent directories.
  1270. * - Relative: `extends="../base"` / `extends="./base"` (the FW/1 style) —
  1271. * resolved against the referencing file's own directory.
  1272. *
  1273. * Conservative by design: a candidate needs at least one corroborating
  1274. * directory segment (a dotted path whose only same-named class sits in an
  1275. * unrelated directory is almost always an out-of-repo library supertype —
  1276. * mxunit/testbox/coldbox-as-dependency), and a corroboration tie yields no
  1277. * edge. Directory comparison is case-insensitive (CFML path resolution is);
  1278. * the class segment itself is matched exactly, which real code satisfies —
  1279. * dotted paths are written to match the on-disk file name.
  1280. */
  1281. private resolveCfmlComponentPath(ref: UnresolvedRef): ResolvedRef | null {
  1282. const cfmlCandidates = (name: string): Node[] =>
  1283. this.context
  1284. .getNodesByName(name)
  1285. .filter(
  1286. (n) =>
  1287. (n.kind === 'class' || n.kind === 'interface') &&
  1288. (n.language === 'cfml' || n.language === 'cfscript')
  1289. );
  1290. const norm = (p: string): string => p.replace(/\\/g, '/').toLowerCase();
  1291. // Relative-path form: `../base`, `./base`, `sub/thing` — resolve against
  1292. // the referencing file's directory and require an exact (case-insensitive)
  1293. // file match.
  1294. if (ref.referenceName.includes('/')) {
  1295. const rel = ref.referenceName.replace(/\.cfc$/i, '');
  1296. const fromDir = ref.filePath.replace(/\\/g, '/').split('/').slice(0, -1);
  1297. const parts = [...fromDir];
  1298. for (const seg of rel.split('/')) {
  1299. if (seg === '' || seg === '.') continue;
  1300. if (seg === '..') {
  1301. if (parts.length === 0) return null; // escapes the project root
  1302. parts.pop();
  1303. } else {
  1304. parts.push(seg);
  1305. }
  1306. }
  1307. const wantPath = norm(parts.join('/') + '.cfc');
  1308. const className = parts[parts.length - 1];
  1309. if (!className) return null;
  1310. const target = cfmlCandidates(className).find((c) => norm(c.filePath) === wantPath);
  1311. return target
  1312. ? { original: ref, targetNodeId: target.id, confidence: 0.95, resolvedBy: 'file-path' }
  1313. : null;
  1314. }
  1315. // Dotted form.
  1316. const segments = ref.referenceName.split('.').map((s) => s.trim()).filter(Boolean);
  1317. if (segments.length < 2) return null;
  1318. const className = segments[segments.length - 1]!;
  1319. const dirSegments = segments.slice(0, -1);
  1320. let best: Node | null = null;
  1321. let bestScore = 0;
  1322. let tie = false;
  1323. for (const cand of cfmlCandidates(className)) {
  1324. const dirs = cand.filePath.replace(/\\/g, '/').split('/').slice(0, -1);
  1325. // Count matching directory segments right-to-left: for
  1326. // `coldbox.system.web.Controller` vs `system/web/Controller.cfc`,
  1327. // `web` and `system` match, then the repo root ends the run → score 2.
  1328. let score = 0;
  1329. while (
  1330. score < dirSegments.length &&
  1331. score < dirs.length &&
  1332. dirSegments[dirSegments.length - 1 - score]!.toLowerCase() ===
  1333. dirs[dirs.length - 1 - score]!.toLowerCase()
  1334. ) {
  1335. score++;
  1336. }
  1337. if (score > bestScore) {
  1338. best = cand;
  1339. bestScore = score;
  1340. tie = false;
  1341. } else if (score === bestScore && score > 0) {
  1342. tie = true;
  1343. }
  1344. }
  1345. if (!best || bestScore === 0 || tie) return null;
  1346. return { original: ref, targetNodeId: best.id, confidence: 0.9, resolvedBy: 'qualified-name' };
  1347. }
  1348. /**
  1349. * Resolve a `this.<member>` function-as-value reference (#756/#808) to the
  1350. * ENCLOSING CLASS's own member — never a same-named symbol elsewhere. The
  1351. * registration idiom (`btn.on('click', this.handleClick)`) names a member
  1352. * of the class being defined, so the only valid target shares the
  1353. * from-symbol's qualified-name scope. Function/method targets only — a
  1354. * property (a data field, post-#808 classification) yields no edge — same
  1355. * file required, no fallback of any kind.
  1356. */
  1357. private resolveThisMemberFnRef(ref: UnresolvedRef): ResolvedRef | null {
  1358. const member = ref.referenceName.slice('this.'.length);
  1359. if (!member) return null;
  1360. const fromNode = this.queries.getNodeById(ref.fromNodeId);
  1361. if (!fromNode) return null;
  1362. // A hook declared at class-body level (Ruby `before_action :authenticate`)
  1363. // attributes to the CLASS node itself — its qualified name IS the scope.
  1364. // For members, strip the member segment.
  1365. let classPrefix: string;
  1366. if (SUPERTYPE_BEARING_KINDS.has(fromNode.kind) || fromNode.kind === 'module') {
  1367. classPrefix = fromNode.qualifiedName;
  1368. } else {
  1369. const sep = fromNode.qualifiedName.lastIndexOf('::');
  1370. if (sep <= 0) return null; // not inside a class scope
  1371. classPrefix = fromNode.qualifiedName.slice(0, sep);
  1372. }
  1373. const candidates = this.context
  1374. .getNodesByQualifiedName(`${classPrefix}::${member}`)
  1375. .filter(
  1376. (n) =>
  1377. (n.kind === 'function' || n.kind === 'method') &&
  1378. n.filePath === ref.filePath &&
  1379. n.id !== ref.fromNodeId
  1380. );
  1381. if (candidates.length === 0) {
  1382. // Not on the class itself — possibly INHERITED. implements/extends
  1383. // edges don't exist yet in this pass, so retry in the supertype pass
  1384. // (resolveDeferredThisMemberRefs) instead of giving up.
  1385. this.deferredThisMemberRefs.push(ref);
  1386. return null;
  1387. }
  1388. const target = candidates.reduce((a, b) => (a.startLine <= b.startLine ? a : b));
  1389. return {
  1390. original: ref,
  1391. targetNodeId: target.id,
  1392. confidence: 0.95,
  1393. resolvedBy: 'function-ref',
  1394. };
  1395. }
  1396. /**
  1397. * Second pass for `this.<member>` refs whose member wasn't on the enclosing
  1398. * class itself (#808): once implements/extends edges exist, walk the
  1399. * class's supertypes (transitively, depth-capped) and resolve the member on
  1400. * the nearest one that declares it — `this.handleSubmit` registered in a
  1401. * subclass resolves to `FormBase::handleSubmit`. Validated targets only
  1402. * (function/method kind, same language family); no match → no edge.
  1403. * Mirrors resolveChainedCallsViaConformance's lifecycle. Returns the number
  1404. * of newly-created edges.
  1405. */
  1406. async resolveDeferredThisMemberRefs(): Promise<number> {
  1407. const deferred = this.deferredThisMemberRefs;
  1408. this.deferredThisMemberRefs = [];
  1409. if (deferred.length === 0) return 0;
  1410. this.clearCaches();
  1411. // Synchronous main-thread post-pass with a per-ref supertype BFS — yield
  1412. // periodically so the #850 liveness watchdog heartbeat can fire (#1091).
  1413. const maybeYield = createYielder();
  1414. const resolved: ResolvedRef[] = [];
  1415. for (const ref of deferred) {
  1416. await maybeYield();
  1417. const member = ref.referenceName.slice('this.'.length);
  1418. const fromNode = this.queries.getNodeById(ref.fromNodeId);
  1419. if (!fromNode || !member) continue;
  1420. // Class-body-level hooks (Ruby) attribute to the CLASS node itself.
  1421. let className: string;
  1422. if (SUPERTYPE_BEARING_KINDS.has(fromNode.kind) || fromNode.kind === 'module') {
  1423. className = fromNode.name;
  1424. } else {
  1425. const sep = fromNode.qualifiedName.lastIndexOf('::');
  1426. if (sep <= 0) continue;
  1427. const classPrefix = fromNode.qualifiedName.slice(0, sep);
  1428. className = classPrefix.includes('::')
  1429. ? classPrefix.slice(classPrefix.lastIndexOf('::') + 2)
  1430. : classPrefix;
  1431. }
  1432. // NODE-anchored BFS up the supertype graph: start from the class node
  1433. // in the ref's own file (never a same-named class elsewhere — rails has
  1434. // a dozen `Engine`s), follow implements/extends EDGES to supertype
  1435. // NODES, and look members up through `contains` edges. No name-based
  1436. // unions anywhere — a name-keyed getSupertypes('Engine') merged every
  1437. // Engine's parents and produced a cross-class wrong edge on rails.
  1438. let frontierNodes = this.context
  1439. .getNodesByName(className)
  1440. .filter(
  1441. (n) =>
  1442. SUPERTYPE_BEARING_KINDS.has(n.kind) &&
  1443. n.filePath === ref.filePath
  1444. );
  1445. if (frontierNodes.length === 0) {
  1446. // The class itself may be declared in another file (partial/reopened
  1447. // classes); fall back to same-family nodes of that name.
  1448. frontierNodes = this.context
  1449. .getNodesByName(className)
  1450. .filter(
  1451. (n) =>
  1452. SUPERTYPE_BEARING_KINDS.has(n.kind) &&
  1453. sameLanguageFamily(n.language, ref.language)
  1454. );
  1455. }
  1456. const seenNodes = new Set<string>(frontierNodes.map((n) => n.id));
  1457. let target: Node | null = null;
  1458. for (let depth = 0; depth < 5 && frontierNodes.length > 0 && !target; depth++) {
  1459. const next: Node[] = [];
  1460. for (const typeNode of frontierNodes) {
  1461. for (const edge of this.queries.getOutgoingEdges(typeNode.id, ['implements', 'extends'])) {
  1462. const superNode = this.queries.getNodeById(edge.target);
  1463. if (!superNode || seenNodes.has(superNode.id)) continue;
  1464. seenNodes.add(superNode.id);
  1465. if (!SUPERTYPE_BEARING_KINDS.has(superNode.kind)) continue;
  1466. // Member lookup anchored on the supertype's contains edges.
  1467. for (const c of this.queries.getOutgoingEdges(superNode.id, ['contains'])) {
  1468. const m = this.queries.getNodeById(c.target);
  1469. if (
  1470. m &&
  1471. m.name === member &&
  1472. (m.kind === 'function' || m.kind === 'method') &&
  1473. sameLanguageFamily(m.language, ref.language)
  1474. ) {
  1475. target = m;
  1476. break;
  1477. }
  1478. }
  1479. if (target) break;
  1480. next.push(superNode);
  1481. }
  1482. if (target) break;
  1483. }
  1484. frontierNodes = next;
  1485. }
  1486. if (target) {
  1487. resolved.push({
  1488. original: ref,
  1489. targetNodeId: target.id,
  1490. confidence: 0.85,
  1491. resolvedBy: 'function-ref',
  1492. });
  1493. }
  1494. }
  1495. if (resolved.length === 0) return 0;
  1496. const edges = this.createEdges(resolved);
  1497. if (edges.length > 0) {
  1498. this.queries.insertEdges(edges);
  1499. this.clearCaches();
  1500. }
  1501. return edges.length;
  1502. }
  1503. private gateLanguage(result: ResolvedRef | null, ref: UnresolvedRef): ResolvedRef | null {
  1504. if (!result) return result;
  1505. const tgt = this.getLanguageFromNodeId(result.targetNodeId);
  1506. if (!tgt || !ref.language) return result;
  1507. if ((ref.referenceKind === 'references' || ref.referenceKind === 'function_ref') && !sameLanguageFamily(tgt, ref.language)) return null;
  1508. if (ref.referenceKind === 'imports' && crossesKnownFamily(tgt, ref.language)) return null;
  1509. return result;
  1510. }
  1511. /**
  1512. * Drop a FRAMEWORK-strategy resolution that crosses two *known* language
  1513. * families for a type-usage (`references`) or import-binding (`imports`)
  1514. * edge. The framework strategy is intentionally ungated for cross-language
  1515. * bridges, but those legitimate bridges are either `calls` edges (RN/Expo
  1516. * JS → native) or config↔code edges whose config side (`yaml`/`blade`/…) is
  1517. * not a known programming-language family. A `references`/`imports` edge
  1518. * between two *known* families is always a coincidental name collision — the
  1519. * React/Svelte/Vue PascalCase component resolvers name-match `getNodesByName`
  1520. * without a language check, so a TS `<TestRunner>` ref happily matched a
  1521. * Kotlin `class TestRunner`. Gating only the both-known-cross-family case
  1522. * lets config bridges and `calls` bridges through untouched.
  1523. */
  1524. private gateFrameworkLanguage(result: ResolvedRef | null, ref: UnresolvedRef): ResolvedRef | null {
  1525. if (!result) return result;
  1526. if (ref.referenceKind !== 'references' && ref.referenceKind !== 'imports') return result;
  1527. const tgt = this.getLanguageFromNodeId(result.targetNodeId);
  1528. if (tgt && ref.language && crossesKnownFamily(tgt, ref.language)) return null;
  1529. return result;
  1530. }
  1531. }
  1532. /**
  1533. * Create a reference resolver instance
  1534. */
  1535. export function createResolver(projectRoot: string, queries: QueryBuilder): ReferenceResolver {
  1536. const resolver = new ReferenceResolver(projectRoot, queries);
  1537. resolver.initialize();
  1538. return resolver;
  1539. }