name-matcher.ts 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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. // Exported for the precedence unit tests (#1079): they assert the
  511. // preferredFqn → same-file → matches[0] ordering directly.
  512. export function resolveMethodOnType(
  513. typeName: string,
  514. methodName: string,
  515. ref: UnresolvedRef,
  516. context: ResolutionContext,
  517. confidence: number,
  518. resolvedBy: ResolvedRef['resolvedBy'],
  519. /**
  520. * Optional FQN that identifies WHICH class declaration `typeName`
  521. * refers to in the caller's file. When multiple candidates share
  522. * the same qualifiedName (`FooConverter::convert` in both
  523. * `dao/converter/` and `service/converter/`), the FQN's
  524. * file-path-suffix picks the right one — the disambiguation
  525. * signal Java imports carry but the call site doesn't (#314).
  526. */
  527. preferredFqn?: string,
  528. /** Recursion guard for the supertype/conformance walk. */
  529. depth = 0,
  530. ): ResolvedRef | null {
  531. // Look up methods by name and match by qualifiedName ending in
  532. // `<typeName>::<methodName>`. This works whether the method is defined
  533. // in-class (`class Foo { int bar() { ... } }`) or out-of-line in a separate
  534. // file (`int Foo::bar() { ... }` in foo.cpp while class Foo is in foo.hpp).
  535. // The previous same-file approach missed the latter — the typical C++ layout.
  536. // Prefer the context's per-(type, method) memo: the raw name lookup fetches
  537. // EVERY node sharing the method name — tens of thousands of rows for a
  538. // collision-heavy Java name like `execute` — and re-filtering that per ref
  539. // was a dominant term in the #1122 watchdog kill on large repos. Only the
  540. // ref-independent filter is memoized; per-ref disambiguation stays below.
  541. let matches: Node[];
  542. if (context.getMethodMatches) {
  543. matches = context.getMethodMatches(typeName, methodName, ref.language);
  544. } else {
  545. const methodCandidates = context.getNodesByName(methodName);
  546. const want = `${typeName}::${methodName}`;
  547. matches = [];
  548. for (const m of methodCandidates) {
  549. if (m.kind !== 'method') continue;
  550. if (m.language !== ref.language) continue;
  551. const qn = m.qualifiedName;
  552. if (qn === want || qn.endsWith(`::${want}`)) {
  553. matches.push(m);
  554. }
  555. }
  556. }
  557. if (matches.length === 0) {
  558. // Conformance fallback: the method may be defined on a supertype `typeName`
  559. // extends, or on a protocol / trait it conforms to (e.g. a Swift protocol-
  560. // extension method, a C# default-interface or extension method, a Kotlin
  561. // extension on a supertype). Walk supertypes transitively (depth-capped) via
  562. // the resolved implements/extends edges — empty in the first resolution pass,
  563. // populated in the conformance pass. Still VALIDATED (the method must exist on
  564. // a supertype), so a wrong inference produces no edge.
  565. if (depth < 4 && context.getSupertypes) {
  566. const viaSupers = nmTimedT('rmot-supers', ref, (): ResolvedRef | null => {
  567. for (const supertype of context.getSupertypes!(typeName, ref.language)) {
  568. const via = resolveMethodOnType(
  569. supertype, methodName, ref, context, confidence, resolvedBy, preferredFqn, depth + 1,
  570. );
  571. if (via) return via;
  572. }
  573. return null;
  574. });
  575. if (viaSupers) return viaSupers;
  576. }
  577. return null;
  578. }
  579. if (matches.length > 1 && preferredFqn) {
  580. const ext = ref.language === 'kotlin' ? '.kt' : '.java';
  581. const fqnPath = preferredFqn.replace(/\./g, '/') + ext;
  582. const chosen = matches.find((m) => {
  583. const fp = m.filePath.replace(/\\/g, '/');
  584. return fp.endsWith(fqnPath) || fp.endsWith('/' + fqnPath);
  585. });
  586. if (chosen) {
  587. return {
  588. original: ref,
  589. targetNodeId: chosen.id,
  590. confidence,
  591. resolvedBy,
  592. };
  593. }
  594. }
  595. // Language-agnostic disambiguation: when several same-named methods survive
  596. // (e.g. two files each declaring `class Logger { void log(); }` — an ODR
  597. // clash, an anonymous-namespace type, or separate translation units), prefer
  598. // the definition in the CALL SITE's own file. Without this, every ambiguous
  599. // call collapses onto the first-indexed definition, so a call in `b/svc.cpp`
  600. // wrongly points at `a/svc.cpp` (#1079). This runs AFTER the `preferredFqn`
  601. // block, so Java/Kotlin import disambiguation — whose target is intentionally
  602. // in ANOTHER file (#314) — is unaffected: that block returns early whenever
  603. // an import FQN pins the class.
  604. const ordered = preferCallSiteFile(matches, ref.filePath);
  605. return {
  606. original: ref,
  607. targetNodeId: ordered[0]!.id,
  608. confidence,
  609. resolvedBy,
  610. };
  611. }
  612. // C++ keywords/control-flow tokens that can appear right before a receiver
  613. // (e.g. `return ptr->m()`) and must NOT be treated as a type.
  614. const CPP_NON_TYPE_TOKENS = new Set([
  615. 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
  616. 'break', 'continue', 'goto', 'throw', 'new', 'delete', 'co_await', 'co_yield',
  617. 'co_return', 'static_cast', 'const_cast', 'dynamic_cast', 'reinterpret_cast',
  618. 'sizeof', 'alignof', 'typeid', 'and', 'or', 'not', 'xor',
  619. ]);
  620. function normalizeCppTypeName(typeName: string): string | null {
  621. const normalized = typeName
  622. .replace(/\b(const|volatile|mutable|typename|class|struct)\b/g, ' ')
  623. .replace(/[&*]+/g, ' ')
  624. .replace(/<[^>]*>/g, ' ')
  625. .replace(/\s+/g, ' ')
  626. .trim();
  627. if (!normalized) return null;
  628. const parts = normalized.split(/::/).filter(Boolean);
  629. const last = parts[parts.length - 1];
  630. if (!last) return null;
  631. if (CPP_NON_TYPE_TOKENS.has(last)) return null;
  632. return last;
  633. }
  634. // Declarator regex: matches `Type receiver`, `Type* receiver`, `Type *receiver`,
  635. // `Type*receiver`, `Type<X> receiver`, etc., REQUIRING a declarator terminator
  636. // (`;`, `=`, `,`, `)`, `[`, `{`, `(`, or end-of-line) after the receiver. The
  637. // terminator rules out uses like `return receiver->m()` where the preceding
  638. // token is a keyword, not a type.
  639. function buildDeclaratorRegex(escapedReceiver: string): RegExp {
  640. return new RegExp(
  641. `([A-Za-z_][\\w:]*(?:\\s*<[^;=(){}]+>)?(?:\\s*[*&]+)?)\\s*\\b${escapedReceiver}\\b\\s*(?=[;=,)\\[{(]|$)`,
  642. );
  643. }
  644. function inferCppReceiverType(
  645. receiverName: string,
  646. ref: UnresolvedRef,
  647. context: ResolutionContext,
  648. depth = 0,
  649. ): string | null {
  650. // Per-file lines cache when available — this runs per `receiver->method()`
  651. // ref and re-splitting the file each time is the same quadratic as the
  652. // shared inferrer's (#1122).
  653. const lines = context.getFileLines
  654. ? context.getFileLines(ref.filePath)
  655. : (context.readFile(ref.filePath)?.split(/\r?\n/) ?? null);
  656. if (!lines || lines.length === 0) return null;
  657. const callLineIndex = Math.max(0, Math.min(lines.length - 1, ref.line - 1));
  658. const escapedReceiver = receiverName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  659. const receiverPattern = new RegExp(`\\b${escapedReceiver}\\b`);
  660. const declaratorRegex = buildDeclaratorRegex(escapedReceiver);
  661. for (let i = callLineIndex; i >= 0; i--) {
  662. const line = lines[i];
  663. if (!line || !receiverPattern.test(line)) continue;
  664. const declaratorMatch = line.match(declaratorRegex);
  665. if (declaratorMatch) {
  666. const normalized = normalizeCppTypeName(declaratorMatch[1] ?? '');
  667. if (normalized === 'auto') {
  668. // `auto x = Foo::instance();` — the declared type is deduced; recover it
  669. // from the initializer (call return type / construction) (#645).
  670. const initType = inferCppAutoInitializerType(line, receiverName, ref, context, depth);
  671. if (initType) return initType;
  672. // No usable initializer on this line — keep scanning earlier ones.
  673. } else if (normalized) {
  674. return normalized;
  675. }
  676. }
  677. }
  678. const headerCandidates = [
  679. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.h'),
  680. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.hpp'),
  681. ref.filePath.replace(/\.(?:c|cc|cpp|cxx)$/i, '.hxx'),
  682. ].filter((candidate, index, arr) => arr.indexOf(candidate) === index && candidate !== ref.filePath);
  683. for (const headerPath of headerCandidates) {
  684. if (!context.fileExists(headerPath)) continue;
  685. const headerLines = context.getFileLines
  686. ? context.getFileLines(headerPath)
  687. : (context.readFile(headerPath)?.split(/\r?\n/) ?? null);
  688. if (!headerLines) continue;
  689. for (const line of headerLines) {
  690. if (!receiverPattern.test(line)) continue;
  691. const declaratorMatch = line.match(declaratorRegex);
  692. if (!declaratorMatch) continue;
  693. const normalized = normalizeCppTypeName(declaratorMatch[1] ?? '');
  694. if (normalized && normalized !== 'auto') return normalized;
  695. }
  696. }
  697. return null;
  698. }
  699. /**
  700. * Last `::`-separated segment of a (possibly namespace-qualified) C++ name.
  701. */
  702. function cppLastSegment(name: string): string {
  703. const parts = name.split('::').filter(Boolean);
  704. return parts[parts.length - 1] ?? name;
  705. }
  706. /**
  707. * Return type captured at extraction for `Class::method` (or a free function),
  708. * read off the indexed node's `returnType` — used by the C++ (#645) and PHP
  709. * (#608) chained-call resolvers. Language-filtered. Null when not indexed or no
  710. * return type was recorded (a `void`/primitive return).
  711. */
  712. function lookupCalleeReturnType(
  713. callee: string,
  714. ref: UnresolvedRef,
  715. context: ResolutionContext,
  716. ): string | null {
  717. let method = callee;
  718. let cls: string | null = null;
  719. if (callee.includes('::')) {
  720. const parts = callee.split('::').filter(Boolean);
  721. method = parts[parts.length - 1] ?? callee;
  722. cls = parts.slice(0, -1).join('::');
  723. }
  724. const candidates = context.getNodesByName(method).filter(
  725. (n) =>
  726. (n.kind === 'method' || n.kind === 'function') &&
  727. n.language === ref.language &&
  728. !!n.returnType,
  729. );
  730. if (cls) {
  731. const want = `${cls}::${method}`;
  732. // The call site may name the class with MORE namespace qualification than
  733. // the stored node (`details::registry::instance` at the call vs
  734. // `registry::instance` on the node — the receiver type only carries the
  735. // immediate class), or LESS. Accept an exact match or either being a
  736. // namespace-suffix of the other; the shared `::<class>::<method>` tail keeps
  737. // it specific.
  738. const m = candidates.find(
  739. (n) =>
  740. n.qualifiedName === want ||
  741. n.qualifiedName.endsWith(`::${want}`) ||
  742. want.endsWith(`::${n.qualifiedName}`),
  743. );
  744. return m?.returnType ?? null;
  745. }
  746. return candidates.find((n) => n.kind === 'function')?.returnType ?? null;
  747. }
  748. /** Does the graph contain an aggregate type named `name`'s last segment? */
  749. function cppClassExists(name: string, ref: UnresolvedRef, context: ResolutionContext): boolean {
  750. const last = cppLastSegment(name);
  751. return context
  752. .getNodesByName(last)
  753. .some((n) => (n.kind === 'class' || n.kind === 'struct' || n.kind === 'union') && n.language === ref.language);
  754. }
  755. /**
  756. * Infer the class produced by a C++ call/construction expression, using return
  757. * types captured at extraction (#645). Handles, in order:
  758. * - `make_unique<T>()` / `make_shared<T>()` → T
  759. * - single-level member call `recv.method()` → recv's type, then method's return
  760. * - `Class::method()` / free `func()` → the callee's recorded return type
  761. * - direct construction `Type()` / `ns::Type()` → Type
  762. * Returns null when undeterminable. Callers MUST still validate the outer method
  763. * exists on the result before creating an edge, so a wrong guess stays silent.
  764. */
  765. function resolveCppCallResultType(
  766. inner: string,
  767. ref: UnresolvedRef,
  768. context: ResolutionContext,
  769. depth = 0,
  770. ): string | null {
  771. if (depth > 3) return null; // guard against pathological mutual recursion
  772. const expr = inner.trim();
  773. const make = expr.match(/(?:^|::)(?:make_unique|make_shared)\s*<\s*([A-Za-z_]\w*)/);
  774. if (make) return make[1] ?? null;
  775. // Single-level member call `recv.method` (the `manager.view().render()` shape).
  776. const dotIdx = expr.lastIndexOf('.');
  777. if (dotIdx > 0) {
  778. const recv = expr.slice(0, dotIdx);
  779. const method = expr.slice(dotIdx + 1);
  780. if (recv.includes('.') || recv.includes('(') || recv.includes('::')) return null; // single level only
  781. const recvType = inferCppReceiverType(recv, ref, context, depth + 1);
  782. if (!recvType) return null;
  783. return lookupCalleeReturnType(`${recvType}::${method}`, ref, context);
  784. }
  785. const ret = lookupCalleeReturnType(expr, ref, context);
  786. if (ret) return ret;
  787. // Direct construction — the callee itself names a class/struct.
  788. if (cppClassExists(expr, ref, context)) return cppLastSegment(expr);
  789. return null;
  790. }
  791. /**
  792. * Recover the type of an `auto`-declared local from its initializer on the
  793. * declaration line — `auto x = Foo::instance();`, `auto w = make_unique<W>();`,
  794. * `auto p = new W();`, `auto w = Widget();` (#645).
  795. */
  796. function inferCppAutoInitializerType(
  797. line: string,
  798. receiverName: string,
  799. ref: UnresolvedRef,
  800. context: ResolutionContext,
  801. depth: number,
  802. ): string | null {
  803. const escaped = receiverName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  804. const m = line.match(new RegExp(`\\b${escaped}\\b\\s*=\\s*([^;]+)`));
  805. if (!m || !m[1]) return null;
  806. const init = m[1].trim();
  807. const neu = init.match(/^new\s+([A-Za-z_][\w:]*)/);
  808. if (neu && neu[1]) return cppLastSegment(neu[1]);
  809. // A call or construction: `Foo(...)`, `A::b(...)`, `make_unique<T>(...)`.
  810. const call = init.match(/^([A-Za-z_][\w:]*(?:\s*<[^>;]*>)?)\s*\(/);
  811. if (call && call[1]) return resolveCppCallResultType(call[1].replace(/\s+/g, ''), ref, context, depth + 1);
  812. return null;
  813. }
  814. /**
  815. * Resolve a C++ chained call whose receiver is itself a call — encoded by the
  816. * extractor as `<innerCallee>().<method>` (#645). The receiver's type is what
  817. * the inner call returns; the outer method is then resolved and VALIDATED on it
  818. * (resolveMethodOnType requires `cls::method` to exist), so a wrong inference
  819. * produces no edge rather than a wrong one.
  820. */
  821. export function matchCppCallChain(
  822. ref: UnresolvedRef,
  823. context: ResolutionContext,
  824. ): ResolvedRef | null {
  825. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  826. if (!m || !m[1] || !m[2]) return null;
  827. const cls = resolveCppCallResultType(m[1], ref, context);
  828. if (!cls) return null;
  829. return resolveMethodOnType(cls, m[2], ref, context, 0.85, 'instance-method');
  830. }
  831. /**
  832. * Resolve a `::`-scoped factory chain whose receiver is a scoped/static call —
  833. * PHP `Cls::for($x)->method()` (#608, the per-credential Laravel client idiom) or
  834. * Rust `Foo::new().bar()` (an associated-function call) — both encoded by the
  835. * extractor as `Cls::factory().method`. The receiver's type is what `Cls::factory`
  836. * returns: a `self` marker (PHP `: self`/`: static`, Rust `-> Self`) resolves to
  837. * the factory's own type, a concrete return type to that type. The outer method is
  838. * then resolved and VALIDATED on it (resolveMethodOnType requires the method to
  839. * exist on the type or a supertype it conforms to), so a wrong inference yields no
  840. * edge rather than a wrong one. Shared by the `::`-receiver languages (PHP, Rust).
  841. */
  842. export function matchScopedCallChain(
  843. ref: UnresolvedRef,
  844. context: ResolutionContext,
  845. ): ResolvedRef | null {
  846. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  847. if (!m || !m[1] || !m[2]) return null;
  848. const inner = m[1];
  849. const method = m[2];
  850. if (!inner.includes('::')) return null; // only static-factory (`Cls::method`) chains
  851. const factoryClass = inner.slice(0, inner.lastIndexOf('::'));
  852. const ret = lookupCalleeReturnType(inner, ref, context);
  853. if (!ret) return null;
  854. // `self` (the extractor's marker for self/static/$this) → the factory's class.
  855. const resolvedClass = ret === 'self' ? factoryClass : ret;
  856. return resolveMethodOnType(resolvedClass, method, ref, context, 0.85, 'instance-method');
  857. }
  858. /**
  859. * Languages where an unprefixed capitalized call `Foo(args)` constructs the
  860. * class (so a `Foo(args).method()` receiver's type is `Foo`). Java/C# need `new`,
  861. * so a bare `Foo()` there is a method call, not construction — excluded. Scala's
  862. * `Foo(args)` is a case-class / companion `apply`, which conventionally returns
  863. * `Foo` — and resolveMethodOnType validates, so a non-conventional `apply` that
  864. * returns another type simply yields no edge rather than a wrong one. Pascal/Delphi:
  865. * a `TFoo(x)` is a TYPECAST whose result is a `TFoo`, so `TFoo(x).method()` resolves
  866. * the method on `TFoo` — same shape, same validation.
  867. */
  868. const CONSTRUCTS_VIA_BARE_CALL = new Set(['kotlin', 'swift', 'scala', 'dart', 'pascal']);
  869. /**
  870. * Resolve a dotted chained call whose receiver is a static factory / fluent call —
  871. * `Foo.getInstance().bar()`, encoded by the extractor as `Foo.getInstance().bar`
  872. * (#645/#608 mechanism). The receiver's type is what `Foo.getInstance` returns
  873. * (its declared return type); the outer method is then resolved and VALIDATED on
  874. * it (resolveMethodOnType requires `Type::method` to exist), so a wrong inference
  875. * yields no edge rather than a wrong one (e.g. a same-named `bar()` on an
  876. * unrelated class is never matched). Shared by the dot-notation languages
  877. * (Java, Kotlin, C#, Swift) — same receiver shape, same `Class::method` qualified names.
  878. */
  879. export function matchDottedCallChain(
  880. ref: UnresolvedRef,
  881. context: ResolutionContext,
  882. ): ResolvedRef | null {
  883. const m = ref.referenceName.match(/^(.+)\(\)\.(\w+)$/);
  884. if (!m || !m[1] || !m[2]) return null;
  885. const inner = m[1]; // `Foo.getInstance`
  886. const method = m[2]; // `bar`
  887. const lastDot = inner.lastIndexOf('.');
  888. if (lastDot <= 0) {
  889. // Go: bare package-level factory FUNCTION `New().method()` — the receiver's
  890. // type is what `New` returns; resolve the method on that.
  891. if (ref.language === 'go') {
  892. const ret = lookupCalleeReturnType(inner, ref, context);
  893. if (ret) {
  894. return resolveMethodOnType(ret, method, ref, context, 0.85, 'instance-method', importedFqnOf(ret, ref, context));
  895. }
  896. // `inner` isn't a function with a captured return type — typically a
  897. // package-level VARIABLE holding a function value (e.g. gin's `engine()`),
  898. // whose type we can't recover. Fall back to bare-name resolution of the
  899. // method so we don't DROP an edge the un-re-encoded bare path would have
  900. // found. (When `inner` IS a real factory function but the method doesn't
  901. // exist on its return type, `ret` is truthy and we returned no edge above —
  902. // the absent-method safety guarantee is preserved.)
  903. //
  904. // CRITICAL: resolve the TARGET via a synthetic bare-name ref, but return the
  905. // match tied to the ORIGINAL `ref` (referenceName `inner().method`). The
  906. // batched resolver (resolveAndPersistBatched) reads unresolved rows from
  907. // offset 0 every pass and relies on the post-batch cleanup (row-id delete
  908. // for DB-loaded refs, referenceName-keyed delete otherwise, #1269) to
  909. // clear each resolved row so the batch empties. If we propagated the
  910. // synthetic ref's bare `method` as `.original`, a key-based delete
  911. // would never match the stored `inner().method` row, the batch would
  912. // never drain, and the loop would re-resolve + re-insert forever (a runaway
  913. // that grew gin's graph to 5M edges / 1.4 GB before this fix).
  914. const bareRef = { ...ref, referenceName: method };
  915. const bareMatch = matchByExactName(bareRef, context) ?? matchFuzzy(bareRef, context);
  916. return bareMatch ? { ...bareMatch, original: ref } : null;
  917. }
  918. // Constructor receiver `Foo(args).method()` (encoded `Foo().method`): a bare,
  919. // capitalized inner is a class construction, so the receiver's type is the
  920. // class itself — resolve the method on it. Only in languages where an
  921. // unprefixed capitalized call constructs the class (Kotlin, Swift); in Java/C#
  922. // a bare `Foo()` is a method call (constructors need `new`), so we must not
  923. // assume construction. A lowercase bare inner is a top-level `factory().method()`
  924. // whose type we can't recover — bail.
  925. if (!CONSTRUCTS_VIA_BARE_CALL.has(ref.language) || !/^[A-Z]/.test(inner)) return null;
  926. return resolveMethodOnType(inner, method, ref, context, 0.85, 'instance-method', importedFqnOf(inner, ref, context));
  927. }
  928. // Factory/fluent receiver `Receiver.factory(args).method()`: the receiver's
  929. // type is what `Receiver.factory` returns (its declared return type).
  930. const factoryClass = inner.slice(0, lastDot).split('.').pop(); // simple class name
  931. const factoryMethod = inner.slice(lastDot + 1);
  932. if (!factoryClass || !factoryMethod) return null;
  933. const ret = lookupCalleeReturnType(`${factoryClass}::${factoryMethod}`, ref, context);
  934. if (!ret) {
  935. // Objective-C: a class-message factory — `[X alloc]`, `[X new]`,
  936. // `[X sharedFoo]` — returns an instance of the RECEIVER class `X` by
  937. // convention (`instancetype`). So when the factory's own return type isn't
  938. // recoverable (its selector returns `instancetype`, or `alloc`/`new` aren't
  939. // user-defined nodes at all), the receiver's type is the class `X` itself.
  940. // This resolves the ubiquitous `[[X alloc] init]` and singleton chains.
  941. // resolveMethodOnType validates against X (and its supertypes), so a class
  942. // whose method actually lives elsewhere yields NO edge, not a wrong one — and
  943. // crucially this does NOT fire when a concrete return type WAS captured but
  944. // simply lacks the method (that already returned null above: absent-method
  945. // safety, so a same-named decoy is still never matched).
  946. if (ref.language === 'objc' && /^[A-Z]/.test(factoryClass)) {
  947. return resolveMethodOnType(factoryClass, method, ref, context, 0.8, 'instance-method', importedFqnOf(factoryClass, ref, context));
  948. }
  949. // Pascal/Delphi: the extractor only re-encodes a `TFoo`/`IFoo`-prefixed chain
  950. // (the type-naming convention), so `factoryClass` is always a real class here.
  951. // A factory whose return type wasn't captured is a CONSTRUCTOR
  952. // (`TFileMem.Create().SetCachePerformance` — `constructor Create` has no `:
  953. // TBar` annotation but returns its own class) or an unannotated function. In
  954. // both cases the receiver's type is the class itself, so resolve the method on
  955. // `factoryClass`. resolveMethodOnType validates against it (and its
  956. // supertypes), so a wrong inference yields no edge — and this never fires when
  957. // a return type WAS captured but lacks the method (absent-method safety above).
  958. if (ref.language === 'pascal' && /^[TI]/.test(factoryClass)) {
  959. return resolveMethodOnType(factoryClass, method, ref, context, 0.8, 'instance-method', importedFqnOf(factoryClass, ref, context));
  960. }
  961. return null;
  962. }
  963. return resolveMethodOnType(ret, method, ref, context, 0.85, 'instance-method', importedFqnOf(ret, ref, context));
  964. }
  965. /**
  966. * When several classes share a simple type name, the caller file's import of
  967. * that type is the only signal that names WHICH one (#314). Returns the imported
  968. * FQN for `typeName` in the ref's file, or undefined.
  969. */
  970. function importedFqnOf(
  971. typeName: string,
  972. ref: UnresolvedRef,
  973. context: ResolutionContext,
  974. ): string | undefined {
  975. const imports = context.getImportMappings(ref.filePath, ref.language);
  976. return imports.find((i) => i.localName === typeName)?.source;
  977. }
  978. /**
  979. * Java/Kotlin: infer a receiver's declared type by walking field declarations
  980. * in the class enclosing the call site. The field's `signature` is already in
  981. * the form "<TypeName> <fieldName>" (set by tree-sitter.ts extractField), so we
  982. * pull the type from there. Handles Spring `@Resource UserBO userbo;` /
  983. * `@Autowired private UserService userService;` where the receiver field name
  984. * doesn't match the class name by Java naming convention.
  985. *
  986. * Returns the bare type name (generics stripped, dotted package stripped) or
  987. * null when no matching field is in the enclosing class.
  988. */
  989. function inferJavaFieldReceiverType(
  990. receiverName: string,
  991. ref: UnresolvedRef,
  992. context: ResolutionContext,
  993. ): string | null {
  994. const inFile = context.getNodesInFile(ref.filePath);
  995. if (inFile.length === 0) return null;
  996. // Find the class enclosing the call line (tightest match by latest start).
  997. let enclosing: Node | null = null;
  998. for (const n of inFile) {
  999. if (n.kind !== 'class' && n.kind !== 'interface') continue;
  1000. if (n.language !== ref.language) continue;
  1001. const end = n.endLine ?? n.startLine;
  1002. if (n.startLine <= ref.line && end >= ref.line) {
  1003. if (!enclosing || n.startLine >= enclosing.startLine) enclosing = n;
  1004. }
  1005. }
  1006. if (!enclosing) return null;
  1007. const enclosingEnd = enclosing.endLine ?? enclosing.startLine;
  1008. const field = inFile.find(
  1009. (n) =>
  1010. n.kind === 'field' &&
  1011. n.name === receiverName &&
  1012. n.language === ref.language &&
  1013. n.startLine >= enclosing.startLine &&
  1014. (n.endLine ?? n.startLine) <= enclosingEnd,
  1015. );
  1016. if (!field || !field.signature) return null;
  1017. // Signature shape: "<TypeName> <fieldName>" (extractField). Pull the type,
  1018. // strip generics + dotted package, drop array/varargs markers.
  1019. const beforeName = field.signature.slice(
  1020. 0,
  1021. field.signature.lastIndexOf(field.name),
  1022. );
  1023. const typeRaw = beforeName.trim();
  1024. if (!typeRaw) return null;
  1025. const typeNoGenerics = typeRaw.replace(/<[^>]*>/g, '').trim();
  1026. const typeNoArray = typeNoGenerics.replace(/\[\s*\]/g, '').replace(/\.\.\.$/, '').trim();
  1027. const parts = typeNoArray.split(/[.\s]+/).filter(Boolean);
  1028. const lastPart = parts[parts.length - 1];
  1029. if (!lastPart) return null;
  1030. if (!/^[A-Z]/.test(lastPart)) return null; // primitives / lowercase → skip
  1031. return lastPart;
  1032. }
  1033. // ── Local-variable receiver-type inference (#1108) ──────────────────────────
  1034. //
  1035. // Instance calls through a local variable (`const lg = new Logger(); lg.log()`)
  1036. // only resolved in C++ before this — no other language could learn the
  1037. // receiver's type. Local variables are not indexed as nodes (node-explosion),
  1038. // so, like the C++ inferrer above, we read the enclosing function's source and
  1039. // match the receiver's declaration/initializer to recover its type. The type is
  1040. // then handed to resolveMethodOnType, which VALIDATES that the type actually
  1041. // declares the method, so a mis-inference produces NO edge — the safety net
  1042. // that lets the patterns below stay simple. C++ keeps its dedicated inferrer
  1043. // (header scan + `auto`); this covers every other language.
  1044. // Tokens a loose pattern might capture that are never a user-defined type.
  1045. const NON_TYPE_RECEIVER_TOKENS = new Set([
  1046. 'this', 'self', 'super', 'new', 'return', 'await', 'yield', 'typeof',
  1047. 'null', 'nil', 'None', 'true', 'false', 'True', 'False', 'undefined',
  1048. ]);
  1049. /**
  1050. * Normalize a captured type expression to a simple type name: drop generic
  1051. * args and pointer/ref markers, take the last `.`/`::`-qualified segment, and
  1052. * reject obvious non-types.
  1053. */
  1054. export function normalizeInferredTypeName(raw: string): string | null {
  1055. const cleaned = raw.replace(/<[^>]*>/g, '').replace(/[&*]/g, '').trim();
  1056. const seg = cleaned.split(/[.:]+/).filter(Boolean).pop();
  1057. if (!seg) return null;
  1058. if (NON_TYPE_RECEIVER_TOKENS.has(seg)) return null;
  1059. return seg;
  1060. }
  1061. /**
  1062. * Per-language patterns that recover a local variable's (or typed parameter's)
  1063. * type from its declaration/initializer. Each regex captures the type in group
  1064. * 1; `r` is the already-escaped receiver name. Ordered most-specific first.
  1065. * PascalCase is required in the capture where the language convention allows,
  1066. * as a cheap false-positive guard on top of resolveMethodOnType's validation.
  1067. */
  1068. /**
  1069. * Compiled-pattern memo for the receiver-type pattern builders below. They
  1070. * run for EVERY `receiver.method()` ref the matcher attempts, compiling 2–4
  1071. * fresh RegExp objects per call — and receivers repeat massively (`self`
  1072. * alone accounts for tens of thousands of refs on a Lua repo, measured 41µs
  1073. * per methodCall miss on kong with compilation a large slice). The patterns
  1074. * are a pure function of (language, receiver) and non-global (`.match()`
  1075. * never touches lastIndex), so shared instances are behavior-identical.
  1076. * FIFO-capped with no per-get mutation (the §7a.6 LRU-churn lesson): a hit
  1077. * costs one Map lookup, overflow evicts oldest, and an evicted entry simply
  1078. * recompiles exactly as every call did before this memo.
  1079. */
  1080. const PATTERN_MEMO = new Map<string, RegExp[]>();
  1081. const PATTERN_MEMO_CAP = 8192;
  1082. /**
  1083. * Per-context incremental receiver-scan states for inferLocalReceiverType
  1084. * (see the memo comment there). Keyed (file, scopeStart, language, receiver);
  1085. * entries are a few dozen bytes, count is bounded by distinct receiver uses
  1086. * (same order as the context's other per-file caches). MUST drop whenever the
  1087. * context's file caches drop — the states are derived from file lines — so
  1088. * ReferenceResolver.clearCaches calls clearNameMatcherMemos alongside
  1089. * clearImportResolverMemos.
  1090. */
  1091. type InferScanState = { hi: number; ansIdx: number; ansType: string | null };
  1092. const INFER_SCAN_STATES = new WeakMap<ResolutionContext, Map<string, InferScanState>>();
  1093. function getInferScanStates(context: ResolutionContext): Map<string, InferScanState> {
  1094. let m = INFER_SCAN_STATES.get(context);
  1095. if (!m) {
  1096. m = new Map();
  1097. INFER_SCAN_STATES.set(context, m);
  1098. }
  1099. return m;
  1100. }
  1101. /** Drop the per-context scan states (see ReferenceResolver.clearCaches). */
  1102. export function clearNameMatcherMemos(context: ResolutionContext): void {
  1103. INFER_SCAN_STATES.delete(context);
  1104. }
  1105. function memoPatterns(key: string, build: () => RegExp[]): RegExp[] {
  1106. const hit = PATTERN_MEMO.get(key);
  1107. if (hit) return hit;
  1108. const patterns = build();
  1109. if (PATTERN_MEMO.size >= PATTERN_MEMO_CAP) {
  1110. const oldest = PATTERN_MEMO.keys().next().value;
  1111. if (oldest !== undefined) PATTERN_MEMO.delete(oldest);
  1112. }
  1113. PATTERN_MEMO.set(key, patterns);
  1114. return patterns;
  1115. }
  1116. export function localReceiverTypePatterns(language: Language, r: string): RegExp[] {
  1117. return memoPatterns(`${language}|${r}`, () => buildLocalReceiverTypePatterns(language, r));
  1118. }
  1119. function buildLocalReceiverTypePatterns(language: Language, r: string): RegExp[] {
  1120. switch (language) {
  1121. case 'typescript':
  1122. case 'javascript':
  1123. case 'tsx':
  1124. case 'jsx':
  1125. case 'arkts':
  1126. return [
  1127. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_$][\\w.$]*)`), // = new Logger()
  1128. // No keyword requirement, so this matches BOTH a local annotation
  1129. // (`const lg: Logger`) and a typed parameter (`function use(lg: Logger)`
  1130. // / `(lg: Logger) =>`) — the parameter case the old `const|let|var`
  1131. // prefix excluded (#1125). Mirrors Kotlin/Swift/Scala; the capture stops
  1132. // at `<` so a generic-typed param (`repo: Repository<User>`) still yields
  1133. // `Repository`. resolveMethodOnType validates the type actually declares
  1134. // the method, so the looser match produces no edge on a mis-inference.
  1135. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.$]*)`), // lg: Logger (annotation or typed param)
  1136. ];
  1137. case 'python':
  1138. return [
  1139. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // lg = Logger(...)
  1140. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // lg: Logger (PEP 526)
  1141. ];
  1142. case 'java':
  1143. return [
  1144. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`), // = new Logger()
  1145. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg; / param
  1146. ];
  1147. case 'kotlin':
  1148. return [
  1149. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // val lg = Logger(...)
  1150. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // val lg: Logger / param
  1151. ];
  1152. case 'csharp':
  1153. return [
  1154. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`), // = new Logger()
  1155. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg; / param
  1156. ];
  1157. case 'swift':
  1158. return [
  1159. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // let lg = Logger(...)
  1160. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // let lg: Logger / param
  1161. ];
  1162. case 'rust':
  1163. return [
  1164. new RegExp(`\\blet\\s+(?:mut\\s+)?${r}\\b(?:\\s*:[^=]+)?=\\s*&?(?:mut\\s+)?([A-Z][\\w]*)`), // let lg = Logger::new()/Logger{}/Logger
  1165. // No `let`, so this covers a `let lg: Logger` binding AND a typed
  1166. // parameter (`fn use(lg: &Logger)`, a closure `|lg: Logger|`) — the
  1167. // parameter case the old `let`-anchored pattern excluded (#1125).
  1168. new RegExp(`\\b${r}\\s*:\\s*&?(?:mut\\s+)?([A-Z][\\w]*)`), // lg: Logger (binding or typed param)
  1169. ];
  1170. case 'go':
  1171. return [
  1172. new RegExp(`\\b${r}\\b\\s*:=\\s*&?([A-Za-z_][\\w.]*)\\s*{`), // lg := Logger{} / &Logger{}
  1173. new RegExp(`\\bvar\\s+${r}\\s+\\*?([A-Za-z_][\\w.]*)`), // var lg Logger / *Logger
  1174. // A typed parameter / method receiver (`func use(lg Logger)`,
  1175. // `func (l Logger) M()`) — name-before-type with no `var`/`:=` (#1125).
  1176. // PascalCase-guarded (unlike the anchored patterns above) to keep the
  1177. // keyword-free `ident Type` shape from matching unrelated pairs; the
  1178. // enclosing-scope bound already excludes package-level struct fields.
  1179. new RegExp(`\\b${r}\\s+\\*?([A-Z][\\w.]*)`), // func use(lg Logger) / (l Logger)
  1180. ];
  1181. case 'ruby':
  1182. return [
  1183. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w:]*)\\.new\\b`), // lg = Logger.new
  1184. ];
  1185. case 'scala':
  1186. return [
  1187. new RegExp(`\\b${r}\\b\\s*=\\s*(?:new\\s+)?([A-Z][\\w.]*)`), // val lg = new Logger / Logger(...)
  1188. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)`), // val lg: Logger / param
  1189. ];
  1190. case 'dart':
  1191. return [
  1192. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w.]*)\\s*\\(`), // var lg = Logger(...)
  1193. // Trailing `[=;,)]` (not just `[=;]`) so a typed parameter — `Logger lg)`
  1194. // / `Logger lg,` — matches too, not only `Logger lg = ...` / `Logger lg;`
  1195. // (#1125). Mirrors Java/C#.
  1196. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`), // Logger lg = ... / param
  1197. ];
  1198. case 'php':
  1199. return [
  1200. new RegExp(`\\$?${r}\\b\\s*=\\s*new\\s+([A-Za-z_\\\\][\\w\\\\]*)`), // $lg = new Logger()
  1201. // A typed parameter (`function use(Logger $lg)`, `?Logger $lg`,
  1202. // `\\App\\Logger $lg`, `&$lg` by-ref) and a typed `catch (E $e)` — the
  1203. // type sits before the `$`-variable (#1125). Namespace `\\` allowed.
  1204. new RegExp(`\\b([A-Za-z_\\\\][\\w\\\\]*)\\s+&?\\$${r}\\b`), // Logger $lg (typed param)
  1205. ];
  1206. case 'lua':
  1207. case 'luau':
  1208. return [
  1209. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w]*)\\.new\\b`), // local lg = Logger.new()
  1210. new RegExp(`\\b${r}\\b\\s*=\\s*([A-Z][\\w]*)\\s*\\(`), // local lg = Logger(...) (callable table)
  1211. // Luau annotation (`local lg: Logger`) / typed param — but Lua's
  1212. // method-call syntax is the IDENTICAL `receiver:Name` shape, and the
  1213. // backward scan starts on the call's own line, so without a gate any
  1214. // PascalCase method call (`lg:Log()`, the Roblox convention)
  1215. // self-matches as "type = Log" before the scan reaches the real
  1216. // declaration (#1124). The lookahead rejects a capture followed by
  1217. // any of Lua's three call forms — `(args)`, `"s"`/`'s'`/`[[s]]`,
  1218. // `{t}` — and its leading `[\w.]` alternative stops backtracking from
  1219. // shrinking the capture to dodge the gate (`lg:Log()` would otherwise
  1220. // still match, as `Lo`).
  1221. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w.]*)(?![\\w.]|\\s*[({"'\\[])`), // local lg: Logger / typed param
  1222. ];
  1223. case 'r':
  1224. return [
  1225. new RegExp(`\\b${r}\\b\\s*(?:<-|<<-|=)\\s*([A-Z][\\w.]*)\\$new\\b`), // lg <- Logger$new() (R6)
  1226. ];
  1227. case 'pascal':
  1228. return [
  1229. new RegExp(`\\b${r}\\b\\s*:\\s*([A-Z][\\w]*)`), // var lg: TLogger / param lg: TLogger
  1230. new RegExp(`\\b${r}\\b\\s*:=\\s*([A-Z][\\w.]*)\\.Create\\b`), // lg := TLogger.Create
  1231. ];
  1232. case 'cfml':
  1233. case 'cfscript':
  1234. return [
  1235. // svc = new UserService() / new path.to.UserService() — dotted component
  1236. // paths reduce to their final segment via normalizeInferredTypeName.
  1237. // Also matches inside tag markup (`<cfset svc = new UserService()>`)
  1238. // since the scan reads raw source lines.
  1239. new RegExp(`\\b${r}\\b\\s*=\\s*new\\s+([A-Za-z_][\\w.]*)`),
  1240. // The classic form: svc = createObject("component", "path.to.UserService")
  1241. // (casing of createObject varies in the wild), plus the modern
  1242. // single-argument form createObject("path.to.UserService").
  1243. new RegExp(`\\b${r}\\b\\s*=\\s*[Cc]reate[Oo]bject\\s*\\(\\s*["']component["']\\s*,\\s*["']([\\w.]+)["']`),
  1244. new RegExp(`\\b${r}\\b\\s*=\\s*[Cc]reate[Oo]bject\\s*\\(\\s*["']([\\w.]+)["']\\s*\\)`),
  1245. // Typed cfscript parameter: `function save(UserService svc)` /
  1246. // `required UserService svc` — CFML's built-in types (string, numeric,
  1247. // any, struct…) are lowercase by convention, so the PascalCase guard
  1248. // excludes them.
  1249. new RegExp(`\\b([A-Z][\\w.]*)\\s+${r}\\b\\s*[=;,)]`),
  1250. // Tag-form typed argument, either attribute order:
  1251. // <cfargument name="svc" type="path.to.UserService">
  1252. new RegExp(`\\bcfargument[^>\\n]*\\bname\\s*=\\s*["']${r}["'][^>\\n]*\\btype\\s*=\\s*["']([\\w.]+)["']`, 'i'),
  1253. new RegExp(`\\bcfargument[^>\\n]*\\btype\\s*=\\s*["']([\\w.]+)["'][^>\\n]*\\bname\\s*=\\s*["']${r}["']`, 'i'),
  1254. // Component property (incl. WireBox DI): `property name="svc"
  1255. // inject="UserService";` / `<cfproperty name="svc" type="UserService">`,
  1256. // either attribute order. An inject DSL value with a namespace
  1257. // (`inject="svc@core"`) captures only the leading name and simply
  1258. // fails type-validation — no edge, never a wrong one.
  1259. new RegExp(`\\b(?:cf)?property\\b[^;\\n]*\\bname\\s*=\\s*["']${r}["'][^;\\n]*\\b(?:type|inject)\\s*=\\s*["']([\\w.]+)["']`, 'i'),
  1260. new RegExp(`\\b(?:cf)?property\\b[^;\\n]*\\b(?:type|inject)\\s*=\\s*["']([\\w.]+)["'][^;\\n]*\\bname\\s*=\\s*["']${r}["']`, 'i'),
  1261. ];
  1262. default:
  1263. return [];
  1264. }
  1265. }
  1266. /** 1-based start line of the tightest function/method enclosing the call. */
  1267. function enclosingScopeStartLine(ref: UnresolvedRef, context: ResolutionContext): number {
  1268. let start = 1;
  1269. for (const n of context.getNodesInFile(ref.filePath)) {
  1270. if (n.kind !== 'function' && n.kind !== 'method') continue;
  1271. if (n.language !== ref.language) continue;
  1272. const end = n.endLine ?? n.startLine;
  1273. if (n.startLine <= ref.line && end >= ref.line && n.startLine >= start) {
  1274. start = n.startLine;
  1275. }
  1276. }
  1277. return start;
  1278. }
  1279. /**
  1280. * Infer a receiver's type from its local declaration/initializer in the
  1281. * enclosing function body. Language-dispatched; returns null for languages
  1282. * without patterns or when no declaration is found. Bounded to the enclosing
  1283. * scope so a same-named variable in another function can't leak in.
  1284. */
  1285. function inferLocalReceiverType(
  1286. receiverName: string,
  1287. ref: UnresolvedRef,
  1288. context: ResolutionContext,
  1289. ): string | null {
  1290. // CFML scope prefixes: `variables.svc` / `this.svc` name a COMPONENT-scoped
  1291. // field whose assignment or `property` declaration usually lives outside the
  1292. // calling function (the init-pseudoconstructor / WireBox-injection pattern),
  1293. // and `local.svc` is an explicit function-local. Strip the prefix so the
  1294. // declaration patterns match (`variables.svc = new X()`, `property
  1295. // name="svc" …`, `var svc = …` all bind the bare name), and widen the scan
  1296. // to the whole file for the component-scoped forms — nearest-declaration-
  1297. // backward still wins, so a function-local shadowing the field is preferred.
  1298. let scanReceiver = receiverName;
  1299. let componentScoped = false;
  1300. if (ref.language === 'cfml' || ref.language === 'cfscript') {
  1301. const scoped = receiverName.match(/^(variables|this|local|arguments)\.(.+)$/i);
  1302. if (scoped) {
  1303. scanReceiver = scoped[2]!;
  1304. const scope = scoped[1]!.toLowerCase();
  1305. componentScoped = scope === 'variables' || scope === 'this';
  1306. }
  1307. }
  1308. // PHP `$this->prop` receiver — the property's declaration lives outside the
  1309. // calling method (a promoted constructor parameter `private readonly Foo $prop`,
  1310. // a typed property `private Foo $prop;`, or a classic constructor parameter
  1311. // `Foo $prop` assigned in __construct). Strip the prefix and widen the scan to
  1312. // the whole file (the constructor may sit below the calling method), but —
  1313. // unlike CFML's scopes above — switch to PROPERTY-shaped patterns: a plain
  1314. // `$prop` local or parameter lives in a different namespace than `$this->prop`
  1315. // and can never shadow it, so the generic local patterns would type the
  1316. // property from unrelated same-named variables in other methods (a wrong
  1317. // 0.9-confidence edge, not a missing one).
  1318. let phpProperty = false;
  1319. if (ref.language === 'php') {
  1320. const scoped = receiverName.match(/^this->(.+)$/);
  1321. if (scoped) {
  1322. scanReceiver = scoped[1]!;
  1323. componentScoped = true;
  1324. phpProperty = true;
  1325. }
  1326. }
  1327. const escapedReceiver = scanReceiver.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1328. const patterns = phpProperty
  1329. ? phpPropertyTypePatterns(escapedReceiver)
  1330. : localReceiverTypePatterns(ref.language, escapedReceiver);
  1331. if (patterns.length === 0) return null;
  1332. // Split through the context's per-file lines cache when available: this runs
  1333. // for EVERY `receiver.method()` ref, and re-splitting the whole file per ref
  1334. // was ~20% of total index CPU on Java-heavy repos (#1122).
  1335. const lines = context.getFileLines
  1336. ? context.getFileLines(ref.filePath)
  1337. : (context.readFile(ref.filePath)?.split(/\r?\n/) ?? null);
  1338. if (!lines || lines.length === 0) return null;
  1339. const callIdx = Math.max(0, Math.min(lines.length - 1, ref.line - 1));
  1340. const startIdx = componentScoped
  1341. ? 0
  1342. : Math.max(0, enclosingScopeStartLine(ref, context) - 1);
  1343. const matchLine = (i: number): string | null => {
  1344. const line = lines[i];
  1345. if (!line) return null;
  1346. // A generated/minified line (one multi-KB statement) is not something a
  1347. // human-written local declaration lives on, and regexing it per ref is
  1348. // pure waste — skip it rather than scan it.
  1349. if (line.length > 10_000) return null;
  1350. for (const re of patterns) {
  1351. const m = line.match(re);
  1352. if (m && m[1]) {
  1353. const type = normalizeInferredTypeName(m[1]);
  1354. if (type) return type;
  1355. }
  1356. }
  1357. return null;
  1358. };
  1359. // Incremental-scan memo (INFER_SCAN_STATES): this scan runs for EVERY
  1360. // `receiver.method()` ref and was measured at 61µs/ref on kong (2.4s of
  1361. // worker time, 99% misses — `self:` calls hunting a declaration Lua never
  1362. // writes). Refs for the same (file, scope, receiver) arrive in ~ascending
  1363. // line order, and the scan is a pure function of the file's immutable
  1364. // lines, so each line pays its regex matches ONCE per key instead of once
  1365. // per ref: query(c) = highest matching line in [startIdx..c]; a monotonic
  1366. // call extends the stored watermark by scanning only (hi..c] (the region
  1367. // at-or-below the previous answer is already proven empty above it); a
  1368. // non-monotonic call (rare — refs are rowid-ordered) falls back to the
  1369. // plain bounded scan and leaves the state alone. componentScoped is keyed
  1370. // out — its position-independent whole-file sweep below has different
  1371. // semantics.
  1372. if (!componentScoped) {
  1373. const states = getInferScanStates(context);
  1374. const key = `${ref.filePath}|${startIdx}|${ref.language}|${scanReceiver}`;
  1375. const state = states.get(key);
  1376. if (!state) {
  1377. for (let i = callIdx; i >= startIdx; i--) {
  1378. const type = matchLine(i);
  1379. if (type) {
  1380. states.set(key, { hi: callIdx, ansIdx: i, ansType: type });
  1381. return type;
  1382. }
  1383. }
  1384. states.set(key, { hi: callIdx, ansIdx: -1, ansType: null });
  1385. return null;
  1386. }
  1387. if (callIdx >= state.hi) {
  1388. for (let i = callIdx; i > state.hi; i--) {
  1389. const type = matchLine(i);
  1390. if (type) {
  1391. state.ansIdx = i;
  1392. state.ansType = type;
  1393. break;
  1394. }
  1395. }
  1396. state.hi = callIdx;
  1397. return state.ansIdx >= startIdx ? state.ansType : null;
  1398. }
  1399. for (let i = callIdx; i >= startIdx; i--) {
  1400. const type = matchLine(i);
  1401. if (type) return type;
  1402. }
  1403. return null;
  1404. }
  1405. // Nearest declaration wins: scan backward from the call to the scope start.
  1406. for (let i = callIdx; i >= startIdx; i--) {
  1407. const type = matchLine(i);
  1408. if (type) return type;
  1409. }
  1410. // A component-scoped field's declaration is position-independent — the
  1411. // `variables.svc = new X()` pseudoconstructor assignment or `property`
  1412. // declaration may sit BELOW the calling function in the file — so when the
  1413. // backward pass finds nothing, sweep the remainder of the file too.
  1414. if (componentScoped) {
  1415. for (let i = callIdx + 1; i < lines.length; i++) {
  1416. const type = matchLine(i);
  1417. if (type) return type;
  1418. }
  1419. }
  1420. // A PHP property with no statically-typed declaration (classic pre-7.4
  1421. // style) may still be typed by what gets ASSIGNED to it — follow the
  1422. // `$this->prop = $var` assignment to the assigned variable's own typed
  1423. // declaration (a classic or multi-line constructor parameter, or a typed
  1424. // setter's parameter).
  1425. if (phpProperty) {
  1426. return inferPhpAssignedPropertyType(escapedReceiver, lines, callIdx);
  1427. }
  1428. return null;
  1429. }
  1430. /**
  1431. * Patterns that recover a PHP class property's declared type for a
  1432. * `$this->prop` receiver. Deliberately NOT localReceiverTypePatterns: only
  1433. * property-shaped declarations qualify —
  1434. * 1. a modifier-prefixed typed declaration, which covers both a typed
  1435. * property (`private ?Foo $prop;`) and a promoted constructor parameter
  1436. * (`private readonly Foo $prop`), and
  1437. * 2. the pseudoconstructor assignment (`$this->prop = new Foo(...)`).
  1438. * A bare `X $prop` parameter or `$prop = new X()` local elsewhere in the
  1439. * file must NOT match: those variables can never alias `$this->prop`.
  1440. * Union-typed properties (`Foo|Bar $prop`) yield no match and thus no edge —
  1441. * silent beats wrong. The classic untyped-property-assigned-in-constructor
  1442. * shape is handled by inferPhpAssignedPropertyType instead.
  1443. */
  1444. function phpPropertyTypePatterns(r: string): RegExp[] {
  1445. return memoPatterns(`php-prop|${r}`, () => buildPhpPropertyTypePatterns(r));
  1446. }
  1447. function buildPhpPropertyTypePatterns(r: string): RegExp[] {
  1448. return [
  1449. new RegExp(
  1450. `\\b(?:(?:private|protected|public|readonly|static|final)(?:\\(set\\))?\\s+)+\\??([A-Za-z_\\\\][\\w\\\\]*)\\s+&?\\$${r}\\b`,
  1451. ), // private readonly ?Foo $prop (typed property / promoted param)
  1452. new RegExp(`\\$this->${r}\\b\\s*=\\s*new\\s+([A-Za-z_\\\\][\\w\\\\]*)`), // $this->prop = new Foo()
  1453. ];
  1454. }
  1455. /**
  1456. * Second-chance typing for a PHP `$this->prop` receiver whose property
  1457. * declaration carries no static type (classic pre-7.4 style): find the
  1458. * `$this->prop = $var` assignment, then recover `$var`'s type from its own
  1459. * declaration WITHIN the assignment's function — the constructor's (possibly
  1460. * multi-line) parameter list, a typed setter's parameter, or a `= new X()`
  1461. * local. The backward scan stops at the enclosing `function` line (checked
  1462. * for a match first — a single-line `__construct(Foo $var) { ... }` carries
  1463. * the typed parameter itself), so a same-named variable in another method
  1464. * can never type the property.
  1465. */
  1466. function inferPhpAssignedPropertyType(
  1467. escapedProp: string,
  1468. lines: string[],
  1469. callIdx: number,
  1470. ): string | null {
  1471. const assignRe = new RegExp(`\\$this->${escapedProp}\\b\\s*=\\s*\\$(\\w+)\\b`);
  1472. const assignAt = (i: number): RegExpMatchArray | null => {
  1473. const line = lines[i];
  1474. if (!line || line.length > 10_000) return null;
  1475. return line.match(assignRe);
  1476. };
  1477. // The assignment is position-independent relative to the call — nearest-
  1478. // backward first, then sweep forward, same order as the componentScoped scan.
  1479. let assignIdx = -1;
  1480. let varName: string | null = null;
  1481. for (let i = callIdx; i >= 0; i--) {
  1482. const m = assignAt(i);
  1483. if (m) { assignIdx = i; varName = m[1]!; break; }
  1484. }
  1485. if (varName === null) {
  1486. for (let i = callIdx + 1; i < lines.length; i++) {
  1487. const m = assignAt(i);
  1488. if (m) { assignIdx = i; varName = m[1]!; break; }
  1489. }
  1490. }
  1491. if (varName === null) return null;
  1492. const varPatterns = localReceiverTypePatterns(
  1493. 'php',
  1494. varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
  1495. );
  1496. for (let i = assignIdx; i >= 0; i--) {
  1497. const line = lines[i];
  1498. if (line && line.length <= 10_000) {
  1499. for (const re of varPatterns) {
  1500. const m = line.match(re);
  1501. if (m && m[1]) {
  1502. const type = normalizeInferredTypeName(m[1]);
  1503. if (type) return type;
  1504. }
  1505. }
  1506. }
  1507. if (line && /\bfunction\b/.test(line)) break;
  1508. }
  1509. return null;
  1510. }
  1511. /**
  1512. * Try to resolve by method name on a class/object
  1513. */
  1514. export function matchMethodCall(
  1515. ref: UnresolvedRef,
  1516. context: ResolutionContext
  1517. ): ResolvedRef | null {
  1518. // Parse method call patterns like "obj.method" or "Class::method". The method
  1519. // part allows trailing `:` keywords so Objective-C selectors resolve
  1520. // (`SDImageCache.storeImage:`, `obj.setX:y:`); colons never appear in other
  1521. // languages' method refs, so this is a no-op for them.
  1522. // The receiver allows dots (`builder.Services.AddCoreServices`) so a CHAINED
  1523. // call resolves by its last segment — Strategy 3 below name-matches the method
  1524. // (with its existing single-candidate / receiver-overlap guards). Without this
  1525. // a multi-dot extension-method call (C# DI `builder.Services.AddCoreServices()`,
  1526. // `Guard.Against.X()`) matched no pattern and never resolved.
  1527. // C++ explicit operator call `a.operator+(b)` reaches the resolver as
  1528. // `a.operator+` (#1247) — the operator's symbol chars (`+`, `==`, `[]`, `()`)
  1529. // fail the \w method part of the plain pattern, so admit them explicitly.
  1530. // Names like `operatorTable` stay on the plain pattern (tried first); the
  1531. // operator form requires at least one non-word char after `operator`, and
  1532. // every downstream strategy compares the method part by exact string
  1533. // equality, so a stray match can't invent an edge.
  1534. const dotMatch =
  1535. ref.referenceName.match(/^([\w.]+)\.(\w+:?(?:\w+:)*)$/) ??
  1536. (ref.language === 'cpp'
  1537. ? ref.referenceName.match(/^([\w.]+)\.(operator[^\w\s.]+)$/)
  1538. : null);
  1539. const colonMatch = ref.referenceName.match(/^(\w+)::(\w+)$/);
  1540. // Lua/Luau method calls use a single colon (`lg:log`); R uses `$` (`lg$log`).
  1541. // Recognize these receiver/method separators so local-variable receiver-type
  1542. // inference (#1108) applies to them too — extraction already emits the ref in
  1543. // this shape, but the resolver otherwise only understood `.` and `::`.
  1544. const luaColonMatch = (ref.language === 'lua' || ref.language === 'luau')
  1545. ? ref.referenceName.match(/^([\w.]+):(\w+)$/)
  1546. : null;
  1547. const rDollarMatch = ref.language === 'r'
  1548. ? ref.referenceName.match(/^([\w.]+)\$(\w+)$/)
  1549. : null;
  1550. // PHP property receiver: `$this->prop->method()` reaches the resolver as
  1551. // `this->prop.method` (the extractor records the receiver's raw text with the
  1552. // leading `$` stripped). Resolve it EXCLUSIVELY through declared-type
  1553. // inference + resolveMethodOnType validation — the name-similarity strategies
  1554. // below must never see this shape, so a property whose type can't be
  1555. // recovered stays unlinked rather than guessed (a wrong inference produces no
  1556. // edge rather than a wrong one). Deeper chains (`this->a->b.method`) don't
  1557. // match the single-property pattern and stay unlinked, same as before.
  1558. const phpThisPropMatch = ref.language === 'php'
  1559. ? ref.referenceName.match(/^(this->\w+)\.(\w+)$/)
  1560. : null;
  1561. if (phpThisPropMatch) {
  1562. const [, receiver, phpMethodName] = phpThisPropMatch;
  1563. const inferredType = inferLocalReceiverType(receiver!, ref, context);
  1564. if (!inferredType) return null;
  1565. return resolveMethodOnType(
  1566. inferredType,
  1567. phpMethodName!,
  1568. ref,
  1569. context,
  1570. 0.9,
  1571. 'instance-method',
  1572. importedFqnOf(inferredType, ref, context),
  1573. );
  1574. }
  1575. const match = dotMatch || colonMatch || luaColonMatch || rDollarMatch;
  1576. if (!match) {
  1577. return null;
  1578. }
  1579. const [, objectOrClass, methodName] = match;
  1580. // A simple `receiver.method` / `receiver:method` / `receiver$method` shape whose
  1581. // receiver type we can try to infer from its local declaration.
  1582. const inferableReceiver = dotMatch || luaColonMatch || rDollarMatch;
  1583. // Infer the receiver's type from its local declaration/initializer in the
  1584. // enclosing scope, then resolve the method on that type (#1108). C++ keeps its
  1585. // dedicated inferrer (header scan + `auto`); every other language uses the
  1586. // shared source-based inferrer. resolveMethodOnType validates the method
  1587. // exists on the inferred type, so a mis-inference produces no edge.
  1588. if (inferableReceiver) {
  1589. const inferredType = nmTimedT('mc-infer', ref, () =>
  1590. ref.language === 'cpp'
  1591. ? inferCppReceiverType(objectOrClass!, ref, context)
  1592. : inferLocalReceiverType(objectOrClass!, ref, context));
  1593. if (inferredType) {
  1594. // Java/Kotlin: when two classes share the simple name, the file's import
  1595. // pins WHICH one (#314). Other languages disambiguate by call-site file.
  1596. const importedFqn =
  1597. ref.language === 'java' || ref.language === 'kotlin'
  1598. ? context
  1599. .getImportMappings(ref.filePath, ref.language)
  1600. .find((i) => i.localName === inferredType)?.source
  1601. : undefined;
  1602. const typedMatch = nmTimedT('mc-rmot', ref, () => resolveMethodOnType(
  1603. inferredType,
  1604. methodName!,
  1605. ref,
  1606. context,
  1607. 0.9,
  1608. 'instance-method',
  1609. importedFqn,
  1610. ));
  1611. if (typedMatch) {
  1612. return typedMatch;
  1613. }
  1614. }
  1615. }
  1616. // Go 2-hop field chain `base.field.Method` (#1276): the base's type comes
  1617. // from the enclosing scope (typed parameter / method receiver / local var),
  1618. // the field's declared type from that struct's own declaration lines, and
  1619. // the method is VALIDATED on the field's type by resolveMethodOnType. This
  1620. // branch is EXCLUSIVE for chained Go receivers: when the hop can't be
  1621. // inferred or the field's type is external (`conn *sql.DB` — no project
  1622. // node), the ref stays unresolved rather than falling through to the
  1623. // bare-name strategies below, which is exactly how `target.conn.Exec(...)`
  1624. // fabricated a dependency on an unrelated local interface's same-named
  1625. // method. Chained Go receivers were never emitted before #1276, so there
  1626. // is no prior recall to preserve on the fallback path.
  1627. if (ref.language === 'go' && dotMatch && objectOrClass!.includes('.')) {
  1628. return matchGoFieldChainCall(objectOrClass!, methodName!, ref, context);
  1629. }
  1630. // Java/Kotlin: receiver may be a field whose name doesn't match the type by
  1631. // Java naming convention (`userbo` → class `UserBO`, abbreviated). Look up
  1632. // the field in the enclosing class to get its declared type, then resolve
  1633. // the method on that type. Covers Spring `@Resource`/`@Autowired` field
  1634. // injection where the field type is the concrete bean class.
  1635. if ((ref.language === 'java' || ref.language === 'kotlin') && dotMatch) {
  1636. const inferredType = inferJavaFieldReceiverType(objectOrClass!, ref, context);
  1637. if (inferredType) {
  1638. // When two classes share the same simple name, the caller file's
  1639. // import is the only signal that names WHICH one — pass the
  1640. // imported FQN so resolveMethodOnType can disambiguate (#314).
  1641. const imports = context.getImportMappings(ref.filePath, ref.language);
  1642. const importedFqn = imports.find((i) => i.localName === inferredType)?.source;
  1643. const typedMatch = nmTimedT('mc-rmot', ref, () => resolveMethodOnType(
  1644. inferredType,
  1645. methodName!,
  1646. ref,
  1647. context,
  1648. 0.9,
  1649. 'instance-method',
  1650. importedFqn,
  1651. ));
  1652. if (typedMatch) {
  1653. return typedMatch;
  1654. }
  1655. }
  1656. }
  1657. // Strategy 1: Direct class name match (existing logic). When the receiver
  1658. // names a class that exists in several files (`Logger.log()` / `Logger::log()`
  1659. // with a `Logger` in both `a/` and `b/`), try the class in the call site's
  1660. // own file first — otherwise the first-indexed class wins and a call in `b/`
  1661. // resolves to `a/`'s method (#1079).
  1662. const strat1 = nmTimedT('mc-class', ref, (): ResolvedRef | null => {
  1663. const classCandidates = preferCallSiteFile(
  1664. context.getNodesByName(objectOrClass!),
  1665. ref.filePath,
  1666. );
  1667. for (const classNode of classCandidates) {
  1668. if (classNode.kind === 'class' || classNode.kind === 'struct' || classNode.kind === 'union' || classNode.kind === 'interface') {
  1669. // Skip cross-language class matches
  1670. if (classNode.language !== ref.language) continue;
  1671. const nodesInFile = context.getNodesInFile(classNode.filePath);
  1672. const methodNode = nodesInFile.find(
  1673. (n) =>
  1674. n.kind === 'method' &&
  1675. n.name === methodName &&
  1676. n.qualifiedName.includes(classNode.name)
  1677. );
  1678. if (methodNode) {
  1679. return {
  1680. original: ref,
  1681. targetNodeId: methodNode.id,
  1682. confidence: 0.85,
  1683. resolvedBy: 'qualified-name',
  1684. };
  1685. }
  1686. }
  1687. }
  1688. return null;
  1689. });
  1690. if (strat1) return strat1;
  1691. // Strategy 2: Instance variable receiver - try capitalized form to find class
  1692. // e.g., "permissionEngine" → look for classes containing "PermissionEngine"
  1693. const capitalizedReceiver = objectOrClass!.charAt(0).toUpperCase() + objectOrClass!.slice(1);
  1694. if (capitalizedReceiver !== objectOrClass) {
  1695. const strat2 = nmTimedT('mc-capital', ref, (): ResolvedRef | null => {
  1696. const fuzzyClassCandidates = preferCallSiteFile(
  1697. context.getNodesByName(capitalizedReceiver),
  1698. ref.filePath,
  1699. );
  1700. for (const classNode of fuzzyClassCandidates) {
  1701. if (classNode.kind === 'class' || classNode.kind === 'struct' || classNode.kind === 'union' || classNode.kind === 'interface') {
  1702. // Skip cross-language class matches
  1703. if (classNode.language !== ref.language) continue;
  1704. const nodesInFile = context.getNodesInFile(classNode.filePath);
  1705. const methodNode = nodesInFile.find(
  1706. (n) =>
  1707. n.kind === 'method' &&
  1708. n.name === methodName &&
  1709. n.qualifiedName.includes(classNode.name)
  1710. );
  1711. if (methodNode) {
  1712. return {
  1713. original: ref,
  1714. targetNodeId: methodNode.id,
  1715. confidence: 0.8,
  1716. resolvedBy: 'instance-method',
  1717. };
  1718. }
  1719. }
  1720. }
  1721. return null;
  1722. });
  1723. if (strat2) return strat2;
  1724. }
  1725. // Strategy 3: Find methods by name across the codebase, match by receiver
  1726. // name similarity with the containing class. Handles abbreviated variable
  1727. // names like permissionEngine → PermissionRuleEngine.
  1728. if (methodName) {
  1729. const strat3 = nmTimedT('mc-byname', ref, (): ResolvedRef | null => {
  1730. const methodCandidates = context.getNodesByName(methodName!);
  1731. // Ubiquitous-method ceiling (#999): a method name re-declared across a
  1732. // vendored theme/SDK (Metronic's `init`/`update`/… on every widget) yields
  1733. // K candidates that receiver-word overlap can't reliably disambiguate —
  1734. // and filtering + scoring all K per call is the O(K²) cost that wedged
  1735. // "Resolving refs" for 15-28 min. Bail before the O(K) work; Strategy 1/2
  1736. // (class-name match) already had their precise shot above.
  1737. if (methodCandidates.length > AMBIGUOUS_NAME_CEILING) {
  1738. return null;
  1739. }
  1740. const methods = methodCandidates.filter(
  1741. (n) => n.kind === 'method' && n.name === methodName
  1742. );
  1743. // Filter to same-language candidates first
  1744. const sameLanguageMethods = methods.filter(m => m.language === ref.language);
  1745. const targetMethods = sameLanguageMethods.length > 0 ? sameLanguageMethods : methods;
  1746. // If only one same-language method with this name exists, use it
  1747. if (targetMethods.length === 1 && targetMethods[0]!.language === ref.language) {
  1748. return {
  1749. original: ref,
  1750. targetNodeId: targetMethods[0]!.id,
  1751. confidence: 0.7,
  1752. resolvedBy: 'instance-method',
  1753. };
  1754. }
  1755. // Multiple methods: score by receiver name word overlap with class name
  1756. if (targetMethods.length > 1) {
  1757. const receiverWords = splitCamelCase(objectOrClass!);
  1758. let bestMatch: typeof targetMethods[0] | undefined;
  1759. let bestScore = 0;
  1760. // Same-file candidates first, so a score tie (`score > bestScore` keeps
  1761. // the first seen) resolves to the call site's own file rather than the
  1762. // first-indexed duplicate (#1079).
  1763. for (const method of preferCallSiteFile(targetMethods, ref.filePath)) {
  1764. const classWords = splitCamelCase(method.qualifiedName);
  1765. let score = receiverWords.filter(w =>
  1766. classWords.some(cw => cw.toLowerCase() === w.toLowerCase())
  1767. ).length;
  1768. // Bonus for same language
  1769. if (method.language === ref.language) score += 1;
  1770. if (score > bestScore) {
  1771. bestScore = score;
  1772. bestMatch = method;
  1773. }
  1774. }
  1775. if (bestMatch && bestScore >= 2) {
  1776. return {
  1777. original: ref,
  1778. targetNodeId: bestMatch.id,
  1779. confidence: 0.65,
  1780. resolvedBy: 'instance-method',
  1781. };
  1782. }
  1783. }
  1784. return null;
  1785. });
  1786. if (strat3) return strat3;
  1787. }
  1788. return null;
  1789. }
  1790. /** Go builtin/primitive field types that can never carry a project method. */
  1791. const GO_BUILTIN_FIELD_TYPES = new Set([
  1792. 'string', 'bool', 'byte', 'rune', 'error', 'any',
  1793. 'int', 'int8', 'int16', 'int32', 'int64',
  1794. 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'uintptr',
  1795. 'float32', 'float64', 'complex64', 'complex128',
  1796. 'chan', 'map', 'func', 'struct', 'interface',
  1797. ]);
  1798. /**
  1799. * Resolve a Go 2-hop field-chain call `base.field.Method(...)` (#1276):
  1800. * `target.conn.Exec("insert")` where `func (target *Target) Write()` and
  1801. * `type Target struct { conn *sql.DB }`. Two inference hops, both read from
  1802. * source the same way #1108 does:
  1803. * 1. `base`'s type from the enclosing scope (method receiver, typed
  1804. * parameter, or local declaration) via inferLocalReceiverType;
  1805. * 2. `field`'s declared type from the struct's own declaration lines.
  1806. * The method is then resolved AND VALIDATED on the field's type. A field
  1807. * whose type has no project node (`sql.DB`, any external dependency) yields
  1808. * null — the caller treats this branch as exclusive for chained Go
  1809. * receivers, so the ref stays unresolved instead of name-guessing.
  1810. */
  1811. function matchGoFieldChainCall(
  1812. receiverChain: string,
  1813. methodName: string,
  1814. ref: UnresolvedRef,
  1815. context: ResolutionContext
  1816. ): ResolvedRef | null {
  1817. const segs = receiverChain.split('.');
  1818. if (segs.length !== 2 || !segs[0] || !segs[1]) return null;
  1819. const [base, field] = segs;
  1820. const baseType = inferLocalReceiverType(base!, ref, context);
  1821. if (!baseType) return null;
  1822. const fieldEsc = field!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1823. const fieldTypeRe = new RegExp(`\\b${fieldEsc}\\s+\\*?\\[?\\]?([A-Za-z_][\\w.]*)`);
  1824. const structs = preferCallSiteFile(context.getNodesByName(baseType), ref.filePath).filter(
  1825. (n) => (n.kind === 'struct' || n.kind === 'class') && n.language === 'go'
  1826. );
  1827. for (const s of structs) {
  1828. const source = context.readFile(s.filePath);
  1829. if (!source) continue;
  1830. // Only the struct's own declaration lines — a same-named identifier
  1831. // elsewhere in the file can't donate a type. Matched LINE BY LINE with
  1832. // comments stripped: chi's `Mux` has a doc comment reading "the tree
  1833. // router" right above `tree *node`, and a whole-block match captured
  1834. // `router` from the prose instead of `node` from the field.
  1835. const declLines = source.split('\n').slice(Math.max(0, s.startLine - 1), s.endLine);
  1836. for (const rawLine of declLines) {
  1837. const line = rawLine.replace(/\/\/.*$/, '').replace(/\/\*.*?\*\//g, '');
  1838. const m = line.match(fieldTypeRe);
  1839. if (!m || !m[1]) continue;
  1840. const rawType = m[1];
  1841. // A package-qualified field type (`http.Handler`, `sql.DB`) is only
  1842. // followed when the package is IN-MODULE: stripping the qualifier and
  1843. // matching the bare name would conflate a stdlib/third-party type with
  1844. // any same-named project type — on chi, `handler http.Handler` bound
  1845. // to an example app's unrelated local `Handler`. That is the exact
  1846. // fabrication this matcher exists to prevent (#1276).
  1847. if (rawType.includes('.')) {
  1848. const pkg = rawType.split('.')[0]!;
  1849. const mod = context.getGoModule?.();
  1850. const imp = context
  1851. .getImportMappings(s.filePath, 'go')
  1852. .find((i) => i.localName === pkg);
  1853. const inModule =
  1854. !!mod &&
  1855. !!imp &&
  1856. (imp.source === mod.modulePath || imp.source.startsWith(mod.modulePath + '/'));
  1857. if (!inModule) continue;
  1858. }
  1859. // Unexported (lowercase) types are idiomatic Go and stay eligible —
  1860. // chi's `mx.tree.FindRoute()` chains through `tree *node`. A
  1861. // mis-capture is harmless: resolveMethodOnType only returns a
  1862. // validated `<type>::<method>` match.
  1863. const fieldType = rawType.split('.').pop();
  1864. if (!fieldType || !/^[A-Za-z_]/.test(fieldType) || GO_BUILTIN_FIELD_TYPES.has(fieldType)) continue;
  1865. const resolved = resolveMethodOnType(fieldType, methodName, ref, context, 0.85, 'instance-method');
  1866. if (resolved) return resolved;
  1867. }
  1868. }
  1869. return null;
  1870. }
  1871. /**
  1872. * Split a camelCase or PascalCase string into words.
  1873. */
  1874. function splitCamelCase(str: string): string[] {
  1875. return str.replace(/([a-z])([A-Z])/g, '$1 $2')
  1876. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
  1877. .split(/[\s._:\/\\]+/)
  1878. .filter(w => w.length > 1);
  1879. }
  1880. /**
  1881. * Compute directory proximity from a pre-split list of directory segments
  1882. * (`filePath1` minus its filename) and a second file path.
  1883. * Returns a score based on the number of shared leading directory segments.
  1884. * Higher score = closer in directory tree.
  1885. *
  1886. * Split into a pre-split variant because findBestMatch scores every candidate
  1887. * against the SAME `ref.filePath`; re-splitting it per candidate was a hot spot
  1888. * on large repos (#915), so the caller splits it once and passes the segments.
  1889. */
  1890. function pathProximityFromDirs(dir1: string[], filePath2: string): number {
  1891. const dir2 = filePath2.split('/');
  1892. dir2.pop(); // drop filename — matches the original slice(0, -1) on both paths
  1893. let shared = 0;
  1894. const limit = Math.min(dir1.length, dir2.length);
  1895. for (let i = 0; i < limit; i++) {
  1896. if (dir1[i] === dir2[i]) {
  1897. shared++;
  1898. } else {
  1899. break;
  1900. }
  1901. }
  1902. // Each shared directory segment contributes 15 points, capped at 80
  1903. return Math.min(shared * 15, 80);
  1904. }
  1905. /**
  1906. * Compute directory proximity between two file paths.
  1907. * Returns a score based on the number of shared directory segments.
  1908. */
  1909. function computePathProximity(filePath1: string, filePath2: string): number {
  1910. const dir1 = filePath1.split('/');
  1911. dir1.pop();
  1912. return pathProximityFromDirs(dir1, filePath2);
  1913. }
  1914. /**
  1915. * Find the best matching node when there are multiple candidates
  1916. */
  1917. function findBestMatch(
  1918. ref: UnresolvedRef,
  1919. candidates: Node[],
  1920. _context: ResolutionContext
  1921. ): Node | null {
  1922. // Prioritization rules:
  1923. // 1. Same file > different file
  1924. // 2. Directory proximity (same module/package > different module)
  1925. // 3. Same language > different language
  1926. // 4. Functions/methods > classes/types (for call references)
  1927. // 5. Exported > non-exported
  1928. let bestScore = -1;
  1929. let bestNode: Node | null = null;
  1930. // Split the ref's path once (it's the same across every candidate) instead of
  1931. // re-splitting it inside computePathProximity per candidate (#915 hot spot).
  1932. const refDirs = ref.filePath.split('/');
  1933. refDirs.pop();
  1934. // A same-language candidate ALWAYS outscores a cross-language one: same-language
  1935. // scores at least +50 (language bonus), while a cross-language candidate maxes
  1936. // out at +35 (−80 language, +80 proximity, +25 kind, +10 exported; it can never
  1937. // be in the same file). So when any same-language candidate exists, skip the
  1938. // cross-language ones — provably the same winner, without paying the per-candidate
  1939. // scoring. Cuts the candidate set to same-language size on mixed front-end +
  1940. // back-end repos (#915). When ALL candidates are cross-language (a legitimate
  1941. // cross-language `calls` bridge), none are skipped and behavior is unchanged.
  1942. const hasSameLanguage = candidates.some((c) => c.language === ref.language);
  1943. for (const candidate of candidates) {
  1944. if (hasSameLanguage && candidate.language !== ref.language) continue;
  1945. let score = 0;
  1946. // Same file bonus
  1947. if (candidate.filePath === ref.filePath) {
  1948. score += 100;
  1949. }
  1950. // Directory proximity bonus — strongly prefer same module/package
  1951. score += pathProximityFromDirs(refDirs, candidate.filePath);
  1952. // Language matching: strongly prefer same language, penalize cross-language
  1953. if (candidate.language === ref.language) {
  1954. score += 50;
  1955. } else {
  1956. score -= 80;
  1957. }
  1958. // For call references, prefer functions/methods
  1959. if (ref.referenceKind === 'calls') {
  1960. if (candidate.kind === 'function' || candidate.kind === 'method') {
  1961. score += 25;
  1962. }
  1963. }
  1964. // For instantiation references (`new Foo()`), prefer class-like
  1965. // targets — without this, a function named `Foo` in another module
  1966. // could outscore the actual class.
  1967. if (ref.referenceKind === 'instantiates') {
  1968. if (
  1969. candidate.kind === 'class' ||
  1970. candidate.kind === 'struct' ||
  1971. candidate.kind === 'union' ||
  1972. candidate.kind === 'interface'
  1973. ) {
  1974. score += 25;
  1975. }
  1976. }
  1977. // For decorator references (`@Foo`), prefer functions. Class
  1978. // decorators (Python `@SomeClass`, Java annotation interfaces)
  1979. // also resolve here, hence the smaller class bonus.
  1980. if (ref.referenceKind === 'decorates') {
  1981. if (candidate.kind === 'function' || candidate.kind === 'method') {
  1982. score += 25;
  1983. } else if (candidate.kind === 'class' || candidate.kind === 'interface') {
  1984. score += 15;
  1985. }
  1986. }
  1987. // Exported bonus
  1988. if (candidate.isExported) {
  1989. score += 10;
  1990. }
  1991. // Closer line number (within same file)
  1992. if (candidate.filePath === ref.filePath && candidate.startLine) {
  1993. const distance = Math.abs(candidate.startLine - ref.line);
  1994. score += Math.max(0, 20 - distance / 10);
  1995. }
  1996. if (score > bestScore) {
  1997. bestScore = score;
  1998. bestNode = candidate;
  1999. }
  2000. }
  2001. return bestNode;
  2002. }
  2003. /**
  2004. * Fuzzy match - last resort with lower confidence
  2005. */
  2006. export function matchFuzzy(
  2007. ref: UnresolvedRef,
  2008. context: ResolutionContext
  2009. ): ResolvedRef | null {
  2010. const lowerName = ref.referenceName.toLowerCase();
  2011. // Use pre-built lowercase index for O(1) lookup instead of scanning all nodes
  2012. const candidates = context.getNodesByLowerName(lowerName);
  2013. // Filter to callable kinds only (function, method, class)
  2014. const callableKinds = new Set(['function', 'method', 'class']);
  2015. const callableCandidates = applyLanguageGate(candidates.filter((n) => callableKinds.has(n.kind)), ref);
  2016. // Prefer same-language matches
  2017. const sameLanguageCandidates = callableCandidates.filter(n => n.language === ref.language);
  2018. const finalCandidates = sameLanguageCandidates.length > 0 ? sameLanguageCandidates : callableCandidates;
  2019. if (finalCandidates.length === 1) {
  2020. const isCrossLanguage = finalCandidates[0]!.language !== ref.language;
  2021. return {
  2022. original: ref,
  2023. targetNodeId: finalCandidates[0]!.id,
  2024. confidence: isCrossLanguage ? 0.3 : 0.5,
  2025. resolvedBy: 'fuzzy',
  2026. };
  2027. }
  2028. return null;
  2029. }
  2030. /**
  2031. * Match all strategies in order of confidence
  2032. */
  2033. /** ArkUI attribute-helper decorators a `.attr(...)` chain may resolve to. */
  2034. const ARKUI_ATTRIBUTE_DECORATORS = new Set(['Extend', 'Styles', 'AnimatableExtend', 'Builder']);
  2035. /**
  2036. * CODEGRAPH_RESOLVE_PROFILE=2 sub-stage attribution for matchReference's
  2037. * strategy pipeline (`nm:<stage>|<refKind>|hit/miss`). Module-global because
  2038. * the matcher is a free function; each thread (main + every pool worker) has
  2039. * its own module instance, and dumpNameMatcherProfile is invoked from
  2040. * ReferenceResolver.dumpResolveProfile so worker tables surface too.
  2041. */
  2042. const NM_PROFILE: Map<string, { n: number; ns: bigint }> | null =
  2043. process.env.CODEGRAPH_RESOLVE_PROFILE === '2' ? new Map() : null;
  2044. function nmTimedT<T>(stage: string, ref: UnresolvedRef, fn: () => T): T {
  2045. if (!NM_PROFILE) return fn();
  2046. const t0 = process.hrtime.bigint();
  2047. const r = fn();
  2048. const dt = process.hrtime.bigint() - t0;
  2049. const key = `nm:${stage}|${ref.referenceKind}|${r ? 'hit' : 'miss'}`;
  2050. const slot = NM_PROFILE.get(key);
  2051. if (slot) {
  2052. slot.n++;
  2053. slot.ns += dt;
  2054. } else {
  2055. NM_PROFILE.set(key, { n: 1, ns: dt });
  2056. }
  2057. return r;
  2058. }
  2059. function nmTimed(stage: string, ref: UnresolvedRef, fn: () => ResolvedRef | null): ResolvedRef | null {
  2060. return nmTimedT(stage, ref, fn);
  2061. }
  2062. /** Dump this thread's matchReference sub-stage table to stderr (no-op unless =2). */
  2063. export function dumpNameMatcherProfile(label: string): void {
  2064. if (!NM_PROFILE || NM_PROFILE.size === 0) return;
  2065. const rows = [...NM_PROFILE.entries()]
  2066. .map(([k, v]) => ({ k, n: v.n, ms: Number(v.ns / 1_000_000n) }))
  2067. .sort((a, b) => b.ms - a.ms);
  2068. for (const r of rows) {
  2069. console.error(
  2070. `[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`
  2071. );
  2072. }
  2073. }
  2074. export function matchReference(
  2075. ref: UnresolvedRef,
  2076. context: ResolutionContext
  2077. ): ResolvedRef | null {
  2078. // Function-as-value refs (#756) resolve ONLY through the dedicated matcher —
  2079. // never the fuzzy/qualified fallthrough below (a wrong callback edge is
  2080. // worse than none).
  2081. if (ref.referenceKind === 'function_ref') {
  2082. return matchFunctionRef(ref, context);
  2083. }
  2084. // ArkTS chained UI attributes — emitted with a leading dot (`.titleStyle`,
  2085. // `.width`) by the extractor — resolve ONLY to decorator-marked attribute
  2086. // helpers: `@Extend`/`@Styles`/`@AnimatableExtend` functions (and global
  2087. // `@Builder`s used attribute-position). Framework attributes (`.width`,
  2088. // `.fontSize` — on nearly every UI line) match no such helper and stay
  2089. // unresolved, NEVER falling through to bare-name matching: on a samples
  2090. // monorepo that fallthrough manufactured 36k wrong edges, giving single
  2091. // same-named properties thousands of false callers. Ambiguity rule matches
  2092. // the rest of the file: several same-named helpers → prefer the call-site
  2093. // file, still ambiguous → drop the ref rather than guess.
  2094. if (ref.language === 'arkts' && ref.referenceName.startsWith('.')) {
  2095. const base = ref.referenceName.slice(1);
  2096. const candidates = context
  2097. .getNodesByName(base)
  2098. .filter(
  2099. (n) =>
  2100. n.language === 'arkts' &&
  2101. n.kind === 'function' &&
  2102. (n.decorators ?? []).some((d) => ARKUI_ATTRIBUTE_DECORATORS.has(d))
  2103. );
  2104. const chosen =
  2105. candidates.length > 1 ? preferCallSiteFile(candidates, ref.filePath) : candidates;
  2106. if (chosen.length !== 1) return null;
  2107. return {
  2108. original: ref,
  2109. targetNodeId: chosen[0]!.id,
  2110. confidence: 0.85,
  2111. resolvedBy: 'exact-match',
  2112. };
  2113. }
  2114. // Erlang `-behaviour(m)` refs target a MODULE. Letting them fall through to
  2115. // bare-name matching grabs any same-named symbol — on emqx,
  2116. // `-behaviour(supervisor)` resolved to a `-define(supervisor, …)` macro
  2117. // constant in an unrelated app. Resolve only to the behaviour module's
  2118. // namespace; an out-of-repo behaviour (OTP's gen_server/supervisor) stays
  2119. // unresolved rather than guessed. The same module-only rule applies to every
  2120. // ref an `.app`/`.app.src` resource file emits — its `{mod, …}` callback and
  2121. // `{applications, …}` dependency names can only mean modules, and on emqx
  2122. // the `ssl` OTP app otherwise resolved to a test helper FUNCTION named ssl.
  2123. if (
  2124. ref.language === 'erlang' &&
  2125. (ref.referenceKind === 'implements' || /\.app(?:\.src)?$/i.test(ref.filePath))
  2126. ) {
  2127. const modules = context
  2128. .getNodesByName(ref.referenceName)
  2129. .filter((n) => n.language === 'erlang' && n.kind === 'namespace');
  2130. const chosen = preferCallSiteFile(modules, ref.filePath)[0];
  2131. if (!chosen) return null;
  2132. return {
  2133. original: ref,
  2134. targetNodeId: chosen.id,
  2135. confidence: 0.9,
  2136. resolvedBy: 'exact-match',
  2137. };
  2138. }
  2139. // Try strategies in order of confidence
  2140. let result: ResolvedRef | null;
  2141. // 0. File path match (e.g., "snippets/drawer-menu.liquid" → file node)
  2142. result = nmTimed('filePath', ref, () => matchByFilePath(ref, context));
  2143. if (result) return result;
  2144. // 1. Qualified name match (highest confidence)
  2145. result = nmTimed('qualifiedName', ref, () => matchByQualifiedName(ref, context));
  2146. if (result) return result;
  2147. // 1b. C++ chained call whose receiver is another call — `Foo::instance().bar()`
  2148. // encoded as `Foo::instance().bar` by the extractor (#645). Resolve the
  2149. // receiver's type from what the inner call returns, then the method on it.
  2150. if (ref.language === 'cpp' || ref.language === 'c') {
  2151. result = nmTimed('cppChain', ref, () => matchCppCallChain(ref, context));
  2152. if (result) return result;
  2153. }
  2154. // 1c. `::`-scoped factory chain — PHP `Cls::for($x)->method()` (#608) or Rust
  2155. // `Foo::new().bar()`, both encoded as `Cls::factory().method`. The receiver's
  2156. // type is the factory's `self` (PHP `: self`/`: static`, Rust `-> Self`) or
  2157. // concrete return type.
  2158. if (ref.language === 'php' || ref.language === 'rust') {
  2159. result = nmTimed('scopedChain', ref, () => matchScopedCallChain(ref, context));
  2160. if (result) return result;
  2161. }
  2162. // 1d. Dotted chained static-factory / fluent call (Java / Kotlin / C# / Swift /
  2163. // Go / Scala / Dart / Objective-C) — `Foo.getInstance().bar()` encoded as
  2164. // `Foo.getInstance().bar`, Go's bare-factory `New().Method()` as `New().Method`,
  2165. // Scala's companion factory, Dart's static factory / factory-constructor, or
  2166. // ObjC's chained message send `[[Foo create] doIt]` encoded as `Foo.create().doIt`
  2167. // (#645/#608 mechanism). Resolve the method's class from the inner call's
  2168. // declared return type, then validate it.
  2169. if (
  2170. ref.language === 'java' ||
  2171. ref.language === 'kotlin' ||
  2172. ref.language === 'csharp' ||
  2173. ref.language === 'swift' ||
  2174. ref.language === 'go' ||
  2175. ref.language === 'scala' ||
  2176. ref.language === 'dart' ||
  2177. ref.language === 'objc' ||
  2178. ref.language === 'pascal'
  2179. ) {
  2180. result = nmTimed('dottedChain', ref, () => matchDottedCallChain(ref, context));
  2181. if (result) return result;
  2182. }
  2183. // 2. Method call pattern
  2184. result = nmTimed('methodCall', ref, () => matchMethodCall(ref, context));
  2185. if (result) return result;
  2186. // 3. Exact name match
  2187. result = nmTimed('exactName', ref, () => matchByExactName(ref, context));
  2188. if (result) return result;
  2189. // 4. Fuzzy match (lowest confidence)
  2190. result = nmTimed('fuzzy', ref, () => matchFuzzy(ref, context));
  2191. if (result) return result;
  2192. return null;
  2193. }