name-matcher.ts 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585
  1. /**
  2. * Name Matcher
  3. *
  4. * Handles symbol name matching for reference resolution.
  5. */
  6. import { Language, Node } from '../types';
  7. import { UnresolvedRef, ResolvedRef, ResolutionContext } from './types';
  8. /**
  9. * Ceiling on how many same-named definitions a FUZZY name-match strategy will
  10. * score. A name defined more times than this is "ubiquitous" — a method/symbol
  11. * re-declared across a vendored theme or SDK (e.g. `init`/`update`/`render` on
  12. * every widget of a committed Metronic theme — #999). No directory-proximity or
  13. * receiver-word-overlap score can reliably pick THE one true target among
  14. * thousands, so the fuzzy strategies (matchByExactName's findBestMatch, and
  15. * matchMethodCall Strategy 3) decline above the ceiling instead of emitting a
  16. * low-confidence, almost-certainly-wrong edge. This also caps their per-ref cost
  17. * at O(ceiling): without it, K same-named refs each scored K candidates — the
  18. * O(K²) blow-up that pinned a core for 15-28 min at "Resolving refs … 94%" on a
  19. * repo vendoring a large JS/TS theme (#999). The PRECISE strategies are
  20. * unaffected: qualified-name, import-based, and class-name (Strategy 1/2)
  21. * resolution all still run and resolve a ubiquitous name when the context names
  22. * its exact target. Real repos top out near ~40 same-named methods, so a normal
  23. * codebase never reaches this; only bulk-vendored code does. Tune via
  24. * `CODEGRAPH_AMBIGUOUS_NAME_CEILING`.
  25. */
  26. const DEFAULT_AMBIGUOUS_NAME_CEILING = 500;
  27. function resolveAmbiguousNameCeiling(): number {
  28. const raw = process.env.CODEGRAPH_AMBIGUOUS_NAME_CEILING;
  29. if (!raw) return DEFAULT_AMBIGUOUS_NAME_CEILING;
  30. const parsed = Number.parseInt(raw, 10);
  31. return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_AMBIGUOUS_NAME_CEILING;
  32. }
  33. const AMBIGUOUS_NAME_CEILING = resolveAmbiguousNameCeiling();
  34. /**
  35. * Try to resolve a path-like reference (e.g., "snippets/drawer-menu.liquid")
  36. * by matching the filename against file nodes.
  37. */
  38. export function matchByFilePath(
  39. ref: UnresolvedRef,
  40. context: ResolutionContext
  41. ): ResolvedRef | null {
  42. // Path-like (`a/b.liquid`) OR a bare filename ending in a short extension
  43. // (`Foo.h` — an Objective-C `#import "Foo.h"`, resolved to the header by
  44. // basename). A bare ref WITHOUT an extension is a symbol name, not a file, so
  45. // leave it to the symbol-matching strategies.
  46. if (!ref.referenceName.includes('/') && !/\.[A-Za-z][A-Za-z0-9]{0,3}$/.test(ref.referenceName)) {
  47. return null;
  48. }
  49. // Extract the filename from the path
  50. const fileName = ref.referenceName.split('/').pop();
  51. if (!fileName) return null;
  52. // Search for file nodes with this name
  53. const candidates = context.getNodesByName(fileName);
  54. const fileNodes = candidates.filter(n => n.kind === 'file');
  55. if (fileNodes.length === 0) return null;
  56. // Prefer exact path match on qualified_name
  57. const exactMatch = fileNodes.find(n => n.qualifiedName === ref.referenceName || n.filePath === ref.referenceName);
  58. if (exactMatch) {
  59. return {
  60. original: ref,
  61. targetNodeId: exactMatch.id,
  62. confidence: 0.95,
  63. resolvedBy: 'file-path',
  64. };
  65. }
  66. // Fall back to suffix match (e.g., ref="snippets/foo.liquid" matches
  67. // "src/snippets/foo.liquid"). When several files share the basename — a
  68. // `#include "RNCAsyncStorage.h"` with a same-named header on another platform
  69. // (windows/code/ vs apple/) — prefer the one in the includer's own directory,
  70. // then by directory proximity / same language family. A C/C++ include (and any
  71. // bare-filename import) resolves relative to the including file, not to an
  72. // arbitrary same-named header elsewhere in the tree.
  73. const suffixMatches = fileNodes.filter(
  74. n => n.qualifiedName.endsWith(ref.referenceName) || n.filePath.endsWith(ref.referenceName)
  75. );
  76. if (suffixMatches.length > 0) {
  77. return {
  78. original: ref,
  79. targetNodeId: pickClosestFileNode(suffixMatches, ref).id,
  80. confidence: 0.85,
  81. resolvedBy: 'file-path',
  82. };
  83. }
  84. // If only one file node with this name, use it with lower confidence
  85. if (fileNodes.length === 1) {
  86. return {
  87. original: ref,
  88. targetNodeId: fileNodes[0]!.id,
  89. confidence: 0.7,
  90. resolvedBy: 'file-path',
  91. };
  92. }
  93. return null;
  94. }
  95. /**
  96. * Among several file nodes that all match a bare include/import by basename,
  97. * pick the one closest to the referencing file: same directory first, then by
  98. * directory-tree proximity, with the same language family as a tiebreak. A
  99. * C/C++ `#include "X.h"` (and any bare-filename import) resolves relative to the
  100. * including file — not to an arbitrary same-named header on another platform.
  101. */
  102. function pickClosestFileNode(candidates: Node[], ref: UnresolvedRef): Node {
  103. const dirOf = (p: string): string => {
  104. const i = p.lastIndexOf('/');
  105. return i >= 0 ? p.slice(0, i) : '';
  106. };
  107. const refDir = dirOf(ref.filePath);
  108. const sameDir = candidates.filter((c) => dirOf(c.filePath) === refDir);
  109. const pool = sameDir.length > 0 ? sameDir : candidates;
  110. let best = pool[0]!;
  111. let bestScore = -Infinity;
  112. for (const c of pool) {
  113. const score =
  114. computePathProximity(ref.filePath, c.filePath) +
  115. (sameLanguageFamily(c.language, ref.language) ? 5 : 0);
  116. if (score > bestScore) {
  117. bestScore = score;
  118. best = c;
  119. }
  120. }
  121. return best;
  122. }
  123. /**
  124. * Language families that share a type system / runtime, so a same-language-only
  125. * reference may still resolve across them (a Kotlin `Foo.BAR` can name a Java
  126. * `Foo`). Anything not listed forms its own singleton family.
  127. */
  128. const LANGUAGE_FAMILY: Record<string, string> = {
  129. java: 'jvm', kotlin: 'jvm', scala: 'jvm',
  130. swift: 'apple', objc: 'apple',
  131. // ArkTS is a TS superset — every HarmonyOS project mixes `.ets` UI with
  132. // `.ts` logic modules, so refs must cross freely between them.
  133. typescript: 'web', tsx: 'web', javascript: 'web', jsx: 'web', arkts: 'web',
  134. c: 'c', cpp: 'c',
  135. // Razor/Blazor markup names C# types — same family so `@model Foo` /
  136. // `<MyComponent/>` resolve to their `.cs` class through the cross-family gate.
  137. csharp: 'dotnet', razor: 'dotnet',
  138. };
  139. export function sameLanguageFamily(a: string, b: string): boolean {
  140. if (a === b) return true;
  141. const fa = LANGUAGE_FAMILY[a];
  142. return fa !== undefined && fa === LANGUAGE_FAMILY[b];
  143. }
  144. /**
  145. * True when `lang` belongs to a known multi-language family (jvm/apple/web/c).
  146. * Languages not listed (php, python, go, ruby, rust, dart, …) and config
  147. * formats (yaml/xml/blade) form their own singleton families and return
  148. * `false` — used to leave config↔code framework bridges (whose config side is
  149. * never a known programming-language family) out of the cross-family gate.
  150. */
  151. export function isKnownLanguageFamily(lang: string): boolean {
  152. return LANGUAGE_FAMILY[lang] !== undefined;
  153. }
  154. /**
  155. * True when `a` and `b` are two DIFFERENT *known* language families — the
  156. * signature of a coincidental cross-language name collision (a TS `import
  157. * React` matching a Swift `import React`, a C++ `#include "X.h"` matching a
  158. * same-named ObjC header on another platform). The both-*known* test is
  159. * deliberately weaker than {@link sameLanguageFamily}'s negation: a
  160. * single-file-component language that carries its own tag (`vue`/`svelte`)
  161. * importing a `.ts` module, or any singleton-family language (php/go/ruby/…),
  162. * returns `false` here and is left alone.
  163. */
  164. export function crossesKnownFamily(a: string, b: string): boolean {
  165. return isKnownLanguageFamily(a) && isKnownLanguageFamily(b) && !sameLanguageFamily(a, b);
  166. }
  167. /**
  168. * Drop cross-language candidates from a name lookup. Two regimes:
  169. * - `references` (type-usage): a type named in language X resolves to a
  170. * SAME-family type, never a coincidentally same-named symbol in another
  171. * language (the Android `BatteryManager` system class vs a JS one). Strict
  172. * same-family filter — cross-language communication is `calls`, not refs.
  173. * - `imports` (import binding): an `import`/`#include` never crosses two
  174. * KNOWN families (TS `import React` ↮ Swift `import React`). Weaker
  175. * both-known filter so `.vue`/`.svelte` (own tag) importing `.ts` survives.
  176. */
  177. function applyLanguageGate(candidates: Node[], ref: UnresolvedRef): Node[] {
  178. if (ref.referenceKind === 'references' || ref.referenceKind === 'function_ref') {
  179. return candidates.filter((c) => sameLanguageFamily(c.language, ref.language));
  180. }
  181. if (ref.referenceKind === 'imports') {
  182. return candidates.filter((c) => !crossesKnownFamily(c.language, ref.language));
  183. }
  184. return candidates;
  185. }
  186. /**
  187. * Resolve a function-as-value reference (#756) — a function name used as a
  188. * callback/function-pointer value (`register(handler)`, `o->cb = handler`,
  189. * `{ .cb = handler }`, `signal(SIGINT, handler)`). The ONLY strategy allowed
  190. * for `function_ref` refs: exact name, function/method targets only, same
  191. * language family, same-file first, and cross-file only when the match is
  192. * UNIQUE. No fuzzy fallback, no qualified-name walking — a wrong callback
  193. * edge is worse than none.
  194. */
  195. export function matchFunctionRef(
  196. ref: UnresolvedRef,
  197. context: ResolutionContext
  198. ): ResolvedRef | null {
  199. // `this.<member>` refs are resolved ONLY by the class-scoped resolver in
  200. // resolveOne (resolveThisMemberFnRef) — never by name matching here.
  201. if (ref.referenceName.startsWith('this.')) return null;
  202. // In JS/TS/Python a bare identifier can never be a method value (methods
  203. // are only reachable through a receiver — `this.m` / `self.m` /
  204. // `Cls.m`), so bare fn-refs match FUNCTIONS only. This also sidesteps the
  205. // pre-existing TS quirk of class fields extracting as method-kind nodes,
  206. // which otherwise soaked up local names passed as arguments (excalidraw
  207. // A/B finding; same pattern in vendored docopt.py). Python's `self.m`
  208. // form keeps method targets via its own capture shape. C++ likewise: a
  209. // bare identifier can only be a FREE function (member values need
  210. // `&Cls::method`). PHP string callables name global FUNCTIONS (methods
  211. // need the `[$obj, 'm']` array form, which carries its own shape). Other
  212. // languages keep method targets: C# method groups, Swift/Dart
  213. // implicit-self, Java/Kotlin method references.
  214. const bareFnOnly =
  215. ref.language === 'typescript' || ref.language === 'tsx' ||
  216. ref.language === 'javascript' || ref.language === 'jsx' ||
  217. ref.language === 'arkts' ||
  218. ref.language === 'cpp' || ref.language === 'python' ||
  219. ref.language === 'php';
  220. // Python additionally accepts CLASS targets for bare identifiers (#1478):
  221. // class-as-value is a core Python idiom (`return SomeSerializer`,
  222. // `Meta.model = Org`, registry dicts, `admin.site.register(Model, Admin)`)
  223. // and, unlike TS, Python has no type-annotation recovery path. The
  224. // false-positive mechanism behind the function-only rule was lowercase
  225. // locals colliding with same-named METHODS (docopt.py) — a candidate must
  226. // be an exact-name CLASS node here, and the extraction gate (same-file
  227. // class ∪ imports) plus unique-or-drop still apply. Methods stay excluded.
  228. const bareClassOk = ref.language === 'python';
  229. // Qualified member-pointer (`&Widget::on_click` → "Widget::on_click"):
  230. // resolve the member ON THAT SCOPE — exempt from bareFnOnly (the `&Cls::m`
  231. // shape is an explicit member reference). Unique-or-drop like everything else.
  232. if (ref.referenceName.includes('::')) {
  233. const memberName = ref.referenceName.slice(ref.referenceName.lastIndexOf('::') + 2);
  234. const scoped = context
  235. .getNodesByName(memberName)
  236. .filter(
  237. (n) =>
  238. (n.kind === 'function' || n.kind === 'method') &&
  239. sameLanguageFamily(n.language, ref.language) &&
  240. n.id !== ref.fromNodeId &&
  241. (n.qualifiedName === ref.referenceName ||
  242. n.qualifiedName.endsWith(`::${ref.referenceName}`))
  243. );
  244. if (scoped.length === 0) return null;
  245. const sameFileScoped = scoped.filter((n) => n.filePath === ref.filePath);
  246. const pool = sameFileScoped.length > 0 ? sameFileScoped : scoped;
  247. if (sameFileScoped.length === 0 && scoped.length > 1) return null;
  248. const target = pool.reduce((a, b) => (a.startLine <= b.startLine ? a : b));
  249. return {
  250. original: ref,
  251. targetNodeId: target.id,
  252. confidence: 0.9,
  253. resolvedBy: 'function-ref',
  254. };
  255. }
  256. let candidates = context
  257. .getNodesByName(ref.referenceName)
  258. .filter(
  259. (n) =>
  260. (n.kind === 'function' ||
  261. (!bareFnOnly && n.kind === 'method') ||
  262. (bareClassOk && n.kind === 'class')) &&
  263. sameLanguageFamily(n.language, ref.language) &&
  264. n.id !== ref.fromNodeId // a function registering itself is not a dependency edge
  265. );
  266. if (candidates.length === 0) return null;
  267. // Swift implicit-self: a bare identifier can name a METHOD only of the
  268. // ENCLOSING type (`Button(action: handleTap)` written inside that type) —
  269. // a same-named method on any OTHER class is a parameter collision
  270. // (Alamofire: a `request` parameter resolving to EventMonitor::request).
  271. // Scope method candidates to the from-symbol's type; top-level code has no
  272. // implicit self, so method targets are excluded there entirely. Free
  273. // functions are unaffected.
  274. if (ref.language === 'swift' && candidates.some((n) => n.kind === 'method')) {
  275. const fromNode = context.getNodeById?.(ref.fromNodeId);
  276. const sep = fromNode ? fromNode.qualifiedName.lastIndexOf('::') : -1;
  277. const classPrefix = fromNode && sep > 0 ? fromNode.qualifiedName.slice(0, sep) : null;
  278. candidates = candidates.filter((n) => {
  279. if (n.kind !== 'method') return true;
  280. if (!classPrefix) return false;
  281. const mSep = n.qualifiedName.lastIndexOf('::');
  282. if (mSep <= 0) return false;
  283. const methodPrefix = n.qualifiedName.slice(0, mSep);
  284. // Accept exact-scope matches plus suffix relationships either way, so
  285. // extension-declared members (`Holder::m`) still match a nested
  286. // from-scope (`Module::Holder::wire`) and vice versa.
  287. return (
  288. methodPrefix === classPrefix ||
  289. methodPrefix.endsWith(`::${classPrefix}`) ||
  290. classPrefix.endsWith(`::${methodPrefix}`)
  291. );
  292. });
  293. if (candidates.length === 0) return null;
  294. }
  295. // Same-file definition wins — the extraction gate guarantees most survivors
  296. // have one, and it's the dominant C pattern (static callback registered in
  297. // a same-file ops struct).
  298. const sameFile = candidates.filter((n) => n.filePath === ref.filePath);
  299. if (sameFile.length > 0) {
  300. // Swift: several same-named METHODS in one file is an API overload family
  301. // (`Session.request(...)` × N), and a bare identifier hitting it is almost
  302. // always a same-named parameter, not a method value (Alamofire A/B
  303. // finding) — refuse rather than guess. A single method (SwiftUI's
  304. // `action: handleTap`) still resolves.
  305. if (
  306. ref.language === 'swift' &&
  307. sameFile.length > 1 &&
  308. sameFile.every((n) => n.kind === 'method')
  309. ) {
  310. return null;
  311. }
  312. // Same-name overloads in one file are the same conceptual symbol; pick
  313. // the first by position for determinism.
  314. const target = sameFile.reduce((a, b) => (a.startLine <= b.startLine ? a : b));
  315. return {
  316. original: ref,
  317. targetNodeId: target.id,
  318. confidence: sameFile.length === 1 ? 0.95 : 0.9,
  319. resolvedBy: 'function-ref',
  320. };
  321. }
  322. // Cross-file (imported names the import resolver didn't already claim):
  323. // only an unambiguous match resolves.
  324. if (candidates.length === 1) {
  325. return {
  326. original: ref,
  327. targetNodeId: candidates[0]!.id,
  328. confidence: 0.8,
  329. resolvedBy: 'function-ref',
  330. };
  331. }
  332. return null;
  333. }
  334. /**
  335. * A function nested inside another FUNCTION is only callable from within its
  336. * container — Python, JS/TS, and every closure language scope it lexically.
  337. * Resolving a bare name from elsewhere to a nested local fabricates an edge
  338. * scope already rules out: `join(...)` in one function must never bind to a
  339. * `join` defined inside a DIFFERENT function (#1230). A candidate whose
  340. * qualifiedName parent is a same-file function/method is kept only when the
  341. * ref originates inside that parent's line range. Class members are
  342. * unaffected (their parent resolves to a class-like node), as are top-level
  343. * symbols and C++ namespace-prefixed names (the prefix has no node).
  344. */
  345. function isLexicallyReachable(
  346. candidate: Node,
  347. ref: UnresolvedRef,
  348. context: ResolutionContext
  349. ): boolean {
  350. if (candidate.kind !== 'function') return true;
  351. const qn = candidate.qualifiedName;
  352. if (!qn || !qn.includes('::')) return true;
  353. const parentQn = qn.slice(0, qn.lastIndexOf('::'));
  354. const containers = context
  355. .getNodesByQualifiedName(parentQn)
  356. .filter(
  357. (p) =>
  358. p.filePath === candidate.filePath &&
  359. (p.kind === 'function' || p.kind === 'method') &&
  360. p.startLine <= candidate.startLine &&
  361. p.endLine >= candidate.endLine
  362. );
  363. if (containers.length === 0) return true;
  364. return (
  365. ref.filePath === candidate.filePath &&
  366. containers.some((p) => ref.line >= p.startLine && ref.line <= p.endLine)
  367. );
  368. }
  369. /**
  370. * Try to resolve a reference by exact name match
  371. */
  372. export function matchByExactName(
  373. ref: UnresolvedRef,
  374. context: ResolutionContext
  375. ): ResolvedRef | null {
  376. // `import`-kind nodes are import STATEMENTS, not definitions, so a reference
  377. // resolving to a sibling file's `import` is a meaningless edge — the real
  378. // import→definition resolution is the import resolver's job (resolveViaImport),
  379. // never name-matching here. Excluding them also removes a quadratic blow-up:
  380. // a ubiquitous package (`react`, `@superset-ui/core`, Python `logging`/`typing`)
  381. // is re-declared as an `import` node in every file that imports it, so K
  382. // unresolved import refs each scored K same-named import candidates through
  383. // findBestMatch — O(K²) per package, the dominant cost of "Resolving refs" on
  384. // large import-heavy (front-end + back-end) repos (#915).
  385. const candidates = applyLanguageGate(context.getNodesByName(ref.referenceName), ref)
  386. .filter((n) => n.kind !== 'import')
  387. // Nested locals are only reachable from inside their container (#1230).
  388. .filter((n) => isLexicallyReachable(n, ref, context));
  389. if (candidates.length === 0) {
  390. return null;
  391. }
  392. // If only one match, use it — but penalize cross-language matches
  393. if (candidates.length === 1) {
  394. const isCrossLanguage = candidates[0]!.language !== ref.language;
  395. return {
  396. original: ref,
  397. targetNodeId: candidates[0]!.id,
  398. confidence: isCrossLanguage ? 0.5 : 0.9,
  399. resolvedBy: 'exact-match',
  400. };
  401. }
  402. // Ubiquitous-name ceiling (#999): above it, picking one target among K
  403. // same-named defs by directory proximity is unreliable AND O(K) per ref — the
  404. // quadratic behind the "Resolving refs" wedge on theme/SDK-vendoring repos.
  405. // Decline; the precise strategies (qualified-name, import, class-name) already
  406. // ran. Falls through to fuzzy, which itself only resolves a UNIQUE candidate.
  407. if (candidates.length > AMBIGUOUS_NAME_CEILING) {
  408. return null;
  409. }
  410. // Multiple matches - try to narrow down
  411. const bestMatch = findBestMatch(ref, candidates, context);
  412. if (bestMatch) {
  413. // Lower confidence when the match is from a distant/unrelated module
  414. const proximity = computePathProximity(ref.filePath, bestMatch.filePath);
  415. const confidence = proximity >= 30 ? 0.7 : 0.4;
  416. return {
  417. original: ref,
  418. targetNodeId: bestMatch.id,
  419. confidence,
  420. resolvedBy: 'exact-match',
  421. };
  422. }
  423. return null;
  424. }
  425. /**
  426. * Try to resolve by qualified name
  427. */
  428. export function matchByQualifiedName(
  429. ref: UnresolvedRef,
  430. context: ResolutionContext
  431. ): ResolvedRef | null {
  432. // Check if the reference name looks qualified (contains :: or .)
  433. if (!ref.referenceName.includes('::') && !ref.referenceName.includes('.')) {
  434. return null;
  435. }
  436. // A method call `receiver.method()` can share an exact qualified name with a
  437. // config-file key: `service.process()` (a `calls` ref named `service.process`)
  438. // vs the yaml key `service.process`. Config keys are bound to their code refs
  439. // upstream by the framework resolvers (`@Value` → `references`); a `calls` ref
  440. // must never resolve to a yaml/properties config node — that's a wrong edge
  441. // AND it hides the real callee. Drop those from both the exact and the partial
  442. // candidate sets so resolution falls through to method resolution below (#1180).
  443. const keepForRef = (nodes: Node[]): Node[] =>
  444. ref.referenceKind === 'calls'
  445. ? nodes.filter(
  446. (n) => !(n.kind === 'constant' && (n.language === 'yaml' || n.language === 'properties')),
  447. )
  448. : nodes;
  449. const candidates = keepForRef(context.getNodesByQualifiedName(ref.referenceName));
  450. if (candidates.length === 1) {
  451. return {
  452. original: ref,
  453. targetNodeId: candidates[0]!.id,
  454. confidence: 0.95,
  455. resolvedBy: 'qualified-name',
  456. };
  457. }
  458. // Several symbols share this exact qualified name (e.g. `Logger::log` declared
  459. // in two files — an ODR clash or separate translation units): prefer the one
  460. // in the call site's own file before the partial-match fallback below, else
  461. // the first-indexed def wins and a call in `b/svc` targets `a/svc` (#1079).
  462. if (candidates.length > 1) {
  463. const ordered = preferCallSiteFile(candidates, ref.filePath);
  464. if (ordered[0]!.filePath === ref.filePath) {
  465. return {
  466. original: ref,
  467. targetNodeId: ordered[0]!.id,
  468. confidence: 0.95,
  469. resolvedBy: 'qualified-name',
  470. };
  471. }
  472. }
  473. // Try partial qualified name match — again preferring the call site's own
  474. // file when more than one symbol's qualifiedName ends with the reference.
  475. const parts = ref.referenceName.split(/[:.]/);
  476. const lastName = parts[parts.length - 1];
  477. if (lastName) {
  478. const partialCandidates = keepForRef(context.getNodesByName(lastName))
  479. .filter((candidate) => candidate.qualifiedName.endsWith(ref.referenceName));
  480. const chosen = preferCallSiteFile(partialCandidates, ref.filePath)[0];
  481. if (chosen) {
  482. return {
  483. original: ref,
  484. targetNodeId: chosen.id,
  485. confidence: 0.85,
  486. resolvedBy: 'qualified-name',
  487. };
  488. }
  489. }
  490. return null;
  491. }
  492. /**
  493. * When a symbol name is ambiguous across files, prefer the candidate(s) declared
  494. * in the call site's own file, keeping the rest in their original order (#1079).
  495. * A same-file definition is the strongest language-agnostic signal for which of
  496. * several same-named symbols a call means; without it, resolution collapses onto
  497. * whichever was indexed first, so a call in `b/svc` wrongly targets `a/svc`.
  498. * No-op when there are <2 candidates or none share the call site's file.
  499. */
  500. export function preferCallSiteFile(nodes: Node[], callSiteFile: string): Node[] {
  501. if (nodes.length < 2) return nodes;
  502. const same: Node[] = [];
  503. const other: Node[] = [];
  504. for (const n of nodes) {
  505. if (n.filePath === callSiteFile) same.push(n);
  506. else other.push(n);
  507. }
  508. return same.length ? [...same, ...other] : nodes;
  509. }
  510. /**
  511. * Languages whose object literals declare callable members — `export const
  512. * api = { call() {…}, get: () => {…} }` used as a namespace (#1573).
  513. */
  514. const OBJECT_LITERAL_LANGUAGES = new Set<string>(['typescript', 'tsx', 'javascript', 'jsx', 'arkts']);
  515. /** True when `inner`'s source range lies within `outer`'s (lines, then columns on a shared line). */
  516. function rangeWithin(inner: Node, outer: Node): boolean {
  517. const innerEnd = inner.endLine ?? inner.startLine;
  518. const outerEnd = outer.endLine ?? outer.startLine;
  519. if (inner.startLine < outer.startLine || innerEnd > outerEnd) return false;
  520. if (inner.startLine === outer.startLine && inner.startColumn < outer.startColumn) return false;
  521. if (innerEnd === outerEnd && inner.endColumn > outer.endColumn) return false;
  522. return true;
  523. }
  524. function sameRange(a: Node, b: Node): boolean {
  525. return (
  526. a.startLine === b.startLine &&
  527. a.startColumn === b.startColumn &&
  528. (a.endLine ?? a.startLine) === (b.endLine ?? b.startLine) &&
  529. a.endColumn === b.endColumn
  530. );
  531. }
  532. /**
  533. * Resolve `container.member` where `container` is a VALUE holding an object
  534. * literal — `export const api = { call() {…}, get: () => {…} }` used as the
  535. * module's namespace (#1573). The members are extracted as plain functions
  536. * with BARE qualified names inside the constant's source extent (there is no
  537. * `api::call`), so neither the `Container::member` lookup the class-shaped
  538. * kinds use (#825) nor the declared-type inference for singleton instances
  539. * (#1292) can reach them, and every such call resolved to nothing — or, via
  540. * an import, to the constant itself. This looks the member up by CONTAINMENT:
  541. * a node named `member` whose range lies inside the container's, in the
  542. * container's own file. A helper declared inside a member's body is not a
  543. * member and is skipped; nothing else in the file can donate a match. Calls
  544. * take callable kinds only; other references accept value members too.
  545. */
  546. export function resolveObjectLiteralMember(
  547. container: Node,
  548. member: string,
  549. ref: UnresolvedRef,
  550. context: ResolutionContext,
  551. confidence: number,
  552. resolvedBy: ResolvedRef['resolvedBy'],
  553. ): ResolvedRef | null {
  554. if (container.kind !== 'constant' && container.kind !== 'variable') return null;
  555. if (!OBJECT_LITERAL_LANGUAGES.has(container.language)) return null;
  556. if (!sameLanguageFamily(container.language, ref.language)) return null;
  557. const inFile = context.getNodesInFile(container.filePath);
  558. const callable = (n: Node) => n.kind === 'function' || n.kind === 'method';
  559. const valueMember = (n: Node) =>
  560. callable(n) || n.kind === 'property' || n.kind === 'variable' || n.kind === 'constant';
  561. const accepts = ref.referenceKind === 'calls' ? callable : valueMember;
  562. const inside = inFile.filter((n) => n.id !== container.id && rangeWithin(n, container));
  563. let candidates = inside.filter((n) => n.name === member && accepts(n));
  564. if (candidates.length === 0) return null;
  565. // Drop a candidate nested inside ANOTHER callable's body within the literal
  566. // (`{ run() { const call = () => {}; } }` — `call` is `run`'s local, not a
  567. // member). Strict containment: an identically-ranged sibling node for the
  568. // same member (a property node over an arrow function) is not a body.
  569. const bodies = inside.filter(callable);
  570. candidates = candidates.filter(
  571. (c) => !bodies.some((b) => b.id !== c.id && !sameRange(b, c) && rangeWithin(c, b))
  572. );
  573. if (candidates.length === 0) return null;
  574. // Several survivors (a property AND a function for one arrow member, say):
  575. // a callable first, then the earliest in source order.
  576. candidates.sort((a, b) => {
  577. const ca = callable(a) ? 0 : 1;
  578. const cb = callable(b) ? 0 : 1;
  579. if (ca !== cb) return ca - cb;
  580. return a.startLine - b.startLine || a.startColumn - b.startColumn;
  581. });
  582. return {
  583. original: ref,
  584. targetNodeId: candidates[0]!.id,
  585. confidence,
  586. resolvedBy,
  587. };
  588. }
  589. // Exported for the precedence unit tests (#1079): they assert the
  590. // preferredFqn → same-file → matches[0] ordering directly.
  591. export function resolveMethodOnType(
  592. typeName: string,
  593. methodName: string,
  594. ref: UnresolvedRef,
  595. context: ResolutionContext,
  596. confidence: number,
  597. resolvedBy: ResolvedRef['resolvedBy'],
  598. /**
  599. * Optional FQN that identifies WHICH class declaration `typeName`
  600. * refers to in the caller's file. When multiple candidates share
  601. * the same qualifiedName (`FooConverter::convert` in both
  602. * `dao/converter/` and `service/converter/`), the FQN's
  603. * file-path-suffix picks the right one — the disambiguation
  604. * signal Java imports carry but the call site doesn't (#314).
  605. */
  606. preferredFqn?: string,
  607. /** Recursion guard for the supertype/conformance walk. */
  608. depth = 0,
  609. ): ResolvedRef | null {
  610. // Look up methods by name and match by qualifiedName ending in
  611. // `<typeName>::<methodName>`. This works whether the method is defined
  612. // in-class (`class Foo { int bar() { ... } }`) or out-of-line in a separate
  613. // file (`int Foo::bar() { ... }` in foo.cpp while class Foo is in foo.hpp).
  614. // The previous same-file approach missed the latter — the typical C++ layout.
  615. // Prefer the context's per-(type, method) memo: the raw name lookup fetches
  616. // EVERY node sharing the method name — tens of thousands of rows for a
  617. // collision-heavy Java name like `execute` — and re-filtering that per ref
  618. // was a dominant term in the #1122 watchdog kill on large repos. Only the
  619. // ref-independent filter is memoized; per-ref disambiguation stays below.
  620. let matches: Node[];
  621. if (context.getMethodMatches) {
  622. matches = context.getMethodMatches(typeName, methodName, ref.language);
  623. } else {
  624. const methodCandidates = context.getNodesByName(methodName);
  625. const want = `${typeName}::${methodName}`;
  626. matches = [];
  627. for (const m of methodCandidates) {
  628. if (m.kind !== 'method') continue;
  629. if (m.language !== ref.language) continue;
  630. const qn = m.qualifiedName;
  631. if (qn === want || qn.endsWith(`::${want}`)) {
  632. matches.push(m);
  633. }
  634. }
  635. }
  636. if (matches.length === 0) {
  637. // Conformance fallback: the method may be defined on a supertype `typeName`
  638. // extends, or on a protocol / trait it conforms to (e.g. a Swift protocol-
  639. // extension method, a C# default-interface or extension method, a Kotlin
  640. // extension on a supertype). Walk supertypes transitively (depth-capped) via
  641. // the resolved implements/extends edges — empty in the first resolution pass,
  642. // populated in the conformance pass. Still VALIDATED (the method must exist on
  643. // a supertype), so a wrong inference produces no edge.
  644. if (depth < 4 && context.getSupertypes) {
  645. const viaSupers = nmTimedT('rmot-supers', ref, (): ResolvedRef | null => {
  646. for (const supertype of context.getSupertypes!(typeName, ref.language)) {
  647. const via = resolveMethodOnType(
  648. supertype, methodName, ref, context, confidence, resolvedBy, preferredFqn, depth + 1,
  649. );
  650. if (via) return via;
  651. }
  652. return null;
  653. });
  654. if (viaSupers) return viaSupers;
  655. }
  656. return null;
  657. }
  658. if (matches.length > 1 && preferredFqn) {
  659. const ext = ref.language === 'kotlin' ? '.kt' : '.java';
  660. const fqnPath = preferredFqn.replace(/\./g, '/') + ext;
  661. const chosen = matches.find((m) => {
  662. const fp = m.filePath.replace(/\\/g, '/');
  663. return fp.endsWith(fqnPath) || fp.endsWith('/' + fqnPath);
  664. });
  665. if (chosen) {
  666. return {
  667. original: ref,
  668. targetNodeId: chosen.id,
  669. confidence,
  670. resolvedBy,
  671. };
  672. }
  673. }
  674. // Language-agnostic disambiguation: when several same-named methods survive
  675. // (e.g. two files each declaring `class Logger { void log(); }` — an ODR
  676. // clash, an anonymous-namespace type, or separate translation units), prefer
  677. // the definition in the CALL SITE's own file. Without this, every ambiguous
  678. // call collapses onto the first-indexed definition, so a call in `b/svc.cpp`
  679. // wrongly points at `a/svc.cpp` (#1079). This runs AFTER the `preferredFqn`
  680. // block, so Java/Kotlin import disambiguation — whose target is intentionally
  681. // in ANOTHER file (#314) — is unaffected: that block returns early whenever
  682. // an import FQN pins the class.
  683. const ordered = preferCallSiteFile(matches, ref.filePath);
  684. return {
  685. original: ref,
  686. targetNodeId: ordered[0]!.id,
  687. confidence,
  688. resolvedBy,
  689. };
  690. }
  691. // C++ keywords/control-flow tokens that can appear right before a receiver
  692. // (e.g. `return ptr->m()`) and must NOT be treated as a type.
  693. const CPP_NON_TYPE_TOKENS = new Set([
  694. 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
  695. 'break', 'continue', 'goto', 'throw', 'new', 'delete', 'co_await', 'co_yield',
  696. 'co_return', 'static_cast', 'const_cast', 'dynamic_cast', 'reinterpret_cast',
  697. 'sizeof', 'alignof', 'typeid', 'and', 'or', 'not', 'xor',
  698. ]);
  699. function normalizeCppTypeName(typeName: string): string | null {
  700. const normalized = typeName
  701. .replace(/\b(const|volatile|mutable|typename|class|struct)\b/g, ' ')
  702. .replace(/[&*]+/g, ' ')
  703. .replace(/<[^>]*>/g, ' ')
  704. .replace(/\s+/g, ' ')
  705. .trim();
  706. if (!normalized) return null;
  707. const parts = normalized.split(/::/).filter(Boolean);
  708. const last = parts[parts.length - 1];
  709. if (!last) return null;
  710. if (CPP_NON_TYPE_TOKENS.has(last)) return null;
  711. return last;
  712. }
  713. // Declarator regex: matches `Type receiver`, `Type* receiver`, `Type *receiver`,
  714. // `Type*receiver`, `Type<X> receiver`, etc., REQUIRING a declarator terminator
  715. // (`;`, `=`, `,`, `)`, `[`, `{`, `(`, or end-of-line) after the receiver. The
  716. // terminator rules out uses like `return receiver->m()` where the preceding
  717. // token is a keyword, not a type.
  718. function buildDeclaratorRegex(escapedReceiver: string): RegExp {
  719. return new RegExp(
  720. `([A-Za-z_][\\w:]*(?:\\s*<[^;=(){}]+>)?(?:\\s*[*&]+)?)\\s*\\b${escapedReceiver}\\b\\s*(?=[;=,)\\[{(]|$)`,
  721. );
  722. }
  723. function inferCppReceiverType(
  724. receiverName: string,
  725. ref: UnresolvedRef,
  726. context: ResolutionContext,
  727. depth = 0,
  728. ): string | null {
  729. // Per-file lines cache when available — this runs per `receiver->method()`
  730. // ref and re-splitting the file each time is the same quadratic as the
  731. // shared inferrer's (#1122).
  732. const lines = context.getFileLines
  733. ? context.getFileLines(ref.filePath)
  734. : (context.readFile(ref.filePath)?.split(/\r?\n/) ?? null);
  735. if (!lines || lines.length === 0) return null;
  736. const callLineIndex = Math.max(0, Math.min(lines.length - 1, ref.line - 1));
  737. const escapedReceiver = receiverName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  738. const receiverPattern = new RegExp(`\\b${escapedReceiver}\\b`);
  739. const declaratorRegex = buildDeclaratorRegex(escapedReceiver);
  740. for (let i = callLineIndex; i >= 0; i--) {
  741. const line = lines[i];
  742. if (!line || !receiverPattern.test(line)) continue;
  743. const declaratorMatch = line.match(declaratorRegex);
  744. if (declaratorMatch) {
  745. const normalized = normalizeCppTypeName(declaratorMatch[1] ?? '');
  746. if (normalized === 'auto') {
  747. // `auto x = Foo::instance();` — the declared type is deduced; recover it
  748. // from the initializer (call return type / construction) (#645).
  749. const initType = inferCppAutoInitializerType(line, receiverName, ref, context, depth);
  750. if (initType) return initType;
  751. // No usable initializer on this line — keep scanning earlier ones.
  752. } else if (normalized) {
  753. return normalized;
  754. }
  755. }
  756. }
  757. const headerCandidates = [
  758. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.h'),
  759. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.hpp'),
  760. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.hxx'),
  761. ].filter((candidate, index, arr) => arr.indexOf(candidate) === index && candidate !== ref.filePath);
  762. for (const headerPath of headerCandidates) {
  763. if (!context.fileExists(headerPath)) continue;
  764. const headerLines = context.getFileLines
  765. ? context.getFileLines(headerPath)
  766. : (context.readFile(headerPath)?.split(/\r?\n/) ?? null);
  767. if (!headerLines) continue;
  768. for (const line of headerLines) {
  769. if (!receiverPattern.test(line)) continue;
  770. const declaratorMatch = line.match(declaratorRegex);
  771. if (!declaratorMatch) continue;
  772. const normalized = normalizeCppTypeName(declaratorMatch[1] ?? '');
  773. if (normalized && normalized !== 'auto') return normalized;
  774. }
  775. }
  776. return null;
  777. }
  778. /**
  779. * Last `::`-separated segment of a (possibly namespace-qualified) C++ name.
  780. */
  781. function cppLastSegment(name: string): string {
  782. const parts = name.split('::').filter(Boolean);
  783. return parts[parts.length - 1] ?? name;
  784. }
  785. /**
  786. * Return type captured at extraction for `Class::method` (or a free function),
  787. * read off the indexed node's `returnType` — used by the C++ (#645) and PHP
  788. * (#608) chained-call resolvers. Language-filtered. Null when not indexed or no
  789. * return type was recorded (a `void`/primitive return).
  790. */
  791. function lookupCalleeReturnType(
  792. callee: string,
  793. ref: UnresolvedRef,
  794. context: ResolutionContext,
  795. ): string | null {
  796. let method = callee;
  797. let cls: string | null = null;
  798. if (callee.includes('::')) {
  799. const parts = callee.split('::').filter(Boolean);
  800. method = parts[parts.length - 1] ?? callee;
  801. cls = parts.slice(0, -1).join('::');
  802. }
  803. const candidates = context.getNodesByName(method).filter(
  804. (n) =>
  805. (n.kind === 'method' || n.kind === 'function') &&
  806. n.language === ref.language &&
  807. !!n.returnType,
  808. );
  809. if (cls) {
  810. const want = `${cls}::${method}`;
  811. // The call site may name the class with MORE namespace qualification than
  812. // the stored node (`details::registry::instance` at the call vs
  813. // `registry::instance` on the node — the receiver type only carries the
  814. // immediate class), or LESS. Accept an exact match or either being a
  815. // namespace-suffix of the other; the shared `::<class>::<method>` tail keeps
  816. // it specific.
  817. const m = candidates.find(
  818. (n) =>
  819. n.qualifiedName === want ||
  820. n.qualifiedName.endsWith(`::${want}`) ||
  821. want.endsWith(`::${n.qualifiedName}`),
  822. );
  823. return m?.returnType ?? null;
  824. }
  825. return candidates.find((n) => n.kind === 'function')?.returnType ?? null;
  826. }
  827. /** Does the graph contain an aggregate type named `name`'s last segment? */
  828. function cppClassExists(name: string, ref: UnresolvedRef, context: ResolutionContext): boolean {
  829. const last = cppLastSegment(name);
  830. return context
  831. .getNodesByName(last)
  832. .some((n) => (n.kind === 'class' || n.kind === 'struct' || n.kind === 'union') && n.language === ref.language);
  833. }
  834. /**
  835. * Infer the class produced by a C++ call/construction expression, using return
  836. * types captured at extraction (#645). Handles, in order:
  837. * - `make_unique<T>()` / `make_shared<T>()` → T
  838. * - single-level member call `recv.method()` → recv's type, then method's return
  839. * - `Class::method()` / free `func()` → the callee's recorded return type
  840. * - direct construction `Type()` / `ns::Type()` → Type
  841. * Returns null when undeterminable. Callers MUST still validate the outer method
  842. * exists on the result before creating an edge, so a wrong guess stays silent.
  843. */
  844. function resolveCppCallResultType(
  845. inner: string,
  846. ref: UnresolvedRef,
  847. context: ResolutionContext,
  848. depth = 0,
  849. ): string | null {
  850. if (depth > 3) return null; // guard against pathological mutual recursion
  851. const expr = inner.trim();
  852. const make = expr.match(/(?:^|::)(?:make_unique|make_shared)\s*<\s*([A-Za-z_]\w*)/);
  853. if (make) return make[1] ?? null;
  854. // Single-level member call `recv.method` (the `manager.view().render()` shape).
  855. const dotIdx = expr.lastIndexOf('.');
  856. if (dotIdx > 0) {
  857. const recv = expr.slice(0, dotIdx);
  858. const method = expr.slice(dotIdx + 1);
  859. if (recv.includes('.') || recv.includes('(') || recv.includes('::')) return null; // single level only
  860. const recvType = inferCppReceiverType(recv, ref, context, depth + 1);
  861. if (!recvType) return null;
  862. return lookupCalleeReturnType(`${recvType}::${method}`, ref, context);
  863. }
  864. const ret = lookupCalleeReturnType(expr, ref, context);
  865. if (ret) return ret;
  866. // Direct construction — the callee itself names a class/struct.
  867. if (cppClassExists(expr, ref, context)) return cppLastSegment(expr);
  868. return null;
  869. }
  870. /**
  871. * Recover the type of an `auto`-declared local from its initializer on the
  872. * declaration line — `auto x = Foo::instance();`, `auto w = make_unique<W>();`,
  873. * `auto p = new W();`, `auto w = Widget();` (#645).
  874. */
  875. function inferCppAutoInitializerType(
  876. line: string,
  877. receiverName: string,
  878. ref: UnresolvedRef,
  879. context: ResolutionContext,
  880. depth: number,
  881. ): string | null {
  882. const escaped = receiverName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  883. const m = line.match(new RegExp(`\\b${escaped}\\b\\s*=\\s*([^;]+)`));
  884. if (!m || !m[1]) return null;
  885. const init = m[1].trim();
  886. const neu = init.match(/^new\s+([A-Za-z_][\w:]*)/);
  887. if (neu && neu[1]) return cppLastSegment(neu[1]);
  888. // A call or construction: `Foo(...)`, `A::b(...)`, `make_unique<T>(...)`.
  889. const call = init.match(/^([A-Za-z_][\w:]*(?:\s*<[^>;]*>)?)\s*\(/);
  890. if (call && call[1]) return resolveCppCallResultType(call[1].replace(/\s+/g, ''), ref, context, depth + 1);
  891. return null;
  892. }
  893. /**
  894. * Resolve a C++ chained call whose receiver is itself a call — encoded by the
  895. * extractor as `<innerCallee>().<method>` (#645). The receiver's type is what
  896. * the inner call returns; the outer method is then resolved and VALIDATED on it
  897. * (resolveMethodOnType requires `cls::method` to exist), so a wrong inference
  898. * produces no edge rather than a wrong one.
  899. */
  900. export function matchCppCallChain(
  901. ref: UnresolvedRef,
  902. context: ResolutionContext,
  903. ): ResolvedRef | null {
  904. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  905. if (!m || !m[1] || !m[2]) return null;
  906. const cls = resolveCppCallResultType(m[1], ref, context);
  907. if (!cls) return null;
  908. return resolveMethodOnType(cls, m[2], ref, context, 0.85, 'instance-method');
  909. }
  910. /**
  911. * Resolve a `::`-scoped factory chain whose receiver is a scoped/static call —
  912. * PHP `Cls::for($x)->method()` (#608, the per-credential Laravel client idiom) or
  913. * Rust `Foo::new().bar()` (an associated-function call) — both encoded by the
  914. * extractor as `Cls::factory().method`. The receiver's type is what `Cls::factory`
  915. * returns: a `self` marker (PHP `: self`/`: static`, Rust `-> Self`) resolves to
  916. * the factory's own type, a concrete return type to that type. The outer method is
  917. * then resolved and VALIDATED on it (resolveMethodOnType requires the method to
  918. * exist on the type or a supertype it conforms to), so a wrong inference yields no
  919. * edge rather than a wrong one. Shared by the `::`-receiver languages (PHP, Rust).
  920. */
  921. export function matchScopedCallChain(
  922. ref: UnresolvedRef,
  923. context: ResolutionContext,
  924. ): ResolvedRef | null {
  925. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  926. if (!m || !m[1] || !m[2]) return null;
  927. const inner = m[1];
  928. const method = m[2];
  929. if (!inner.includes('::')) return null; // only static-factory (`Cls::method`) chains
  930. const factoryClass = inner.slice(0, inner.lastIndexOf('::'));
  931. const ret = lookupCalleeReturnType(inner, ref, context);
  932. if (!ret) return null;
  933. // `self` (the extractor's marker for self/static/$this) → the factory's class.
  934. const resolvedClass = ret === 'self' ? factoryClass : ret;
  935. return resolveMethodOnType(resolvedClass, method, ref, context, 0.85, 'instance-method');
  936. }
  937. /**
  938. * Languages where an unprefixed capitalized call `Foo(args)` constructs the
  939. * class (so a `Foo(args).method()` receiver's type is `Foo`). Java/C# need `new`,
  940. * so a bare `Foo()` there is a method call, not construction — excluded. Scala's
  941. * `Foo(args)` is a case-class / companion `apply`, which conventionally returns
  942. * `Foo` — and resolveMethodOnType validates, so a non-conventional `apply` that
  943. * returns another type simply yields no edge rather than a wrong one. Pascal/Delphi:
  944. * a `TFoo(x)` is a TYPECAST whose result is a `TFoo`, so `TFoo(x).method()` resolves
  945. * the method on `TFoo` — same shape, same validation.
  946. */
  947. const CONSTRUCTS_VIA_BARE_CALL = new Set(['kotlin', 'swift', 'scala', 'dart', 'pascal']);
  948. /**
  949. * Resolve a dotted chained call whose receiver is a static factory / fluent call —
  950. * `Foo.getInstance().bar()`, encoded by the extractor as `Foo.getInstance().bar`
  951. * (#645/#608 mechanism). The receiver's type is what `Foo.getInstance` returns
  952. * (its declared return type); the outer method is then resolved and VALIDATED on
  953. * it (resolveMethodOnType requires `Type::method` to exist), so a wrong inference
  954. * yields no edge rather than a wrong one (e.g. a same-named `bar()` on an
  955. * unrelated class is never matched). Shared by the dot-notation languages
  956. * (Java, Kotlin, C#, Swift) — same receiver shape, same `Class::method` qualified names.
  957. */
  958. export function matchDottedCallChain(
  959. ref: UnresolvedRef,
  960. context: ResolutionContext,
  961. ): ResolvedRef | null {
  962. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  963. if (!m || !m[1] || !m[2]) return null;
  964. const inner = m[1]; // `Foo.getInstance`
  965. const method = m[2]; // `bar`
  966. const lastDot = inner.lastIndexOf('.');
  967. if (lastDot <= 0) {
  968. // Go: bare package-level factory FUNCTION `New().method()` — the receiver's
  969. // type is what `New` returns; resolve the method on that.
  970. if (ref.language === 'go') {
  971. const ret = lookupCalleeReturnType(inner, ref, context);
  972. if (ret) {
  973. return resolveMethodOnType(ret, method, ref, context, 0.85, 'instance-method', importedFqnOf(ret, ref, context));
  974. }
  975. // `inner` isn't a function with a captured return type — typically a
  976. // package-level VARIABLE holding a function value (e.g. gin's `engine()`),
  977. // whose type we can't recover. Fall back to bare-name resolution of the
  978. // method so we don't DROP an edge the un-re-encoded bare path would have
  979. // found. (When `inner` IS a real factory function but the method doesn't
  980. // exist on its return type, `ret` is truthy and we returned no edge above —
  981. // the absent-method safety guarantee is preserved.)
  982. //
  983. // CRITICAL: resolve the TARGET via a synthetic bare-name ref, but return the
  984. // match tied to the ORIGINAL `ref` (referenceName `inner().method`). The
  985. // batched resolver (resolveAndPersistBatched) reads unresolved rows from
  986. // offset 0 every pass and relies on the post-batch cleanup (row-id delete
  987. // for DB-loaded refs, referenceName-keyed delete otherwise, #1269) to
  988. // clear each resolved row so the batch empties. If we propagated the
  989. // synthetic ref's bare `method` as `.original`, a key-based delete
  990. // would never match the stored `inner().method` row, the batch would
  991. // never drain, and the loop would re-resolve + re-insert forever (a runaway
  992. // that grew gin's graph to 5M edges / 1.4 GB before this fix).
  993. const bareRef = { ...ref, referenceName: method };
  994. const bareMatch = matchByExactName(bareRef, context) ?? matchFuzzy(bareRef, context);
  995. return bareMatch ? { ...bareMatch, original: ref } : null;
  996. }
  997. // Constructor receiver `Foo(args).method()` (encoded `Foo().method`): a bare,
  998. // capitalized inner is a class construction, so the receiver's type is the
  999. // class itself — resolve the method on it. Only in languages where an
  1000. // unprefixed capitalized call constructs the class (Kotlin, Swift); in Java/C#
  1001. // a bare `Foo()` is a method call (constructors need `new`), so we must not
  1002. // assume construction. A lowercase bare inner is a top-level `factory().method()`
  1003. // whose type we can't recover — bail.
  1004. if (!CONSTRUCTS_VIA_BARE_CALL.has(ref.language) || !/^[A-Z]/.test(inner)) return null;
  1005. return resolveMethodOnType(inner, method, ref, context, 0.85, 'instance-method', importedFqnOf(inner, ref, context));
  1006. }
  1007. // Factory/fluent receiver `Receiver.factory(args).method()`: the receiver's
  1008. // type is what `Receiver.factory` returns (its declared return type).
  1009. const factoryClass = inner.slice(0, lastDot).split('.').pop(); // simple class name
  1010. const factoryMethod = inner.slice(lastDot + 1);
  1011. if (!factoryClass || !factoryMethod) return null;
  1012. const ret = lookupCalleeReturnType(`${factoryClass}::${factoryMethod}`, ref, context);
  1013. if (!ret) {
  1014. // Objective-C: a class-message factory — `[X alloc]`, `[X new]`,
  1015. // `[X sharedFoo]` — returns an instance of the RECEIVER class `X` by
  1016. // convention (`instancetype`). So when the factory's own return type isn't
  1017. // recoverable (its selector returns `instancetype`, or `alloc`/`new` aren't
  1018. // user-defined nodes at all), the receiver's type is the class `X` itself.
  1019. // This resolves the ubiquitous `[[X alloc] init]` and singleton chains.
  1020. // resolveMethodOnType validates against X (and its supertypes), so a class
  1021. // whose method actually lives elsewhere yields NO edge, not a wrong one — and
  1022. // crucially this does NOT fire when a concrete return type WAS captured but
  1023. // simply lacks the method (that already returned null above: absent-method
  1024. // safety, so a same-named decoy is still never matched).
  1025. if (ref.language === 'objc' && /^[A-Z]/.test(factoryClass)) {
  1026. return resolveMethodOnType(factoryClass, method, ref, context, 0.8, 'instance-method', importedFqnOf(factoryClass, ref, context));
  1027. }
  1028. // Pascal/Delphi: the extractor only re-encodes a `TFoo`/`IFoo`-prefixed chain
  1029. // (the type-naming convention), so `factoryClass` is always a real class here.
  1030. // A factory whose return type wasn't captured is a CONSTRUCTOR
  1031. // (`TFileMem.Create().SetCachePerformance` — `constructor Create` has no `:
  1032. // TBar` annotation but returns its own class) or an unannotated function. In
  1033. // both cases the receiver's type is the class itself, so resolve the method on
  1034. // `factoryClass`. resolveMethodOnType validates against it (and its
  1035. // supertypes), so a wrong inference yields no edge — and this never fires when
  1036. // a return type WAS captured but lacks the method (absent-method safety above).
  1037. if (ref.language === 'pascal' && /^[TI]/.test(factoryClass)) {
  1038. return resolveMethodOnType(factoryClass, method, ref, context, 0.8, 'instance-method', importedFqnOf(factoryClass, ref, context));
  1039. }
  1040. return null;
  1041. }
  1042. return resolveMethodOnType(ret, method, ref, context, 0.85, 'instance-method', importedFqnOf(ret, ref, context));
  1043. }
  1044. /**
  1045. * When several classes share a simple type name, the caller file's import of
  1046. * that type is the only signal that names WHICH one (#314). Returns the imported
  1047. * FQN for `typeName` in the ref's file, or undefined.
  1048. */
  1049. function importedFqnOf(
  1050. typeName: string,
  1051. ref: UnresolvedRef,
  1052. context: ResolutionContext,
  1053. ): string | undefined {
  1054. const imports = context.getImportMappings(ref.filePath, ref.language);
  1055. return imports.find((i) => i.localName === typeName)?.source;
  1056. }
  1057. /**
  1058. * Java/Kotlin: infer a receiver's declared type by walking field declarations
  1059. * in the class enclosing the call site. The field's `signature` is already in
  1060. * the form "<TypeName> <fieldName>" (set by tree-sitter.ts extractField), so we
  1061. * pull the type from there. Handles Spring `@Resource UserBO userbo;` /
  1062. * `@Autowired private UserService userService;` where the receiver field name
  1063. * doesn't match the class name by Java naming convention.
  1064. *
  1065. * Returns the bare type name (generics stripped, dotted package stripped) or
  1066. * null when no matching field is in the enclosing class.
  1067. */
  1068. function inferJavaFieldReceiverType(
  1069. receiverName: string,
  1070. ref: UnresolvedRef,
  1071. context: ResolutionContext,
  1072. ): string | null {
  1073. const inFile = context.getNodesInFile(ref.filePath);
  1074. if (inFile.length === 0) return null;
  1075. // Find the class enclosing the call line (tightest match by latest start).
  1076. let enclosing: Node | null = null;
  1077. for (const n of inFile) {
  1078. if (n.kind !== 'class' && n.kind !== 'interface') continue;
  1079. if (n.language !== ref.language) continue;
  1080. const end = n.endLine ?? n.startLine;
  1081. if (n.startLine <= ref.line && end >= ref.line) {
  1082. if (!enclosing || n.startLine >= enclosing.startLine) enclosing = n;
  1083. }
  1084. }
  1085. if (!enclosing) return null;
  1086. const enclosingEnd = enclosing.endLine ?? enclosing.startLine;
  1087. const field = inFile.find(
  1088. (n) =>
  1089. n.kind === 'field' &&
  1090. n.name === receiverName &&
  1091. n.language === ref.language &&
  1092. n.startLine >= enclosing.startLine &&
  1093. (n.endLine ?? n.startLine) <= enclosingEnd,
  1094. );
  1095. if (!field || !field.signature) return null;
  1096. // Signature shape: "<TypeName> <fieldName>" (extractField). Pull the type,
  1097. // strip generics + dotted package, drop array/varargs markers.
  1098. const beforeName = field.signature.slice(
  1099. 0,
  1100. field.signature.lastIndexOf(field.name),
  1101. );
  1102. const typeRaw = beforeName.trim();
  1103. if (!typeRaw) return null;
  1104. const typeNoGenerics = typeRaw.replace(/<[^>]*>/g, '').trim();
  1105. const typeNoArray = typeNoGenerics.replace(/\[\s*\]/g, '').replace(/\.\.\.$/, '').trim();
  1106. const parts = typeNoArray.split(/[.\s]+/).filter(Boolean);
  1107. const lastPart = parts[parts.length - 1];
  1108. if (!lastPart) return null;
  1109. if (!/^[A-Z]/.test(lastPart)) return null; // primitives / lowercase → skip
  1110. return lastPart;
  1111. }
  1112. // ── Local-variable receiver-type inference (#1108) ──────────────────────────
  1113. //
  1114. // Instance calls through a local variable (`const lg = new Logger(); lg.log()`)
  1115. // only resolved in C++ before this — no other language could learn the
  1116. // receiver's type. Local variables are not indexed as nodes (node-explosion),
  1117. // so, like the C++ inferrer above, we read the enclosing function's source and
  1118. // match the receiver's declaration/initializer to recover its type. The type is
  1119. // then handed to resolveMethodOnType, which VALIDATES that the type actually
  1120. // declares the method, so a mis-inference produces NO edge — the safety net
  1121. // that lets the patterns below stay simple. C++ keeps its dedicated inferrer
  1122. // (header scan + `auto`); this covers every other language.
  1123. // Tokens a loose pattern might capture that are never a user-defined type.
  1124. const NON_TYPE_RECEIVER_TOKENS = new Set([
  1125. 'this', 'self', 'super', 'new', 'return', 'await', 'yield', 'typeof',
  1126. 'null', 'nil', 'None', 'true', 'false', 'True', 'False', 'undefined',
  1127. ]);
  1128. /**
  1129. * Normalize a captured type expression to a simple type name: drop generic
  1130. * args and pointer/ref markers, take the last `.`/`::`-qualified segment, and
  1131. * reject obvious non-types.
  1132. */
  1133. export function normalizeInferredTypeName(raw: string): string | null {
  1134. const cleaned = raw.replace(/<[^>]*>/g, '').replace(/[&*]/g, '').trim();
  1135. const seg = cleaned.split(/[.:]+/).filter(Boolean).pop();
  1136. if (!seg) return null;
  1137. if (NON_TYPE_RECEIVER_TOKENS.has(seg)) return null;
  1138. return seg;
  1139. }
  1140. /**
  1141. * Per-language patterns that recover a local variable's (or typed parameter's)
  1142. * type from its declaration/initializer. Each regex captures the type in group
  1143. * 1; `r` is the already-escaped receiver name. Ordered most-specific first.
  1144. * PascalCase is required in the capture where the language convention allows,
  1145. * as a cheap false-positive guard on top of resolveMethodOnType's validation.
  1146. */
  1147. /**
  1148. * Compiled-pattern memo for the receiver-type pattern builders below. They
  1149. * run for EVERY `receiver.method()` ref the matcher attempts, compiling 2–4
  1150. * fresh RegExp objects per call — and receivers repeat massively (`self`
  1151. * alone accounts for tens of thousands of refs on a Lua repo, measured 41µs
  1152. * per methodCall miss on kong with compilation a large slice). The patterns
  1153. * are a pure function of (language, receiver) and non-global (`.match()`
  1154. * never touches lastIndex), so shared instances are behavior-identical.
  1155. * FIFO-capped with no per-get mutation (the §7a.6 LRU-churn lesson): a hit
  1156. * costs one Map lookup, overflow evicts oldest, and an evicted entry simply
  1157. * recompiles exactly as every call did before this memo.
  1158. */
  1159. const PATTERN_MEMO = new Map<string, RegExp[]>();
  1160. const PATTERN_MEMO_CAP = 8192;
  1161. /**
  1162. * Per-context incremental receiver-scan states for inferLocalReceiverType
  1163. * (see the memo comment there). Keyed (file, scopeStart, language, receiver);
  1164. * entries are a few dozen bytes, count is bounded by distinct receiver uses
  1165. * (same order as the context's other per-file caches). MUST drop whenever the
  1166. * context's file caches drop — the states are derived from file lines — so
  1167. * ReferenceResolver.clearCaches calls clearNameMatcherMemos alongside
  1168. * clearImportResolverMemos.
  1169. */
  1170. type InferScanState = { hi: number; ansIdx: number; ansType: string | null };
  1171. const INFER_SCAN_STATES = new WeakMap<ResolutionContext, Map<string, InferScanState>>();
  1172. function getInferScanStates(context: ResolutionContext): Map<string, InferScanState> {
  1173. let m = INFER_SCAN_STATES.get(context);
  1174. if (!m) {
  1175. m = new Map();
  1176. INFER_SCAN_STATES.set(context, m);
  1177. }
  1178. return m;
  1179. }
  1180. /** Drop the per-context scan states (see ReferenceResolver.clearCaches). */
  1181. export function clearNameMatcherMemos(context: ResolutionContext): void {
  1182. INFER_SCAN_STATES.delete(context);
  1183. }
  1184. function memoPatterns(key: string, build: () => RegExp[]): RegExp[] {
  1185. const hit = PATTERN_MEMO.get(key);
  1186. if (hit) return hit;
  1187. const patterns = build();
  1188. if (PATTERN_MEMO.size >= PATTERN_MEMO_CAP) {
  1189. const oldest = PATTERN_MEMO.keys().next().value;
  1190. if (oldest !== undefined) PATTERN_MEMO.delete(oldest);
  1191. }
  1192. PATTERN_MEMO.set(key, patterns);
  1193. return patterns;
  1194. }
  1195. export function localReceiverTypePatterns(language: Language, r: string): RegExp[] {
  1196. return memoPatterns(`${language}|${r}`, () => buildLocalReceiverTypePatterns(language, r));
  1197. }
  1198. function buildLocalReceiverTypePatterns(language: Language, r: string): RegExp[] {
  1199. switch (language) {
  1200. case 'typescript':
  1201. case 'javascript':
  1202. case 'tsx':
  1203. case 'jsx':
  1204. case 'arkts':
  1205. return [
  1206. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_$][\\w.$]*)`), // = new Logger()
  1207. // No keyword requirement, so this matches BOTH a local annotation
  1208. // (`const lg: Logger`) and a typed parameter (`function use(lg: Logger)`
  1209. // / `(lg: Logger) =>`) — the parameter case the old `const|let|var`
  1210. // prefix excluded (#1125). Mirrors Kotlin/Swift/Scala; the capture stops
  1211. // at `<` so a generic-typed param (`repo: Repository<User>`) still yields
  1212. // `Repository`. resolveMethodOnType validates the type actually declares
  1213. // the method, so the looser match produces no edge on a mis-inference.
  1214. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.$]*)`), // lg: Logger (annotation or typed param)
  1215. ];
  1216. case 'python':
  1217. return [
  1218. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // lg = Logger(...)
  1219. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // lg: Logger (PEP 526)
  1220. ];
  1221. case 'java':
  1222. return [
  1223. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`), // = new Logger()
  1224. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg; / param
  1225. ];
  1226. case 'kotlin':
  1227. return [
  1228. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // val lg = Logger(...)
  1229. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // val lg: Logger / param
  1230. ];
  1231. case 'csharp':
  1232. return [
  1233. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`), // = new Logger()
  1234. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg; / param
  1235. ];
  1236. case 'swift':
  1237. return [
  1238. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // let lg = Logger(...)
  1239. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // let lg: Logger / param
  1240. ];
  1241. case 'rust':
  1242. return [
  1243. new RegExp(`\\blet\\s+(?:mut\\s+)?${r}\\b(?:\\s*:[^=]+)?=\\s*&?(?:mut\\s+)?([A-Z][\\w]*)`), // let lg = Logger::new()/Logger{}/Logger
  1244. // No `let`, so this covers a `let lg: Logger` binding AND a typed
  1245. // parameter (`fn use(lg: &Logger)`, a closure `|lg: Logger|`) — the
  1246. // parameter case the old `let`-anchored pattern excluded (#1125).
  1247. new RegExp(`\\b${r}\\s*:\\s*&?(?:mut\\s+)?([A-Z][\\w]*)`), // lg: Logger (binding or typed param)
  1248. ];
  1249. case 'go':
  1250. return [
  1251. new RegExp(`\\b${r}\\b\\s*:=\\s*&?([A-Za-z_][\\w.]*)\\s*{`), // lg := Logger{} / &Logger{}
  1252. new RegExp(`\\bvar\\s+${r}\\s+\\*?([A-Za-z_][\\w.]*)`), // var lg Logger / *Logger
  1253. // A typed parameter / method receiver (`func use(lg Logger)`,
  1254. // `func (l Logger) M()`) — name-before-type with no `var`/`:=` (#1125).
  1255. // PascalCase-guarded (unlike the anchored patterns above) to keep the
  1256. // keyword-free `ident Type` shape from matching unrelated pairs; the
  1257. // enclosing-scope bound already excludes package-level struct fields.
  1258. new RegExp(`\\b${r}\\s+\\*?([A-Z][\\w.]*)`), // func use(lg Logger) / (l Logger)
  1259. ];
  1260. case 'ruby':
  1261. return [
  1262. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w:]*)\\.new\\b`), // lg = Logger.new
  1263. ];
  1264. case 'scala':
  1265. return [
  1266. new RegExp(`\\b${r}\\b\\s*=\\s*(?:new\\s+)?([A-Z][\\w.]*)`), // val lg = new Logger / Logger(...)
  1267. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // val lg: Logger / param
  1268. ];
  1269. case 'dart':
  1270. return [
  1271. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // var lg = Logger(...)
  1272. // Trailing `[=;,)]` (not just `[=;]`) so a typed parameter — `Logger lg)`
  1273. // / `Logger lg,` — matches too, not only `Logger lg = ...` / `Logger lg;`
  1274. // (#1125). Mirrors Java/C#.
  1275. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg = ... / param
  1276. ];
  1277. case 'php':
  1278. return [
  1279. new RegExp(`\\$?${r}\\b\\s*=\\s*new\\s+([A-Za-z_\\\\][\\w\\\\]*)`), // $lg = new Logger()
  1280. // A typed parameter (`function use(Logger $lg)`, `?Logger $lg`,
  1281. // `\\App\\Logger $lg`, `&$lg` by-ref) and a typed `catch (E $e)` — the
  1282. // type sits before the `$`-variable (#1125). Namespace `\\` allowed.
  1283. new RegExp(`\\b([A-Za-z_\\\\][\\w\\\\]*)\\s+&?\\$${r}\\b`), // Logger $lg (typed param)
  1284. ];
  1285. case 'lua':
  1286. case 'luau':
  1287. return [
  1288. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w]*)\\.new\\b`), // local lg = Logger.new()
  1289. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w]*)\\s*\\(`), // local lg = Logger(...) (callable table)
  1290. // Luau annotation (`local lg: Logger`) / typed param — but Lua's
  1291. // method-call syntax is the IDENTICAL `receiver:Name` shape, and the
  1292. // backward scan starts on the call's own line, so without a gate any
  1293. // PascalCase method call (`lg:Log()`, the Roblox convention)
  1294. // self-matches as "type = Log" before the scan reaches the real
  1295. // declaration (#1124). The lookahead rejects a capture followed by
  1296. // any of Lua's three call forms — `(args)`, `"s"`/`'s'`/`[[s]]`,
  1297. // `{t}` — and its leading `[\w.]` alternative stops backtracking from
  1298. // shrinking the capture to dodge the gate (`lg:Log()` would otherwise
  1299. // still match, as `Lo`).
  1300. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)(?![\\w.]|\\s*[({"'\\[])`), // local lg: Logger / typed param
  1301. ];
  1302. case 'r':
  1303. return [
  1304. new RegExp(`\\b${r}\\b\\s*(?:<-|<<-|=)\\s*([A-Z][\\w.]*)\\$new\\b`), // lg <- Logger$new() (R6)
  1305. ];
  1306. case 'pascal':
  1307. return [
  1308. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w]*)`), // var lg: TLogger / param lg: TLogger
  1309. new RegExp(`\\b${r}\\b\\s*:=\\s*([A-Z][\\w.]*)\\.Create\\b`), // lg := TLogger.Create
  1310. ];
  1311. case 'cfml':
  1312. case 'cfscript':
  1313. return [
  1314. // svc = new UserService() / new path.to.UserService() — dotted component
  1315. // paths reduce to their final segment via normalizeInferredTypeName.
  1316. // Also matches inside tag markup (`<cfset svc = new UserService()>`)
  1317. // since the scan reads raw source lines.
  1318. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`),
  1319. // The classic form: svc = createObject("component", "path.to.UserService")
  1320. // (casing of createObject varies in the wild), plus the modern
  1321. // single-argument form createObject("path.to.UserService").
  1322. new RegExp(`\\b${r}\\b\\s*=\\s*[Cc]reate[Oo]bject\\s*\\(\\s*["']component["']\\s*,\\s*["']([\\w.]+)["']`),
  1323. new RegExp(`\\b${r}\\b\\s*=\\s*[Cc]reate[Oo]bject\\s*\\(\\s*["']([\\w.]+)["']\\s*\\)`),
  1324. // Typed cfscript parameter: `function save(UserService svc)` /
  1325. // `required UserService svc` — CFML's built-in types (string, numeric,
  1326. // any, struct…) are lowercase by convention, so the PascalCase guard
  1327. // excludes them.
  1328. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`),
  1329. // Tag-form typed argument, either attribute order:
  1330. // <cfargument name="svc" type="path.to.UserService">
  1331. new RegExp(`\\bcfargument[^>\\n]*\\bname\\s*=\\s*["']${r}["'][^>\\n]*\\btype\\s*=\\s*["']([\\w.]+)["']`, 'i'),
  1332. new RegExp(`\\bcfargument[^>\\n]*\\btype\\s*=\\s*["']([\\w.]+)["'][^>\\n]*\\bname\\s*=\\s*["']${r}["']`, 'i'),
  1333. // Component property (incl. WireBox DI): `property name="svc"
  1334. // inject="UserService";` / `<cfproperty name="svc" type="UserService">`,
  1335. // either attribute order. An inject DSL value with a namespace
  1336. // (`inject="svc@core"`) captures only the leading name and simply
  1337. // fails type-validation — no edge, never a wrong one.
  1338. new RegExp(`\\b(?:cf)?property\\b[^;\\n]*\\bname\\s*=\\s*["']${r}["'][^;\\n]*\\b(?:type|inject)\\s*=\\s*["']([\\w.]+)["']`, 'i'),
  1339. new RegExp(`\\b(?:cf)?property\\b[^;\\n]*\\b(?:type|inject)\\s*=\\s*["']([\\w.]+)["'][^;\\n]*\\bname\\s*=\\s*["']${r}["']`, 'i'),
  1340. ];
  1341. default:
  1342. return [];
  1343. }
  1344. }
  1345. /** 1-based start line of the tightest function/method enclosing the call. */
  1346. function enclosingScopeStartLine(ref: UnresolvedRef, context: ResolutionContext): number {
  1347. let start = 1;
  1348. for (const n of context.getNodesInFile(ref.filePath)) {
  1349. if (n.kind !== 'function' && n.kind !== 'method') continue;
  1350. if (n.language !== ref.language) continue;
  1351. const end = n.endLine ?? n.startLine;
  1352. if (n.startLine <= ref.line && end >= ref.line && n.startLine >= start) {
  1353. start = n.startLine;
  1354. }
  1355. }
  1356. return start;
  1357. }
  1358. /**
  1359. * Infer a receiver's type from its local declaration/initializer in the
  1360. * enclosing function body. Language-dispatched; returns null for languages
  1361. * without patterns or when no declaration is found. Bounded to the enclosing
  1362. * scope so a same-named variable in another function can't leak in.
  1363. */
  1364. function inferLocalReceiverType(
  1365. receiverName: string,
  1366. ref: UnresolvedRef,
  1367. context: ResolutionContext,
  1368. ): string | null {
  1369. // CFML scope prefixes: `variables.svc` / `this.svc` name a COMPONENT-scoped
  1370. // field whose assignment or `property` declaration usually lives outside the
  1371. // calling function (the init-pseudoconstructor / WireBox-injection pattern),
  1372. // and `local.svc` is an explicit function-local. Strip the prefix so the
  1373. // declaration patterns match (`variables.svc = new X()`, `property
  1374. // name="svc" …`, `var svc = …` all bind the bare name), and widen the scan
  1375. // to the whole file for the component-scoped forms — nearest-declaration-
  1376. // backward still wins, so a function-local shadowing the field is preferred.
  1377. let scanReceiver = receiverName;
  1378. let componentScoped = false;
  1379. if (ref.language === 'cfml' || ref.language === 'cfscript') {
  1380. const scoped = receiverName.match(/^(variables|this|local|arguments)\.(.+)$/i);
  1381. if (scoped) {
  1382. scanReceiver = scoped[2]!;
  1383. const scope = scoped[1]!.toLowerCase();
  1384. componentScoped = scope === 'variables' || scope === 'this';
  1385. }
  1386. }
  1387. // PHP `$this->prop` receiver — the property's declaration lives outside the
  1388. // calling method (a promoted constructor parameter `private readonly Foo $prop`,
  1389. // a typed property `private Foo $prop;`, or a classic constructor parameter
  1390. // `Foo $prop` assigned in __construct). Strip the prefix and widen the scan to
  1391. // the whole file (the constructor may sit below the calling method), but —
  1392. // unlike CFML's scopes above — switch to PROPERTY-shaped patterns: a plain
  1393. // `$prop` local or parameter lives in a different namespace than `$this->prop`
  1394. // and can never shadow it, so the generic local patterns would type the
  1395. // property from unrelated same-named variables in other methods (a wrong
  1396. // 0.9-confidence edge, not a missing one).
  1397. let phpProperty = false;
  1398. if (ref.language === 'php') {
  1399. const scoped = receiverName.match(/^this->(.+)$/);
  1400. if (scoped) {
  1401. scanReceiver = scoped[1]!;
  1402. componentScoped = true;
  1403. phpProperty = true;
  1404. }
  1405. }
  1406. const escapedReceiver = scanReceiver.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1407. const patterns = phpProperty
  1408. ? phpPropertyTypePatterns(escapedReceiver)
  1409. : localReceiverTypePatterns(ref.language, escapedReceiver);
  1410. if (patterns.length === 0) return null;
  1411. // Split through the context's per-file lines cache when available: this runs
  1412. // for EVERY `receiver.method()` ref, and re-splitting the whole file per ref
  1413. // was ~20% of total index CPU on Java-heavy repos (#1122).
  1414. const lines = context.getFileLines
  1415. ? context.getFileLines(ref.filePath)
  1416. : (context.readFile(ref.filePath)?.split(/\r?\n/) ?? null);
  1417. if (!lines || lines.length === 0) return null;
  1418. const callIdx = Math.max(0, Math.min(lines.length - 1, ref.line - 1));
  1419. const startIdx = componentScoped
  1420. ? 0
  1421. : Math.max(0, enclosingScopeStartLine(ref, context) - 1);
  1422. const matchLine = (i: number): string | null => {
  1423. const line = lines[i];
  1424. if (!line) return null;
  1425. // A generated/minified line (one multi-KB statement) is not something a
  1426. // human-written local declaration lives on, and regexing it per ref is
  1427. // pure waste — skip it rather than scan it.
  1428. if (line.length > 10_000) return null;
  1429. for (const re of patterns) {
  1430. const m = line.match(re);
  1431. if (m && m[1]) {
  1432. const type = normalizeInferredTypeName(m[1]);
  1433. if (type) return type;
  1434. }
  1435. }
  1436. return null;
  1437. };
  1438. // Incremental-scan memo (INFER_SCAN_STATES): this scan runs for EVERY
  1439. // `receiver.method()` ref and was measured at 61µs/ref on kong (2.4s of
  1440. // worker time, 99% misses — `self:` calls hunting a declaration Lua never
  1441. // writes). Refs for the same (file, scope, receiver) arrive in ~ascending
  1442. // line order, and the scan is a pure function of the file's immutable
  1443. // lines, so each line pays its regex matches ONCE per key instead of once
  1444. // per ref: query(c) = highest matching line in [startIdx..c]; a monotonic
  1445. // call extends the stored watermark by scanning only (hi..c] (the region
  1446. // at-or-below the previous answer is already proven empty above it); a
  1447. // non-monotonic call (rare — refs are rowid-ordered) falls back to the
  1448. // plain bounded scan and leaves the state alone. componentScoped is keyed
  1449. // out — its position-independent whole-file sweep below has different
  1450. // semantics.
  1451. if (!componentScoped) {
  1452. const states = getInferScanStates(context);
  1453. const key = `${ref.filePath}|${startIdx}|${ref.language}|${scanReceiver}`;
  1454. const state = states.get(key);
  1455. if (!state) {
  1456. for (let i = callIdx; i >= startIdx; i--) {
  1457. const type = matchLine(i);
  1458. if (type) {
  1459. states.set(key, { hi: callIdx, ansIdx: i, ansType: type });
  1460. return type;
  1461. }
  1462. }
  1463. states.set(key, { hi: callIdx, ansIdx: -1, ansType: null });
  1464. return null;
  1465. }
  1466. if (callIdx >= state.hi) {
  1467. for (let i = callIdx; i > state.hi; i--) {
  1468. const type = matchLine(i);
  1469. if (type) {
  1470. state.ansIdx = i;
  1471. state.ansType = type;
  1472. break;
  1473. }
  1474. }
  1475. state.hi = callIdx;
  1476. return state.ansIdx >= startIdx ? state.ansType : null;
  1477. }
  1478. for (let i = callIdx; i >= startIdx; i--) {
  1479. const type = matchLine(i);
  1480. if (type) return type;
  1481. }
  1482. return null;
  1483. }
  1484. // Nearest declaration wins: scan backward from the call to the scope start.
  1485. for (let i = callIdx; i >= startIdx; i--) {
  1486. const type = matchLine(i);
  1487. if (type) return type;
  1488. }
  1489. // A component-scoped field's declaration is position-independent — the
  1490. // `variables.svc = new X()` pseudoconstructor assignment or `property`
  1491. // declaration may sit BELOW the calling function in the file — so when the
  1492. // backward pass finds nothing, sweep the remainder of the file too.
  1493. if (componentScoped) {
  1494. for (let i = callIdx + 1; i < lines.length; i++) {
  1495. const type = matchLine(i);
  1496. if (type) return type;
  1497. }
  1498. }
  1499. // A PHP property with no statically-typed declaration (classic pre-7.4
  1500. // style) may still be typed by what gets ASSIGNED to it — follow the
  1501. // `$this->prop = $var` assignment to the assigned variable's own typed
  1502. // declaration (a classic or multi-line constructor parameter, or a typed
  1503. // setter's parameter).
  1504. if (phpProperty) {
  1505. return inferPhpAssignedPropertyType(escapedReceiver, lines, callIdx);
  1506. }
  1507. return null;
  1508. }
  1509. /**
  1510. * Patterns that recover a PHP class property's declared type for a
  1511. * `$this->prop` receiver. Deliberately NOT localReceiverTypePatterns: only
  1512. * property-shaped declarations qualify —
  1513. * 1. a modifier-prefixed typed declaration, which covers both a typed
  1514. * property (`private ?Foo $prop;`) and a promoted constructor parameter
  1515. * (`private readonly Foo $prop`), and
  1516. * 2. the pseudoconstructor assignment (`$this->prop = new Foo(...)`).
  1517. * A bare `X $prop` parameter or `$prop = new X()` local elsewhere in the
  1518. * file must NOT match: those variables can never alias `$this->prop`.
  1519. * Union-typed properties (`Foo|Bar $prop`) yield no match and thus no edge —
  1520. * silent beats wrong. The classic untyped-property-assigned-in-constructor
  1521. * shape is handled by inferPhpAssignedPropertyType instead.
  1522. */
  1523. function phpPropertyTypePatterns(r: string): RegExp[] {
  1524. return memoPatterns(`php-prop|${r}`, () => buildPhpPropertyTypePatterns(r));
  1525. }
  1526. function buildPhpPropertyTypePatterns(r: string): RegExp[] {
  1527. return [
  1528. new RegExp(
  1529. `\\b(?:(?:private|protected|public|readonly|static|final)(?:\\(set\\))?\\s+)+\\??([A-Za-z_\\\\][\\w\\\\]*)\\s+&?\\$${r}\\b`,
  1530. ), // private readonly ?Foo $prop (typed property / promoted param)
  1531. new RegExp(`\\$this->${r}\\b\\s*=\\s*new\\s+([A-Za-z_\\\\][\\w\\\\]*)`), // $this->prop = new Foo()
  1532. ];
  1533. }
  1534. /**
  1535. * Second-chance typing for a PHP `$this->prop` receiver whose property
  1536. * declaration carries no static type (classic pre-7.4 style): find the
  1537. * `$this->prop = $var` assignment, then recover `$var`'s type from its own
  1538. * declaration WITHIN the assignment's function — the constructor's (possibly
  1539. * multi-line) parameter list, a typed setter's parameter, or a `= new X()`
  1540. * local. The backward scan stops at the enclosing `function` line (checked
  1541. * for a match first — a single-line `__construct(Foo $var) { ... }` carries
  1542. * the typed parameter itself), so a same-named variable in another method
  1543. * can never type the property.
  1544. */
  1545. function inferPhpAssignedPropertyType(
  1546. escapedProp: string,
  1547. lines: string[],
  1548. callIdx: number,
  1549. ): string | null {
  1550. const assignRe = new RegExp(`\\$this->${escapedProp}\\b\\s*=\\s*\\$(\\w+)\\b`);
  1551. const assignAt = (i: number): RegExpMatchArray | null => {
  1552. const line = lines[i];
  1553. if (!line || line.length > 10_000) return null;
  1554. return line.match(assignRe);
  1555. };
  1556. // The assignment is position-independent relative to the call — nearest-
  1557. // backward first, then sweep forward, same order as the componentScoped scan.
  1558. let assignIdx = -1;
  1559. let varName: string | null = null;
  1560. for (let i = callIdx; i >= 0; i--) {
  1561. const m = assignAt(i);
  1562. if (m) { assignIdx = i; varName = m[1]!; break; }
  1563. }
  1564. if (varName === null) {
  1565. for (let i = callIdx + 1; i < lines.length; i++) {
  1566. const m = assignAt(i);
  1567. if (m) { assignIdx = i; varName = m[1]!; break; }
  1568. }
  1569. }
  1570. if (varName === null) return null;
  1571. const varPatterns = localReceiverTypePatterns(
  1572. 'php',
  1573. varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
  1574. );
  1575. for (let i = assignIdx; i >= 0; i--) {
  1576. const line = lines[i];
  1577. if (line && line.length <= 10_000) {
  1578. for (const re of varPatterns) {
  1579. const m = line.match(re);
  1580. if (m && m[1]) {
  1581. const type = normalizeInferredTypeName(m[1]);
  1582. if (type) return type;
  1583. }
  1584. }
  1585. }
  1586. if (line && /\bfunction\b/.test(line)) break;
  1587. }
  1588. return null;
  1589. }
  1590. /**
  1591. * Try to resolve by method name on a class/object
  1592. */
  1593. export function matchMethodCall(
  1594. ref: UnresolvedRef,
  1595. context: ResolutionContext
  1596. ): ResolvedRef | null {
  1597. // Parse method call patterns like "obj.method" or "Class::method". The method
  1598. // part allows trailing `:` keywords so Objective-C selectors resolve
  1599. // (`SDImageCache.storeImage:`, `obj.setX:y:`); colons never appear in other
  1600. // languages' method refs, so this is a no-op for them.
  1601. // The receiver allows dots (`builder.Services.AddCoreServices`) so a CHAINED
  1602. // call resolves by its last segment — Strategy 3 below name-matches the method
  1603. // (with its existing single-candidate / receiver-overlap guards). Without this
  1604. // a multi-dot extension-method call (C# DI `builder.Services.AddCoreServices()`,
  1605. // `Guard.Against.X()`) matched no pattern and never resolved.
  1606. // C++ explicit operator call `a.operator+(b)` reaches the resolver as
  1607. // `a.operator+` (#1247) — the operator's symbol chars (`+`, `==`, `[]`, `()`)
  1608. // fail the \w method part of the plain pattern, so admit them explicitly.
  1609. // Names like `operatorTable` stay on the plain pattern (tried first); the
  1610. // operator form requires at least one non-word char after `operator`, and
  1611. // every downstream strategy compares the method part by exact string
  1612. // equality, so a stray match can't invent an edge.
  1613. const dotMatch =
  1614. ref.referenceName.match(/^([\w.]+)\.(\w+:?(?:\w+:)*)$/) ??
  1615. (ref.language === 'cpp'
  1616. ? ref.referenceName.match(/^([\w.]+)\.(operator[^\w\s.]+)$/)
  1617. : null);
  1618. const colonMatch = ref.referenceName.match(/^(\w+)::(\w+)$/);
  1619. // Lua/Luau method calls use a single colon (`lg:log`); R uses `$` (`lg$log`).
  1620. // Recognize these receiver/method separators so local-variable receiver-type
  1621. // inference (#1108) applies to them too — extraction already emits the ref in
  1622. // this shape, but the resolver otherwise only understood `.` and `::`.
  1623. const luaColonMatch = (ref.language === 'lua' || ref.language === 'luau')
  1624. ? ref.referenceName.match(/^([\w.]+):(\w+)$/)
  1625. : null;
  1626. const rDollarMatch = ref.language === 'r'
  1627. ? ref.referenceName.match(/^([\w.]+)\$(\w+)$/)
  1628. : null;
  1629. // PHP property receiver: `$this->prop->method()` reaches the resolver as
  1630. // `this->prop.method` (the extractor records the receiver's raw text with the
  1631. // leading `$` stripped). Resolve it EXCLUSIVELY through declared-type
  1632. // inference + resolveMethodOnType validation — the name-similarity strategies
  1633. // below must never see this shape, so a property whose type can't be
  1634. // recovered stays unlinked rather than guessed (a wrong inference produces no
  1635. // edge rather than a wrong one). Deeper chains (`this->a->b.method`) don't
  1636. // match the single-property pattern and stay unlinked, same as before.
  1637. const phpThisPropMatch = ref.language === 'php'
  1638. ? ref.referenceName.match(/^(this->\w+)\.(\w+)$/)
  1639. : null;
  1640. if (phpThisPropMatch) {
  1641. const [, receiver, phpMethodName] = phpThisPropMatch;
  1642. const inferredType = inferLocalReceiverType(receiver!, ref, context);
  1643. if (!inferredType) return null;
  1644. return resolveMethodOnType(
  1645. inferredType,
  1646. phpMethodName!,
  1647. ref,
  1648. context,
  1649. 0.9,
  1650. 'instance-method',
  1651. importedFqnOf(inferredType, ref, context),
  1652. );
  1653. }
  1654. const match = dotMatch || colonMatch || luaColonMatch || rDollarMatch;
  1655. if (!match) {
  1656. return null;
  1657. }
  1658. const [, objectOrClass, methodName] = match;
  1659. // A simple `receiver.method` / `receiver:method` / `receiver$method` shape whose
  1660. // receiver type we can try to infer from its local declaration.
  1661. const inferableReceiver = dotMatch || luaColonMatch || rDollarMatch;
  1662. // Infer the receiver's type from its local declaration/initializer in the
  1663. // enclosing scope, then resolve the method on that type (#1108). C++ keeps its
  1664. // dedicated inferrer (header scan + `auto`); every other language uses the
  1665. // shared source-based inferrer. resolveMethodOnType validates the method
  1666. // exists on the inferred type, so a mis-inference produces no edge.
  1667. if (inferableReceiver) {
  1668. const inferredType = nmTimedT('mc-infer', ref, () =>
  1669. ref.language === 'cpp'
  1670. ? inferCppReceiverType(objectOrClass!, ref, context)
  1671. : inferLocalReceiverType(objectOrClass!, ref, context));
  1672. if (inferredType) {
  1673. // Java/Kotlin: when two classes share the simple name, the file's import
  1674. // pins WHICH one (#314). Other languages disambiguate by call-site file.
  1675. const importedFqn =
  1676. ref.language === 'java' || ref.language === 'kotlin'
  1677. ? context
  1678. .getImportMappings(ref.filePath, ref.language)
  1679. .find((i) => i.localName === inferredType)?.source
  1680. : undefined;
  1681. const typedMatch = nmTimedT('mc-rmot', ref, () => resolveMethodOnType(
  1682. inferredType,
  1683. methodName!,
  1684. ref,
  1685. context,
  1686. 0.9,
  1687. 'instance-method',
  1688. importedFqn,
  1689. ));
  1690. if (typedMatch) {
  1691. return typedMatch;
  1692. }
  1693. }
  1694. }
  1695. // Go 2-hop field chain `base.field.Method` (#1276): the base's type comes
  1696. // from the enclosing scope (typed parameter / method receiver / local var),
  1697. // the field's declared type from that struct's own declaration lines, and
  1698. // the method is VALIDATED on the field's type by resolveMethodOnType. This
  1699. // branch is EXCLUSIVE for chained Go receivers: when the hop can't be
  1700. // inferred or the field's type is external (`conn *sql.DB` — no project
  1701. // node), the ref stays unresolved rather than falling through to the
  1702. // bare-name strategies below, which is exactly how `target.conn.Exec(...)`
  1703. // fabricated a dependency on an unrelated local interface's same-named
  1704. // method. Chained Go receivers were never emitted before #1276, so there
  1705. // is no prior recall to preserve on the fallback path.
  1706. if (ref.language === 'go' && dotMatch && objectOrClass!.includes('.')) {
  1707. return matchGoFieldChainCall(objectOrClass!, methodName!, ref, context);
  1708. }
  1709. // Rust call through a field of the enclosing type — `self.inner.run()`,
  1710. // emitted as `self.inner.run` (#1585). Same discipline as the Go branch
  1711. // above, and EXCLUSIVE for the same reason: validated field-type inference
  1712. // or nothing. Letting this shape reach the bare-name strategies below is
  1713. // how `self.inner.run()` resolved to a same-named method on an unrelated
  1714. // type — or to the calling method itself, a self-edge the source doesn't
  1715. // contain — whenever the field's type was external or merely shared a
  1716. // method name with something nearby.
  1717. if (ref.language === 'rust' && dotMatch && objectOrClass!.startsWith('self.')) {
  1718. return matchRustSelfFieldCall(objectOrClass!.slice('self.'.length), methodName!, ref, context);
  1719. }
  1720. // Java/Kotlin: receiver may be a field whose name doesn't match the type by
  1721. // Java naming convention (`userbo` → class `UserBO`, abbreviated). Look up
  1722. // the field in the enclosing class to get its declared type, then resolve
  1723. // the method on that type. Covers Spring `@Resource`/`@Autowired` field
  1724. // injection where the field type is the concrete bean class.
  1725. if ((ref.language === 'java' || ref.language === 'kotlin') && dotMatch) {
  1726. const inferredType = inferJavaFieldReceiverType(objectOrClass!, ref, context);
  1727. if (inferredType) {
  1728. // When two classes share the same simple name, the caller file's
  1729. // import is the only signal that names WHICH one — pass the
  1730. // imported FQN so resolveMethodOnType can disambiguate (#314).
  1731. const imports = context.getImportMappings(ref.filePath, ref.language);
  1732. const importedFqn = imports.find((i) => i.localName === inferredType)?.source;
  1733. const typedMatch = nmTimedT('mc-rmot', ref, () => resolveMethodOnType(
  1734. inferredType,
  1735. methodName!,
  1736. ref,
  1737. context,
  1738. 0.9,
  1739. 'instance-method',
  1740. importedFqn,
  1741. ));
  1742. if (typedMatch) {
  1743. return typedMatch;
  1744. }
  1745. }
  1746. }
  1747. // Object-literal namespace receiver (#1573): `api.call()` where `api` is a
  1748. // same-file `const api = { call() {…}, get: () => {…} }`. Its members are
  1749. // plain functions with bare names inside the constant's extent — no
  1750. // `Container::member` qualified name — so none of the class-shaped
  1751. // strategies below can see them (Strategy 3 only considers `method`
  1752. // kinds) and the call resolved to nothing at all. Same file only: a
  1753. // cross-file use reaches the same helper through the import path.
  1754. if (dotMatch && !objectOrClass!.includes('.') && OBJECT_LITERAL_LANGUAGES.has(ref.language)) {
  1755. const literalMatch = nmTimedT('mc-literal', ref, (): ResolvedRef | null => {
  1756. const holders = preferCallSiteFile(context.getNodesByName(objectOrClass!), ref.filePath).filter(
  1757. (n) => (n.kind === 'constant' || n.kind === 'variable') && n.filePath === ref.filePath
  1758. );
  1759. for (const holder of holders) {
  1760. const hit = resolveObjectLiteralMember(holder, methodName!, ref, context, 0.85, 'instance-method');
  1761. if (hit) return hit;
  1762. }
  1763. return null;
  1764. });
  1765. if (literalMatch) return literalMatch;
  1766. }
  1767. // Strategy 1: Direct class name match (existing logic). When the receiver
  1768. // names a class that exists in several files (`Logger.log()` / `Logger::log()`
  1769. // with a `Logger` in both `a/` and `b/`), try the class in the call site's
  1770. // own file first — otherwise the first-indexed class wins and a call in `b/`
  1771. // resolves to `a/`'s method (#1079).
  1772. const strat1 = nmTimedT('mc-class', ref, (): ResolvedRef | null => {
  1773. const classCandidates = preferCallSiteFile(
  1774. context.getNodesByName(objectOrClass!),
  1775. ref.filePath,
  1776. );
  1777. for (const classNode of classCandidates) {
  1778. if (classNode.kind === 'class' || classNode.kind === 'struct' || classNode.kind === 'union' || classNode.kind === 'interface') {
  1779. // Skip cross-language class matches
  1780. if (classNode.language !== ref.language) continue;
  1781. const nodesInFile = context.getNodesInFile(classNode.filePath);
  1782. const methodNode = nodesInFile.find(
  1783. (n) =>
  1784. n.kind === 'method' &&
  1785. n.name === methodName &&
  1786. n.qualifiedName.includes(classNode.name)
  1787. );
  1788. if (methodNode) {
  1789. return {
  1790. original: ref,
  1791. targetNodeId: methodNode.id,
  1792. confidence: 0.85,
  1793. resolvedBy: 'qualified-name',
  1794. };
  1795. }
  1796. }
  1797. }
  1798. return null;
  1799. });
  1800. if (strat1) return strat1;
  1801. // Strategy 2: Instance variable receiver - try capitalized form to find class
  1802. // e.g., "permissionEngine" → look for classes containing "PermissionEngine"
  1803. const capitalizedReceiver = objectOrClass!.charAt(0).toUpperCase() + objectOrClass!.slice(1);
  1804. if (capitalizedReceiver !== objectOrClass) {
  1805. const strat2 = nmTimedT('mc-capital', ref, (): ResolvedRef | null => {
  1806. const fuzzyClassCandidates = preferCallSiteFile(
  1807. context.getNodesByName(capitalizedReceiver),
  1808. ref.filePath,
  1809. );
  1810. for (const classNode of fuzzyClassCandidates) {
  1811. if (classNode.kind === 'class' || classNode.kind === 'struct' || classNode.kind === 'union' || classNode.kind === 'interface') {
  1812. // Skip cross-language class matches
  1813. if (classNode.language !== ref.language) continue;
  1814. const nodesInFile = context.getNodesInFile(classNode.filePath);
  1815. const methodNode = nodesInFile.find(
  1816. (n) =>
  1817. n.kind === 'method' &&
  1818. n.name === methodName &&
  1819. n.qualifiedName.includes(classNode.name)
  1820. );
  1821. if (methodNode) {
  1822. return {
  1823. original: ref,
  1824. targetNodeId: methodNode.id,
  1825. confidence: 0.8,
  1826. resolvedBy: 'instance-method',
  1827. };
  1828. }
  1829. }
  1830. }
  1831. return null;
  1832. });
  1833. if (strat2) return strat2;
  1834. }
  1835. // Strategy 3: Find methods by name across the codebase, match by receiver
  1836. // name similarity with the containing class. Handles abbreviated variable
  1837. // names like permissionEngine → PermissionRuleEngine.
  1838. if (methodName) {
  1839. const strat3 = nmTimedT('mc-byname', ref, (): ResolvedRef | null => {
  1840. const methodCandidates = context.getNodesByName(methodName!);
  1841. // Ubiquitous-method ceiling (#999): a method name re-declared across a
  1842. // vendored theme/SDK (Metronic's `init`/`update`/… on every widget) yields
  1843. // K candidates that receiver-word overlap can't reliably disambiguate —
  1844. // and filtering + scoring all K per call is the O(K²) cost that wedged
  1845. // "Resolving refs" for 15-28 min. Bail before the O(K) work; Strategy 1/2
  1846. // (class-name match) already had their precise shot above.
  1847. if (methodCandidates.length > AMBIGUOUS_NAME_CEILING) {
  1848. return null;
  1849. }
  1850. const methods = methodCandidates.filter(
  1851. (n) => n.kind === 'method' && n.name === methodName
  1852. );
  1853. // Filter to same-language candidates first
  1854. const sameLanguageMethods = methods.filter(m => m.language === ref.language);
  1855. const targetMethods = sameLanguageMethods.length > 0 ? sameLanguageMethods : methods;
  1856. // If only one same-language method with this name exists, use it
  1857. if (targetMethods.length === 1 && targetMethods[0]!.language === ref.language) {
  1858. return {
  1859. original: ref,
  1860. targetNodeId: targetMethods[0]!.id,
  1861. confidence: 0.7,
  1862. resolvedBy: 'instance-method',
  1863. };
  1864. }
  1865. // Multiple methods: score by receiver name word overlap with class name
  1866. if (targetMethods.length > 1) {
  1867. const receiverWords = splitCamelCase(objectOrClass!);
  1868. let bestMatch: typeof targetMethods[0] | undefined;
  1869. let bestScore = 0;
  1870. // Same-file candidates first, so a score tie (`score > bestScore` keeps
  1871. // the first seen) resolves to the call site's own file rather than the
  1872. // first-indexed duplicate (#1079).
  1873. for (const method of preferCallSiteFile(targetMethods, ref.filePath)) {
  1874. const classWords = splitCamelCase(method.qualifiedName);
  1875. let score = receiverWords.filter(w =>
  1876. classWords.some(cw => cw.toLowerCase() === w.toLowerCase())
  1877. ).length;
  1878. // Bonus for same language
  1879. if (method.language === ref.language) score += 1;
  1880. if (score > bestScore) {
  1881. bestScore = score;
  1882. bestMatch = method;
  1883. }
  1884. }
  1885. if (bestMatch && bestScore >= 2) {
  1886. return {
  1887. original: ref,
  1888. targetNodeId: bestMatch.id,
  1889. confidence: 0.65,
  1890. resolvedBy: 'instance-method',
  1891. };
  1892. }
  1893. }
  1894. return null;
  1895. });
  1896. if (strat3) return strat3;
  1897. }
  1898. return null;
  1899. }
  1900. /** Go builtin/primitive field types that can never carry a project method. */
  1901. const GO_BUILTIN_FIELD_TYPES = new Set([
  1902. 'string', 'bool', 'byte', 'rune', 'error', 'any',
  1903. 'int', 'int8', 'int16', 'int32', 'int64',
  1904. 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'uintptr',
  1905. 'float32', 'float64', 'complex64', 'complex128',
  1906. 'chan', 'map', 'func', 'struct', 'interface',
  1907. ]);
  1908. /**
  1909. * Resolve a Go 2-hop field-chain call `base.field.Method(...)` (#1276):
  1910. * `target.conn.Exec("insert")` where `func (target *Target) Write()` and
  1911. * `type Target struct { conn *sql.DB }`. Two inference hops, both read from
  1912. * source the same way #1108 does:
  1913. * 1. `base`'s type from the enclosing scope (method receiver, typed
  1914. * parameter, or local declaration) via inferLocalReceiverType;
  1915. * 2. `field`'s declared type from the struct's own declaration lines.
  1916. * The method is then resolved AND VALIDATED on the field's type. A field
  1917. * whose type has no project node (`sql.DB`, any external dependency) yields
  1918. * null — the caller treats this branch as exclusive for chained Go
  1919. * receivers, so the ref stays unresolved instead of name-guessing.
  1920. */
  1921. function matchGoFieldChainCall(
  1922. receiverChain: string,
  1923. methodName: string,
  1924. ref: UnresolvedRef,
  1925. context: ResolutionContext
  1926. ): ResolvedRef | null {
  1927. const segs = receiverChain.split('.');
  1928. if (segs.length !== 2 || !segs[0] || !segs[1]) return null;
  1929. const [base, field] = segs;
  1930. const baseType = inferLocalReceiverType(base!, ref, context);
  1931. if (!baseType) return null;
  1932. const fieldEsc = field!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1933. const fieldTypeRe = new RegExp(`\\b${fieldEsc}\\s+\\*?\\[?\\]?([A-Za-z_][\\w.]*)`);
  1934. const structs = preferCallSiteFile(context.getNodesByName(baseType), ref.filePath).filter(
  1935. (n) => (n.kind === 'struct' || n.kind === 'class') && n.language === 'go'
  1936. );
  1937. for (const s of structs) {
  1938. const source = context.readFile(s.filePath);
  1939. if (!source) continue;
  1940. // Only the struct's own declaration lines — a same-named identifier
  1941. // elsewhere in the file can't donate a type. Matched LINE BY LINE with
  1942. // comments stripped: chi's `Mux` has a doc comment reading "the tree
  1943. // router" right above `tree *node`, and a whole-block match captured
  1944. // `router` from the prose instead of `node` from the field.
  1945. const declLines = source.split('\n').slice(Math.max(0, s.startLine - 1), s.endLine);
  1946. for (const rawLine of declLines) {
  1947. const line = rawLine.replace(/\/\/.*$/, '').replace(/\/\*.*?\*\//g, '');
  1948. const m = line.match(fieldTypeRe);
  1949. if (!m || !m[1]) continue;
  1950. const rawType = m[1];
  1951. // A package-qualified field type (`http.Handler`, `sql.DB`) is only
  1952. // followed when the package is IN-MODULE: stripping the qualifier and
  1953. // matching the bare name would conflate a stdlib/third-party type with
  1954. // any same-named project type — on chi, `handler http.Handler` bound
  1955. // to an example app's unrelated local `Handler`. That is the exact
  1956. // fabrication this matcher exists to prevent (#1276).
  1957. if (rawType.includes('.')) {
  1958. const pkg = rawType.split('.')[0]!;
  1959. const mod = context.getGoModule?.();
  1960. const imp = context
  1961. .getImportMappings(s.filePath, 'go')
  1962. .find((i) => i.localName === pkg);
  1963. const inModule =
  1964. !!mod &&
  1965. !!imp &&
  1966. (imp.source === mod.modulePath || imp.source.startsWith(mod.modulePath + '/'));
  1967. if (!inModule) continue;
  1968. }
  1969. // Unexported (lowercase) types are idiomatic Go and stay eligible —
  1970. // chi's `mx.tree.FindRoute()` chains through `tree *node`. A
  1971. // mis-capture is harmless: resolveMethodOnType only returns a
  1972. // validated `<type>::<method>` match.
  1973. const fieldType = rawType.split('.').pop();
  1974. if (!fieldType || !/^[A-Za-z_]/.test(fieldType) || GO_BUILTIN_FIELD_TYPES.has(fieldType)) continue;
  1975. const resolved = resolveMethodOnType(fieldType, methodName, ref, context, 0.85, 'instance-method');
  1976. if (resolved) return resolved;
  1977. }
  1978. }
  1979. return null;
  1980. }
  1981. // Rust primitives and the prelude's own types: a field of one of these never
  1982. // names a project type, so a `self.<field>.<method>()` on it stays unresolved.
  1983. const RUST_NON_PROJECT_FIELD_TYPES = new Set([
  1984. 'bool', 'char', 'str', 'String',
  1985. 'i8', 'i16', 'i32', 'i64', 'i128', 'isize',
  1986. 'u8', 'u16', 'u32', 'u64', 'u128', 'usize',
  1987. 'f32', 'f64',
  1988. 'Self', 'self',
  1989. ]);
  1990. /**
  1991. * Reduce a Rust field's declared type text to the simple name of the type a
  1992. * method call on that field auto-derefs to, or null when there is none we can
  1993. * name. Only the layers Rust's method-call auto-deref looks through are
  1994. * unwrapped: references (`&`, `&'a mut`) and the owning smart pointers
  1995. * (`Box`, `Rc`, `Arc`) — `self.inner.run()` with `inner: Box<Inner>` calls
  1996. * `Inner::run`. Containers that do NOT auto-deref to their parameter
  1997. * (`Option<Inner>`, `Vec<Inner>`, `Mutex<Inner>`, `RefCell<Inner>`) keep their
  1998. * own name and, having no project node, resolve to nothing — `self.items.push()`
  1999. * must never become `Inner::push`. A trait object (`Box<dyn Source>`) yields
  2000. * the trait, whose method node the interface-impl synthesizer fans out. A
  2001. * generic parameter (`T`), a primitive, a tuple / array / raw pointer / fn
  2002. * type, or a non-identifier yields null.
  2003. */
  2004. export function rustFieldTypeName(raw: string): string | null {
  2005. let t = raw.trim();
  2006. for (;;) {
  2007. const before = t;
  2008. t = t.replace(/^&\s*(?:'\w+\s+)?(?:mut\s+)?/, '');
  2009. t = t.replace(/^(?:Box|Rc|Arc)\s*<\s*/, '');
  2010. t = t.replace(/^(?:dyn|impl)\s+/, '');
  2011. if (t === before) break;
  2012. }
  2013. // Drop generic args, the closing `>`s of unwrapped pointers, and trait-object
  2014. // bounds (`dyn Source + Send`); keep the last path segment.
  2015. t = t.replace(/[<>+].*$/, '').trim();
  2016. const seg = t.split('::').filter(Boolean).pop();
  2017. if (!seg || !/^[A-Za-z_]\w*$/.test(seg)) return null;
  2018. if (RUST_NON_PROJECT_FIELD_TYPES.has(seg)) return null;
  2019. if (/^[A-Z]$/.test(seg)) return null; // bare single-letter generic parameter
  2020. return seg;
  2021. }
  2022. /**
  2023. * Resolve a Rust call through a field of the enclosing type —
  2024. * `self.inner.run()`, emitted by the extractor as `self.inner.run` (#1585).
  2025. * Mirrors the Go 2-hop precedent above (#1276): the owner type is the calling
  2026. * method's qualified-name prefix (`Outer::run` → `Outer`), the field's declared
  2027. * type comes from the owner struct's OWN declaration lines, and the method is
  2028. * resolved AND VALIDATED on that type by resolveMethodOnType. The caller
  2029. * treats this branch as exclusive for `self.<field>` receivers: a field whose
  2030. * type is external (`std::vec::IntoIter`, `regex::Regex`), a generic
  2031. * parameter, or not declared where we can see it yields null and the ref stays
  2032. * unresolved. Rust struct fields are not graph nodes, so the declaration text
  2033. * is the only place the type lives.
  2034. */
  2035. function matchRustSelfFieldCall(
  2036. field: string,
  2037. methodName: string,
  2038. ref: UnresolvedRef,
  2039. context: ResolutionContext,
  2040. ): ResolvedRef | null {
  2041. // The extractor only ever emits a single field hop; anything else is not ours.
  2042. if (!field || field.includes('.')) return null;
  2043. const caller = context.getNodeById?.(ref.fromNodeId);
  2044. if (!caller) return null;
  2045. const sep = caller.qualifiedName.lastIndexOf('::');
  2046. if (sep <= 0) return null; // a free fn has no `self`
  2047. const owner = caller.qualifiedName.slice(0, sep).split('::').pop();
  2048. if (!owner) return null;
  2049. const owners = preferCallSiteFile(context.getNodesByName(owner), ref.filePath).filter(
  2050. (n) =>
  2051. (n.kind === 'struct' || n.kind === 'union' || n.kind === 'class') &&
  2052. n.language === 'rust'
  2053. );
  2054. const fieldEsc = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  2055. // `pub inner: Inner,` / `inner: Box<dyn Source>,` / `pub(crate) inner: T }` —
  2056. // the type text runs to the field separator. A comma inside generic args
  2057. // (`HashMap<K, V>`) truncates the capture, which rustFieldTypeName then
  2058. // reduces to the container's own name — exactly the non-deref case it
  2059. // refuses anyway.
  2060. const fieldRe = new RegExp(`\\b${fieldEsc}\\s*:\\s*([^,{}]+)`);
  2061. for (const s of owners) {
  2062. const source = context.readFile(s.filePath);
  2063. if (!source) continue;
  2064. // Only the struct's own declaration lines, comment-stripped line by line —
  2065. // same discipline as the Go helper: prose or a same-named identifier
  2066. // elsewhere in the file can never donate a type.
  2067. const declLines = source.split('\n').slice(Math.max(0, s.startLine - 1), s.endLine);
  2068. for (const rawLine of declLines) {
  2069. const line = rawLine.replace(/\/\/.*$/, '').replace(/\/\*.*?\*\//g, '');
  2070. const m = line.match(fieldRe);
  2071. if (!m || !m[1]) continue;
  2072. const fieldType = rustFieldTypeName(m[1]);
  2073. // The field is declared here; whether or not its type names a project
  2074. // symbol, this owner is the answer — no other same-named struct applies.
  2075. if (!fieldType) return null;
  2076. return resolveMethodOnType(fieldType, methodName, ref, context, 0.85, 'instance-method');
  2077. }
  2078. }
  2079. return null;
  2080. }
  2081. /**
  2082. * Split a camelCase or PascalCase string into words.
  2083. */
  2084. function splitCamelCase(str: string): string[] {
  2085. return str.replace(/([a-z])([A-Z])/g, '$1 $2')
  2086. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
  2087. .split(/[\s._:\/\\]+/)
  2088. .filter(w => w.length > 1);
  2089. }
  2090. /**
  2091. * Compute directory proximity from a pre-split list of directory segments
  2092. * (`filePath1` minus its filename) and a second file path.
  2093. * Returns a score based on the number of shared leading directory segments.
  2094. * Higher score = closer in directory tree.
  2095. *
  2096. * Split into a pre-split variant because findBestMatch scores every candidate
  2097. * against the SAME `ref.filePath`; re-splitting it per candidate was a hot spot
  2098. * on large repos (#915), so the caller splits it once and passes the segments.
  2099. */
  2100. function pathProximityFromDirs(dir1: string[], filePath2: string): number {
  2101. const dir2 = filePath2.split('/');
  2102. dir2.pop(); // drop filename — matches the original slice(0, -1) on both paths
  2103. let shared = 0;
  2104. const limit = Math.min(dir1.length, dir2.length);
  2105. for (let i = 0; i < limit; i++) {
  2106. if (dir1[i] === dir2[i]) {
  2107. shared++;
  2108. } else {
  2109. break;
  2110. }
  2111. }
  2112. // Each shared directory segment contributes 15 points, capped at 80
  2113. return Math.min(shared * 15, 80);
  2114. }
  2115. /**
  2116. * Compute directory proximity between two file paths.
  2117. * Returns a score based on the number of shared directory segments.
  2118. */
  2119. function computePathProximity(filePath1: string, filePath2: string): number {
  2120. const dir1 = filePath1.split('/');
  2121. dir1.pop();
  2122. return pathProximityFromDirs(dir1, filePath2);
  2123. }
  2124. /**
  2125. * Find the best matching node when there are multiple candidates
  2126. */
  2127. function findBestMatch(
  2128. ref: UnresolvedRef,
  2129. candidates: Node[],
  2130. _context: ResolutionContext
  2131. ): Node | null {
  2132. // Prioritization rules:
  2133. // 1. Same file > different file
  2134. // 2. Directory proximity (same module/package > different module)
  2135. // 3. Same language > different language
  2136. // 4. Functions/methods > classes/types (for call references)
  2137. // 5. Exported > non-exported
  2138. let bestScore = -1;
  2139. let bestNode: Node | null = null;
  2140. // Split the ref's path once (it's the same across every candidate) instead of
  2141. // re-splitting it inside computePathProximity per candidate (#915 hot spot).
  2142. const refDirs = ref.filePath.split('/');
  2143. refDirs.pop();
  2144. // A same-language candidate ALWAYS outscores a cross-language one: same-language
  2145. // scores at least +50 (language bonus), while a cross-language candidate maxes
  2146. // out at +35 (−80 language, +80 proximity, +25 kind, +10 exported; it can never
  2147. // be in the same file). So when any same-language candidate exists, skip the
  2148. // cross-language ones — provably the same winner, without paying the per-candidate
  2149. // scoring. Cuts the candidate set to same-language size on mixed front-end +
  2150. // back-end repos (#915). When ALL candidates are cross-language (a legitimate
  2151. // cross-language `calls` bridge), none are skipped and behavior is unchanged.
  2152. const hasSameLanguage = candidates.some((c) => c.language === ref.language);
  2153. for (const candidate of candidates) {
  2154. if (hasSameLanguage && candidate.language !== ref.language) continue;
  2155. let score = 0;
  2156. // Same file bonus
  2157. if (candidate.filePath === ref.filePath) {
  2158. score += 100;
  2159. }
  2160. // Directory proximity bonus — strongly prefer same module/package
  2161. score += pathProximityFromDirs(refDirs, candidate.filePath);
  2162. // Language matching: strongly prefer same language, penalize cross-language
  2163. if (candidate.language === ref.language) {
  2164. score += 50;
  2165. } else {
  2166. score -= 80;
  2167. }
  2168. // For call references, prefer functions/methods
  2169. if (ref.referenceKind === 'calls') {
  2170. if (candidate.kind === 'function' || candidate.kind === 'method') {
  2171. score += 25;
  2172. }
  2173. }
  2174. // For instantiation references (`new Foo()`), prefer class-like
  2175. // targets — without this, a function named `Foo` in another module
  2176. // could outscore the actual class.
  2177. if (ref.referenceKind === 'instantiates') {
  2178. if (
  2179. candidate.kind === 'class' ||
  2180. candidate.kind === 'struct' ||
  2181. candidate.kind === 'union' ||
  2182. candidate.kind === 'interface'
  2183. ) {
  2184. score += 25;
  2185. }
  2186. }
  2187. // For decorator references (`@Foo`), prefer functions. Class
  2188. // decorators (Python `@SomeClass`, Java annotation interfaces)
  2189. // also resolve here, hence the smaller class bonus.
  2190. if (ref.referenceKind === 'decorates') {
  2191. if (candidate.kind === 'function' || candidate.kind === 'method') {
  2192. score += 25;
  2193. } else if (candidate.kind === 'class' || candidate.kind === 'interface') {
  2194. score += 15;
  2195. }
  2196. }
  2197. // Exported bonus
  2198. if (candidate.isExported) {
  2199. score += 10;
  2200. }
  2201. // Closer line number (within same file)
  2202. if (candidate.filePath === ref.filePath && candidate.startLine) {
  2203. const distance = Math.abs(candidate.startLine - ref.line);
  2204. score += Math.max(0, 20 - distance / 10);
  2205. }
  2206. if (score > bestScore) {
  2207. bestScore = score;
  2208. bestNode = candidate;
  2209. }
  2210. }
  2211. return bestNode;
  2212. }
  2213. /**
  2214. * Fuzzy match - last resort with lower confidence
  2215. */
  2216. export function matchFuzzy(
  2217. ref: UnresolvedRef,
  2218. context: ResolutionContext
  2219. ): ResolvedRef | null {
  2220. const lowerName = ref.referenceName.toLowerCase();
  2221. // Use pre-built lowercase index for O(1) lookup instead of scanning all nodes
  2222. const candidates = context.getNodesByLowerName(lowerName);
  2223. // Filter to callable kinds only (function, method, class)
  2224. const callableKinds = new Set(['function', 'method', 'class']);
  2225. const callableCandidates = applyLanguageGate(candidates.filter((n) => callableKinds.has(n.kind)), ref);
  2226. // Prefer same-language matches
  2227. const sameLanguageCandidates = callableCandidates.filter(n => n.language === ref.language);
  2228. const finalCandidates = sameLanguageCandidates.length > 0 ? sameLanguageCandidates : callableCandidates;
  2229. if (finalCandidates.length === 1) {
  2230. const isCrossLanguage = finalCandidates[0]!.language !== ref.language;
  2231. return {
  2232. original: ref,
  2233. targetNodeId: finalCandidates[0]!.id,
  2234. confidence: isCrossLanguage ? 0.3 : 0.5,
  2235. resolvedBy: 'fuzzy',
  2236. };
  2237. }
  2238. return null;
  2239. }
  2240. /**
  2241. * Match all strategies in order of confidence
  2242. */
  2243. /** ArkUI attribute-helper decorators a `.attr(...)` chain may resolve to. */
  2244. const ARKUI_ATTRIBUTE_DECORATORS = new Set(['Extend', 'Styles', 'AnimatableExtend', 'Builder']);
  2245. /**
  2246. * CODEGRAPH_RESOLVE_PROFILE=2 sub-stage attribution for matchReference's
  2247. * strategy pipeline (`nm:<stage>|<refKind>|hit/miss`). Module-global because
  2248. * the matcher is a free function; each thread (main + every pool worker) has
  2249. * its own module instance, and dumpNameMatcherProfile is invoked from
  2250. * ReferenceResolver.dumpResolveProfile so worker tables surface too.
  2251. */
  2252. const NM_PROFILE: Map<string, { n: number; ns: bigint }> | null =
  2253. process.env.CODEGRAPH_RESOLVE_PROFILE === '2' ? new Map() : null;
  2254. function nmTimedT<T>(stage: string, ref: UnresolvedRef, fn: () => T): T {
  2255. if (!NM_PROFILE) return fn();
  2256. const t0 = process.hrtime.bigint();
  2257. const r = fn();
  2258. const dt = process.hrtime.bigint() - t0;
  2259. const key = `nm:${stage}|${ref.referenceKind}|${r ? 'hit' : 'miss'}`;
  2260. const slot = NM_PROFILE.get(key);
  2261. if (slot) {
  2262. slot.n++;
  2263. slot.ns += dt;
  2264. } else {
  2265. NM_PROFILE.set(key, { n: 1, ns: dt });
  2266. }
  2267. return r;
  2268. }
  2269. function nmTimed(stage: string, ref: UnresolvedRef, fn: () => ResolvedRef | null): ResolvedRef | null {
  2270. return nmTimedT(stage, ref, fn);
  2271. }
  2272. /** Dump this thread's matchReference sub-stage table to stderr (no-op unless =2). */
  2273. export function dumpNameMatcherProfile(label: string): void {
  2274. if (!NM_PROFILE || NM_PROFILE.size === 0) return;
  2275. const rows = [...NM_PROFILE.entries()]
  2276. .map(([k, v]) => ({ k, n: v.n, ms: Number(v.ns / 1_000_000n) }))
  2277. .sort((a, b) => b.ms - a.ms);
  2278. for (const r of rows) {
  2279. console.error(
  2280. `[resolve-profile] ${label} ${r.k}: n=${r.n} total=${(r.ms / 1000).toFixed(1)}s avg=${((r.ms * 1000) / Math.max(1, r.n)).toFixed(0)}µs`
  2281. );
  2282. }
  2283. }
  2284. export function matchReference(
  2285. ref: UnresolvedRef,
  2286. context: ResolutionContext
  2287. ): ResolvedRef | null {
  2288. // Function-as-value refs (#756) resolve ONLY through the dedicated matcher —
  2289. // never the fuzzy/qualified fallthrough below (a wrong callback edge is
  2290. // worse than none).
  2291. if (ref.referenceKind === 'function_ref') {
  2292. return matchFunctionRef(ref, context);
  2293. }
  2294. // ArkTS chained UI attributes — emitted with a leading dot (`.titleStyle`,
  2295. // `.width`) by the extractor — resolve ONLY to decorator-marked attribute
  2296. // helpers: `@Extend`/`@Styles`/`@AnimatableExtend` functions (and global
  2297. // `@Builder`s used attribute-position). Framework attributes (`.width`,
  2298. // `.fontSize` — on nearly every UI line) match no such helper and stay
  2299. // unresolved, NEVER falling through to bare-name matching: on a samples
  2300. // monorepo that fallthrough manufactured 36k wrong edges, giving single
  2301. // same-named properties thousands of false callers. Ambiguity rule matches
  2302. // the rest of the file: several same-named helpers → prefer the call-site
  2303. // file, still ambiguous → drop the ref rather than guess.
  2304. if (ref.language === 'arkts' && ref.referenceName.startsWith('.')) {
  2305. const base = ref.referenceName.slice(1);
  2306. const candidates = context
  2307. .getNodesByName(base)
  2308. .filter(
  2309. (n) =>
  2310. n.language === 'arkts' &&
  2311. n.kind === 'function' &&
  2312. (n.decorators ?? []).some((d) => ARKUI_ATTRIBUTE_DECORATORS.has(d))
  2313. );
  2314. const chosen =
  2315. candidates.length > 1 ? preferCallSiteFile(candidates, ref.filePath) : candidates;
  2316. if (chosen.length !== 1) return null;
  2317. return {
  2318. original: ref,
  2319. targetNodeId: chosen[0]!.id,
  2320. confidence: 0.85,
  2321. resolvedBy: 'exact-match',
  2322. };
  2323. }
  2324. // Erlang `-behaviour(m)` refs target a MODULE. Letting them fall through to
  2325. // bare-name matching grabs any same-named symbol — on emqx,
  2326. // `-behaviour(supervisor)` resolved to a `-define(supervisor, …)` macro
  2327. // constant in an unrelated app. Resolve only to the behaviour module's
  2328. // namespace; an out-of-repo behaviour (OTP's gen_server/supervisor) stays
  2329. // unresolved rather than guessed. The same module-only rule applies to every
  2330. // ref an `.app`/`.app.src` resource file emits — its `{mod, …}` callback and
  2331. // `{applications, …}` dependency names can only mean modules, and on emqx
  2332. // the `ssl` OTP app otherwise resolved to a test helper FUNCTION named ssl.
  2333. if (
  2334. ref.language === 'erlang' &&
  2335. (ref.referenceKind === 'implements' || /\.app(?:\.src)?$/i.test(ref.filePath))
  2336. ) {
  2337. const modules = context
  2338. .getNodesByName(ref.referenceName)
  2339. .filter((n) => n.language === 'erlang' && n.kind === 'namespace');
  2340. const chosen = preferCallSiteFile(modules, ref.filePath)[0];
  2341. if (!chosen) return null;
  2342. return {
  2343. original: ref,
  2344. targetNodeId: chosen.id,
  2345. confidence: 0.9,
  2346. resolvedBy: 'exact-match',
  2347. };
  2348. }
  2349. // Try strategies in order of confidence
  2350. let result: ResolvedRef | null;
  2351. // 0. File path match (e.g., "snippets/drawer-menu.liquid" → file node)
  2352. result = nmTimed('filePath', ref, () => matchByFilePath(ref, context));
  2353. if (result) return result;
  2354. // 1. Qualified name match (highest confidence)
  2355. result = nmTimed('qualifiedName', ref, () => matchByQualifiedName(ref, context));
  2356. if (result) return result;
  2357. // 1b. C++ chained call whose receiver is another call — `Foo::instance().bar()`
  2358. // encoded as `Foo::instance().bar` by the extractor (#645). Resolve the
  2359. // receiver's type from what the inner call returns, then the method on it.
  2360. if (ref.language === 'cpp' || ref.language === 'c') {
  2361. result = nmTimed('cppChain', ref, () => matchCppCallChain(ref, context));
  2362. if (result) return result;
  2363. }
  2364. // 1c. `::`-scoped factory chain — PHP `Cls::for($x)->method()` (#608) or Rust
  2365. // `Foo::new().bar()`, both encoded as `Cls::factory().method`. The receiver's
  2366. // type is the factory's `self` (PHP `: self`/`: static`, Rust `-> Self`) or
  2367. // concrete return type.
  2368. if (ref.language === 'php' || ref.language === 'rust') {
  2369. result = nmTimed('scopedChain', ref, () => matchScopedCallChain(ref, context));
  2370. if (result) return result;
  2371. }
  2372. // 1d. Dotted chained static-factory / fluent call (Java / Kotlin / C# / Swift /
  2373. // Go / Scala / Dart / Objective-C) — `Foo.getInstance().bar()` encoded as
  2374. // `Foo.getInstance().bar`, Go's bare-factory `New().Method()` as `New().Method`,
  2375. // Scala's companion factory, Dart's static factory / factory-constructor, or
  2376. // ObjC's chained message send `[[Foo create] doIt]` encoded as `Foo.create().doIt`
  2377. // (#645/#608 mechanism). Resolve the method's class from the inner call's
  2378. // declared return type, then validate it.
  2379. if (
  2380. ref.language === 'java' ||
  2381. ref.language === 'kotlin' ||
  2382. ref.language === 'csharp' ||
  2383. ref.language === 'swift' ||
  2384. ref.language === 'go' ||
  2385. ref.language === 'scala' ||
  2386. ref.language === 'dart' ||
  2387. ref.language === 'objc' ||
  2388. ref.language === 'pascal'
  2389. ) {
  2390. result = nmTimed('dottedChain', ref, () => matchDottedCallChain(ref, context));
  2391. if (result) return result;
  2392. }
  2393. // 2. Method call pattern
  2394. result = nmTimed('methodCall', ref, () => matchMethodCall(ref, context));
  2395. if (result) return result;
  2396. // 3. Exact name match
  2397. result = nmTimed('exactName', ref, () => matchByExactName(ref, context));
  2398. if (result) return result;
  2399. // 4. Fuzzy match (lowest confidence)
  2400. result = nmTimed('fuzzy', ref, () => matchFuzzy(ref, context));
  2401. if (result) return result;
  2402. return null;
  2403. }