resolution.test.ts 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373
  1. /**
  2. * Resolution Module Tests
  3. *
  4. * Tests for Phase 3: Reference Resolution
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, UnresolvedReference } from '../src/types';
  12. import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
  13. import { matchReference, resolveMethodOnType, matchByQualifiedName, preferCallSiteFile, matchMethodCall } from '../src/resolution/name-matcher';
  14. import { resolveImportPath, extractImportMappings, resolveJvmImport, loadCppIncludeDirs, clearCppIncludeDirCache, isPhpIncludePathRef } from '../src/resolution/import-resolver';
  15. import type { UnresolvedRef } from '../src/resolution/types';
  16. import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
  17. import { QueryBuilder } from '../src/db/queries';
  18. import { DatabaseConnection } from '../src/db';
  19. describe('Resolution Module', () => {
  20. let tempDir: string;
  21. let cg: CodeGraph;
  22. beforeEach(() => {
  23. // Create temp directory
  24. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
  25. });
  26. afterEach(() => {
  27. // Clean up
  28. if (cg) {
  29. cg.destroy();
  30. } else if (fs.existsSync(tempDir)) {
  31. fs.rmSync(tempDir, { recursive: true });
  32. }
  33. });
  34. describe('Name Matcher', () => {
  35. it('should match exact name references', () => {
  36. // Create a mock context
  37. const mockNodes: Node[] = [
  38. {
  39. id: 'func:test.ts:myFunction:10',
  40. kind: 'function',
  41. name: 'myFunction',
  42. qualifiedName: 'test.ts::myFunction',
  43. filePath: 'test.ts',
  44. language: 'typescript',
  45. startLine: 10,
  46. endLine: 20,
  47. startColumn: 0,
  48. endColumn: 0,
  49. updatedAt: Date.now(),
  50. },
  51. ];
  52. const context: ResolutionContext = {
  53. getNodesInFile: () => mockNodes,
  54. getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
  55. getNodesByQualifiedName: () => [],
  56. getNodesByKind: () => [],
  57. fileExists: () => true,
  58. readFile: () => null,
  59. getProjectRoot: () => '/test',
  60. getAllFiles: () => ['test.ts'],
  61. };
  62. const ref = {
  63. fromNodeId: 'caller:main.ts:caller:5',
  64. referenceName: 'myFunction',
  65. referenceKind: 'calls' as const,
  66. line: 5,
  67. column: 10,
  68. filePath: 'main.ts',
  69. language: 'typescript' as const,
  70. };
  71. const result = matchReference(ref, context);
  72. expect(result).not.toBeNull();
  73. expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
  74. expect(result?.resolvedBy).toBe('exact-match');
  75. });
  76. it('should resolve Erlang -behaviour refs only to module namespaces', () => {
  77. // On emqx, `-behaviour(supervisor)` (OTP behaviour, not in the repo)
  78. // fell through to bare-name matching and resolved to a
  79. // `-define(supervisor, ...)` macro constant in an unrelated app.
  80. const macroConstant: Node = {
  81. id: 'constant:apps/bridge/src/impl.erl:supervisor:61',
  82. kind: 'constant',
  83. name: 'supervisor',
  84. qualifiedName: 'impl::supervisor',
  85. filePath: 'apps/bridge/src/impl.erl',
  86. language: 'erlang',
  87. startLine: 61,
  88. endLine: 61,
  89. startColumn: 0,
  90. endColumn: 0,
  91. updatedAt: Date.now(),
  92. };
  93. const behaviourModule: Node = {
  94. id: 'namespace:src/my_behaviour.erl:my_behaviour:1',
  95. kind: 'namespace',
  96. name: 'my_behaviour',
  97. qualifiedName: 'my_behaviour',
  98. filePath: 'src/my_behaviour.erl',
  99. language: 'erlang',
  100. startLine: 1,
  101. endLine: 1,
  102. startColumn: 0,
  103. endColumn: 0,
  104. updatedAt: Date.now(),
  105. };
  106. const nodes = [macroConstant, behaviourModule];
  107. const context: ResolutionContext = {
  108. getNodesInFile: () => [],
  109. getNodesByName: (name) => nodes.filter((n) => n.name === name),
  110. getNodesByQualifiedName: () => [],
  111. getNodesByKind: () => [],
  112. fileExists: () => false,
  113. readFile: () => null,
  114. getProjectRoot: () => '/test',
  115. getAllFiles: () => [],
  116. getNodesByLowerName: () => [],
  117. getImportMappings: () => [],
  118. };
  119. const mkRef = (name: string) => ({
  120. fromNodeId: 'namespace:src/worker.erl:worker:1',
  121. referenceName: name,
  122. referenceKind: 'implements' as const,
  123. line: 2,
  124. column: 0,
  125. filePath: 'src/worker.erl',
  126. language: 'erlang' as const,
  127. });
  128. // Out-of-repo behaviour whose name collides with a macro constant:
  129. // stays unresolved instead of linking the constant.
  130. expect(matchReference(mkRef('supervisor'), context)).toBeNull();
  131. // In-repo behaviour module resolves to its namespace.
  132. const resolved = matchReference(mkRef('my_behaviour'), context);
  133. expect(resolved?.targetNodeId).toBe(behaviourModule.id);
  134. });
  135. it('should prefer same-module candidates over cross-module matches', () => {
  136. // Simulates a Python monorepo where multiple apps define navigate()
  137. const candidateA: Node = {
  138. id: 'func:apps/app_a/src/server.py:navigate:10',
  139. kind: 'function',
  140. name: 'navigate',
  141. qualifiedName: 'apps/app_a/src/server.py::navigate',
  142. filePath: 'apps/app_a/src/server.py',
  143. language: 'python',
  144. startLine: 10,
  145. endLine: 20,
  146. startColumn: 0,
  147. endColumn: 0,
  148. updatedAt: Date.now(),
  149. };
  150. const candidateB: Node = {
  151. id: 'func:apps/app_b/src/server.py:navigate:15',
  152. kind: 'function',
  153. name: 'navigate',
  154. qualifiedName: 'apps/app_b/src/server.py::navigate',
  155. filePath: 'apps/app_b/src/server.py',
  156. language: 'python',
  157. startLine: 15,
  158. endLine: 25,
  159. startColumn: 0,
  160. endColumn: 0,
  161. updatedAt: Date.now(),
  162. };
  163. const context: ResolutionContext = {
  164. getNodesInFile: () => [],
  165. getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
  166. getNodesByQualifiedName: () => [],
  167. getNodesByKind: () => [],
  168. fileExists: () => true,
  169. readFile: () => null,
  170. getProjectRoot: () => '/test',
  171. getAllFiles: () => [],
  172. getNodesByLowerName: () => [],
  173. getImportMappings: () => [],
  174. };
  175. // Reference from app_a should resolve to app_a's navigate, not app_b's
  176. const ref = {
  177. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  178. referenceName: 'navigate',
  179. referenceKind: 'calls' as const,
  180. line: 5,
  181. column: 10,
  182. filePath: 'apps/app_a/src/handler.py',
  183. language: 'python' as const,
  184. };
  185. const result = matchReference(ref, context);
  186. expect(result).not.toBeNull();
  187. expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
  188. expect(result?.resolvedBy).toBe('exact-match');
  189. });
  190. it('should lower confidence for cross-module exact matches', () => {
  191. // Only one candidate but in a completely different module
  192. const candidates: Node[] = [
  193. {
  194. id: 'func:apps/app_b/src/server.py:navigate:10',
  195. kind: 'function',
  196. name: 'navigate',
  197. qualifiedName: 'apps/app_b/src/server.py::navigate',
  198. filePath: 'apps/app_b/src/server.py',
  199. language: 'python',
  200. startLine: 10,
  201. endLine: 20,
  202. startColumn: 0,
  203. endColumn: 0,
  204. updatedAt: Date.now(),
  205. },
  206. {
  207. id: 'func:apps/app_c/src/server.py:navigate:10',
  208. kind: 'function',
  209. name: 'navigate',
  210. qualifiedName: 'apps/app_c/src/server.py::navigate',
  211. filePath: 'apps/app_c/src/server.py',
  212. language: 'python',
  213. startLine: 10,
  214. endLine: 20,
  215. startColumn: 0,
  216. endColumn: 0,
  217. updatedAt: Date.now(),
  218. },
  219. ];
  220. const context: ResolutionContext = {
  221. getNodesInFile: () => [],
  222. getNodesByName: (name) => name === 'navigate' ? candidates : [],
  223. getNodesByQualifiedName: () => [],
  224. getNodesByKind: () => [],
  225. fileExists: () => true,
  226. readFile: () => null,
  227. getProjectRoot: () => '/test',
  228. getAllFiles: () => [],
  229. getNodesByLowerName: () => [],
  230. getImportMappings: () => [],
  231. };
  232. // Reference from app_a — neither candidate is in the same module
  233. const ref = {
  234. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  235. referenceName: 'navigate',
  236. referenceKind: 'calls' as const,
  237. line: 5,
  238. column: 10,
  239. filePath: 'apps/app_a/src/handler.py',
  240. language: 'python' as const,
  241. };
  242. const result = matchReference(ref, context);
  243. // Should still resolve but with low confidence
  244. expect(result).not.toBeNull();
  245. expect(result?.confidence).toBeLessThanOrEqual(0.4);
  246. });
  247. it('should match qualified name references', () => {
  248. const mockClassNode: Node = {
  249. id: 'class:user.ts:User:5',
  250. kind: 'class',
  251. name: 'User',
  252. qualifiedName: 'user.ts::User',
  253. filePath: 'user.ts',
  254. language: 'typescript',
  255. startLine: 5,
  256. endLine: 30,
  257. startColumn: 0,
  258. endColumn: 0,
  259. updatedAt: Date.now(),
  260. };
  261. const mockMethodNode: Node = {
  262. id: 'method:user.ts:User.save:15',
  263. kind: 'method',
  264. name: 'save',
  265. qualifiedName: 'user.ts::User::save',
  266. filePath: 'user.ts',
  267. language: 'typescript',
  268. startLine: 15,
  269. endLine: 25,
  270. startColumn: 0,
  271. endColumn: 0,
  272. updatedAt: Date.now(),
  273. };
  274. const context: ResolutionContext = {
  275. getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
  276. getNodesByName: (name) => {
  277. if (name === 'User') return [mockClassNode];
  278. if (name === 'save') return [mockMethodNode];
  279. return [];
  280. },
  281. getNodesByQualifiedName: (qn) => {
  282. if (qn === 'user.ts::User::save') return [mockMethodNode];
  283. return [];
  284. },
  285. getNodesByKind: () => [],
  286. fileExists: () => true,
  287. readFile: () => null,
  288. getProjectRoot: () => '/test',
  289. getAllFiles: () => ['user.ts'],
  290. };
  291. const ref = {
  292. fromNodeId: 'caller:main.ts:main:5',
  293. referenceName: 'User.save',
  294. referenceKind: 'calls' as const,
  295. line: 5,
  296. column: 10,
  297. filePath: 'main.ts',
  298. language: 'typescript' as const,
  299. };
  300. const result = matchReference(ref, context);
  301. expect(result).not.toBeNull();
  302. expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
  303. });
  304. });
  305. describe('Ubiquitous-name ceiling (#999)', () => {
  306. // A vendored theme/SDK re-declares the same method name across thousands of
  307. // files (Metronic's `init`/`update`/… on every widget). The fuzzy strategies
  308. // used to score every same-named candidate per ref — O(K) per ref, O(K²)
  309. // total — which pinned a core for 15-28 min at "Resolving refs … 94%". Above
  310. // the ceiling they must DECLINE instead, since no proximity/word-overlap
  311. // score can pick the one true target among thousands anyway.
  312. const CEILING = 500;
  313. // A spy context: counts how many nodes the strategy actually inspects, so we
  314. // can assert the cap short-circuits BEFORE the O(K) scoring (not just that it
  315. // returns null).
  316. const makeManyMethods = (n: number, name: string): Node[] =>
  317. Array.from({ length: n }, (_, i) => ({
  318. id: `method:widget${i}.js:Widget${i}.${name}:1`,
  319. kind: 'method' as const,
  320. name,
  321. qualifiedName: `widget${i}.js::Widget${i}::${name}`,
  322. filePath: `static/theme/widget${i}.js`,
  323. language: 'javascript' as const,
  324. startLine: 1,
  325. endLine: 5,
  326. startColumn: 0,
  327. endColumn: 0,
  328. updatedAt: Date.now(),
  329. }));
  330. const spyContext = (nodes: Node[]): { ctx: ResolutionContext; lookups: () => number } => {
  331. let scanned = 0;
  332. const ctx: ResolutionContext = {
  333. getNodesInFile: () => [],
  334. getNodesByName: (name) => {
  335. const hit = nodes.filter((n) => n.name === name);
  336. scanned += hit.length;
  337. return hit;
  338. },
  339. getNodesByQualifiedName: () => [],
  340. getNodesByKind: () => [],
  341. fileExists: () => true,
  342. readFile: () => null,
  343. getProjectRoot: () => '/test',
  344. getAllFiles: () => [],
  345. getNodesByLowerName: () => [],
  346. getImportMappings: () => [],
  347. };
  348. return { ctx, lookups: () => scanned };
  349. };
  350. it('declines a method call (`obj.init`) above the ceiling instead of scoring K candidates', () => {
  351. const { ctx } = spyContext(makeManyMethods(CEILING + 1, 'init'));
  352. const ref = {
  353. fromNodeId: 'method:caller.js:caller:1',
  354. referenceName: 'widget.init',
  355. referenceKind: 'calls' as const,
  356. line: 2,
  357. column: 4,
  358. filePath: 'static/theme/caller.js',
  359. language: 'javascript' as const,
  360. };
  361. expect(matchReference(ref, ctx)).toBeNull();
  362. });
  363. it('declines a bare exact-name ref above the ceiling', () => {
  364. const { ctx } = spyContext(makeManyMethods(CEILING + 1, 'render'));
  365. const ref = {
  366. fromNodeId: 'method:caller.js:caller:1',
  367. referenceName: 'render',
  368. referenceKind: 'calls' as const,
  369. line: 2,
  370. column: 4,
  371. filePath: 'static/theme/caller.js',
  372. language: 'javascript' as const,
  373. };
  374. expect(matchReference(ref, ctx)).toBeNull();
  375. });
  376. it('still resolves a SAME-FILE definition when one exists (precise path unaffected)', () => {
  377. // Strategy 1 (class-name) and same-file matching are precise — a ubiquitous
  378. // name with an unambiguous local target still resolves.
  379. const nodes = makeManyMethods(CEILING + 1, 'init');
  380. const local: Node = {
  381. id: 'class:static/theme/caller.js:Widgetly:1',
  382. kind: 'class',
  383. name: 'Widgetly',
  384. qualifiedName: 'static/theme/caller.js::Widgetly',
  385. filePath: 'static/theme/caller.js',
  386. language: 'javascript',
  387. startLine: 1, endLine: 9, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  388. };
  389. const localMethod: Node = {
  390. id: 'method:static/theme/caller.js:Widgetly.init:2',
  391. kind: 'method',
  392. name: 'init',
  393. qualifiedName: 'static/theme/caller.js::Widgetly::init',
  394. filePath: 'static/theme/caller.js',
  395. language: 'javascript',
  396. startLine: 2, endLine: 4, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  397. };
  398. const all = [...nodes, local, localMethod];
  399. const ctx: ResolutionContext = {
  400. getNodesInFile: (fp) => all.filter((n) => n.filePath === fp),
  401. getNodesByName: (name) => all.filter((n) => n.name === name),
  402. getNodesByQualifiedName: () => [],
  403. getNodesByKind: () => [],
  404. fileExists: () => true,
  405. readFile: () => null,
  406. getProjectRoot: () => '/test',
  407. getAllFiles: () => [],
  408. getNodesByLowerName: () => [],
  409. getImportMappings: () => [],
  410. };
  411. // `Widgetly.init` names the class explicitly → Strategy 1 resolves it.
  412. const ref = {
  413. fromNodeId: 'method:static/theme/caller.js:caller:6',
  414. referenceName: 'Widgetly.init',
  415. referenceKind: 'calls' as const,
  416. line: 6,
  417. column: 4,
  418. filePath: 'static/theme/caller.js',
  419. language: 'javascript' as const,
  420. };
  421. const result = matchReference(ref, ctx);
  422. expect(result?.targetNodeId).toBe('method:static/theme/caller.js:Widgetly.init:2');
  423. });
  424. it('still scores normally JUST below the ceiling (no behavior change for normal repos)', () => {
  425. // Real repos top out near ~40 same-named methods; this proves a sub-ceiling
  426. // collision still resolves via proximity, so the cap is invisible to them.
  427. const nodes = makeManyMethods(CEILING - 1, 'update');
  428. // Make ONE candidate share the caller's directory so proximity picks it.
  429. nodes[0] = {
  430. ...nodes[0]!,
  431. id: 'method:static/theme/app/Widget0.update:1',
  432. qualifiedName: 'static/theme/app/widget.js::Widget0::update',
  433. filePath: 'static/theme/app/widget.js',
  434. };
  435. const ctx: ResolutionContext = {
  436. getNodesInFile: () => [],
  437. getNodesByName: (name) => nodes.filter((n) => n.name === name),
  438. getNodesByQualifiedName: () => [],
  439. getNodesByKind: () => [],
  440. fileExists: () => true,
  441. readFile: () => null,
  442. getProjectRoot: () => '/test',
  443. getAllFiles: () => [],
  444. getNodesByLowerName: () => [],
  445. getImportMappings: () => [],
  446. };
  447. const ref = {
  448. fromNodeId: 'method:static/theme/app/caller.js:caller:1',
  449. referenceName: 'update',
  450. referenceKind: 'calls' as const,
  451. line: 2,
  452. column: 4,
  453. filePath: 'static/theme/app/caller.js',
  454. language: 'javascript' as const,
  455. };
  456. // Below the ceiling the fuzzy path runs and resolves SOMETHING (not capped).
  457. expect(matchReference(ref, ctx)).not.toBeNull();
  458. });
  459. });
  460. describe('Import Resolver', () => {
  461. it('should resolve relative import paths', () => {
  462. const context: ResolutionContext = {
  463. getNodesInFile: () => [],
  464. getNodesByName: () => [],
  465. getNodesByQualifiedName: () => [],
  466. getNodesByKind: () => [],
  467. fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
  468. readFile: () => null,
  469. getProjectRoot: () => '',
  470. getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
  471. };
  472. const result = resolveImportPath(
  473. './utils',
  474. 'src/components/Button.ts',
  475. 'typescript',
  476. context
  477. );
  478. expect(result).toBe('src/components/utils.ts');
  479. });
  480. it('should resolve parent directory imports', () => {
  481. const context: ResolutionContext = {
  482. getNodesInFile: () => [],
  483. getNodesByName: () => [],
  484. getNodesByQualifiedName: () => [],
  485. getNodesByKind: () => [],
  486. fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
  487. readFile: () => null,
  488. getProjectRoot: () => '',
  489. getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
  490. };
  491. const result = resolveImportPath(
  492. '../helpers',
  493. 'src/components/Button.ts',
  494. 'typescript',
  495. context
  496. );
  497. expect(result).toBe('src/helpers.ts');
  498. });
  499. it('should extract JS/TS import mappings', () => {
  500. const content = `
  501. import { foo } from './foo';
  502. import bar from '../bar';
  503. import * as utils from './utils';
  504. import { baz, qux } from './baz';
  505. `;
  506. const mappings = extractImportMappings(
  507. 'src/index.ts',
  508. content,
  509. 'typescript'
  510. );
  511. expect(mappings.length).toBeGreaterThan(0);
  512. expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
  513. expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
  514. });
  515. it('should extract Python import mappings', () => {
  516. const content = `
  517. from utils import helper
  518. from .models import User
  519. import os
  520. from ..services import auth_service
  521. `;
  522. const mappings = extractImportMappings(
  523. 'src/main.py',
  524. content,
  525. 'python'
  526. );
  527. expect(mappings.length).toBeGreaterThan(0);
  528. expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
  529. expect(mappings.some((m) => m.localName === 'User')).toBe(true);
  530. });
  531. });
  532. describe('JVM FQN Import Resolution', () => {
  533. // Build a ResolutionContext stub whose getNodesByQualifiedName answers
  534. // from a fixed table — the only context method resolveJvmImport touches.
  535. const makeContext = (byQName: Record<string, Node[]>): ResolutionContext => ({
  536. getNodesInFile: () => [],
  537. getNodesByName: () => [],
  538. getNodesByQualifiedName: (q) => byQName[q] ?? [],
  539. getNodesByKind: () => [],
  540. fileExists: () => false,
  541. readFile: () => null,
  542. getProjectRoot: () => '',
  543. getAllFiles: () => [],
  544. });
  545. const node = (id: string, name: string, qualifiedName: string, kind: Node['kind'] = 'class', language: Node['language'] = 'kotlin'): Node => ({
  546. id, kind, name, qualifiedName,
  547. filePath: 'Models.kt', language,
  548. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0,
  549. updatedAt: 0,
  550. });
  551. const importRef = (referenceName: string, language: Node['language'] = 'kotlin'): UnresolvedRef => ({
  552. fromNodeId: 'caller',
  553. referenceName,
  554. referenceKind: 'imports',
  555. line: 1, column: 0,
  556. filePath: 'Caller.kt',
  557. language,
  558. });
  559. it('resolves a Kotlin class import by FQN regardless of filename', () => {
  560. const target = node('n1', 'Bar', 'com.example.foo::Bar');
  561. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  562. const result = resolveJvmImport(importRef('com.example.foo.Bar'), ctx);
  563. expect(result?.targetNodeId).toBe('n1');
  564. expect(result?.resolvedBy).toBe('import');
  565. });
  566. it('resolves a Kotlin top-level function import by FQN', () => {
  567. const util = node('n2', 'util', 'com.example.foo::util', 'function');
  568. const ctx = makeContext({ 'com.example.foo::util': [util] });
  569. const result = resolveJvmImport(importRef('com.example.foo.util'), ctx);
  570. expect(result?.targetNodeId).toBe('n2');
  571. });
  572. it('resolves a Java import by FQN', () => {
  573. const target = node('n3', 'Bar', 'com.example.foo::Bar', 'class', 'java');
  574. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  575. const result = resolveJvmImport(importRef('com.example.foo.Bar', 'java'), ctx);
  576. expect(result?.targetNodeId).toBe('n3');
  577. });
  578. it('resolves cross-language: Kotlin importing a Java class', () => {
  579. // The Kotlin file declares `import com.example.JavaBar` — the target is
  580. // a Java class node. JVM interop means the resolver doesn't care about
  581. // the source language of the target, only that the FQN matches.
  582. const target = node('n4', 'JavaBar', 'com.example::JavaBar', 'class', 'java');
  583. const ctx = makeContext({ 'com.example::JavaBar': [target] });
  584. const result = resolveJvmImport(importRef('com.example.JavaBar'), ctx);
  585. expect(result?.targetNodeId).toBe('n4');
  586. });
  587. it('disambiguates a name collision across packages', () => {
  588. // Two classes named `Bar` in different packages. Each import resolves
  589. // to the one whose FQN matches — not to "whichever was found first".
  590. const barA = node('n5a', 'Bar', 'com.example.alpha::Bar');
  591. const barB = node('n5b', 'Bar', 'com.example.beta::Bar');
  592. const ctx = makeContext({
  593. 'com.example.alpha::Bar': [barA],
  594. 'com.example.beta::Bar': [barB],
  595. });
  596. expect(resolveJvmImport(importRef('com.example.alpha.Bar'), ctx)?.targetNodeId).toBe('n5a');
  597. expect(resolveJvmImport(importRef('com.example.beta.Bar'), ctx)?.targetNodeId).toBe('n5b');
  598. });
  599. it('returns null for wildcard imports', () => {
  600. const ctx = makeContext({});
  601. expect(resolveJvmImport(importRef('com.example.foo.*'), ctx)).toBeNull();
  602. });
  603. it('returns null for unqualified names', () => {
  604. // A single-segment name has no package; nothing to look up by FQN.
  605. const ctx = makeContext({ 'Bar': [node('n6', 'Bar', 'Bar')] });
  606. expect(resolveJvmImport(importRef('Bar'), ctx)).toBeNull();
  607. });
  608. it('returns null for non-JVM languages', () => {
  609. const target = node('n7', 'Bar', 'com.example::Bar');
  610. const ctx = makeContext({ 'com.example::Bar': [target] });
  611. expect(resolveJvmImport(importRef('com.example.Bar', 'typescript'), ctx)).toBeNull();
  612. });
  613. it('returns null for non-imports reference kinds', () => {
  614. // The resolver intentionally only acts on `imports` refs; ordinary
  615. // `calls`/`extends` refs fall through to the framework + name-matcher
  616. // strategies.
  617. const target = node('n8', 'Bar', 'com.example::Bar');
  618. const ctx = makeContext({ 'com.example::Bar': [target] });
  619. const ref: UnresolvedRef = {
  620. fromNodeId: 'caller', referenceName: 'com.example.Bar',
  621. referenceKind: 'calls', line: 1, column: 0,
  622. filePath: 'Caller.kt', language: 'kotlin',
  623. };
  624. expect(resolveJvmImport(ref, ctx)).toBeNull();
  625. });
  626. it('returns null when the FQN is not in the index', () => {
  627. const ctx = makeContext({});
  628. expect(resolveJvmImport(importRef('com.example.Unknown'), ctx)).toBeNull();
  629. });
  630. });
  631. describe('Framework Detection', () => {
  632. it('should detect React framework', () => {
  633. const context: ResolutionContext = {
  634. getNodesInFile: () => [],
  635. getNodesByName: () => [],
  636. getNodesByQualifiedName: () => [],
  637. getNodesByKind: () => [],
  638. fileExists: () => false,
  639. readFile: (p) => {
  640. if (p === 'package.json') {
  641. return JSON.stringify({
  642. dependencies: { react: '^18.0.0' },
  643. });
  644. }
  645. return null;
  646. },
  647. getProjectRoot: () => '/test',
  648. getAllFiles: () => ['package.json', 'src/App.tsx'],
  649. };
  650. const frameworks = detectFrameworks(context);
  651. expect(frameworks.some((f) => f.name === 'react')).toBe(true);
  652. });
  653. it('should detect Express framework', () => {
  654. const context: ResolutionContext = {
  655. getNodesInFile: () => [],
  656. getNodesByName: () => [],
  657. getNodesByQualifiedName: () => [],
  658. getNodesByKind: () => [],
  659. fileExists: () => false,
  660. readFile: (p) => {
  661. if (p === 'package.json') {
  662. return JSON.stringify({
  663. dependencies: { express: '^4.18.0' },
  664. });
  665. }
  666. return null;
  667. },
  668. getProjectRoot: () => '/test',
  669. getAllFiles: () => ['package.json', 'src/app.js'],
  670. };
  671. const frameworks = detectFrameworks(context);
  672. expect(frameworks.some((f) => f.name === 'express')).toBe(true);
  673. });
  674. it('should detect Laravel framework', () => {
  675. const context: ResolutionContext = {
  676. getNodesInFile: () => [],
  677. getNodesByName: () => [],
  678. getNodesByQualifiedName: () => [],
  679. getNodesByKind: () => [],
  680. fileExists: (p) => p === 'artisan',
  681. readFile: () => null,
  682. getProjectRoot: () => '/test',
  683. getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
  684. };
  685. const frameworks = detectFrameworks(context);
  686. expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
  687. });
  688. it('should return all framework resolvers', () => {
  689. const resolvers = getAllFrameworkResolvers();
  690. expect(resolvers.length).toBeGreaterThan(0);
  691. expect(resolvers.some((r) => r.name === 'react')).toBe(true);
  692. expect(resolvers.some((r) => r.name === 'express')).toBe(true);
  693. expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
  694. });
  695. });
  696. describe('React Framework Resolver', () => {
  697. it('should resolve React component references', () => {
  698. const mockNodes: Node[] = [
  699. {
  700. id: 'component:src/Button.tsx:Button:5',
  701. kind: 'component',
  702. name: 'Button',
  703. qualifiedName: 'src/Button.tsx::Button',
  704. filePath: 'src/Button.tsx',
  705. language: 'tsx',
  706. startLine: 5,
  707. endLine: 20,
  708. startColumn: 0,
  709. endColumn: 0,
  710. updatedAt: Date.now(),
  711. },
  712. ];
  713. const context: ResolutionContext = {
  714. getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
  715. getNodesByName: () => mockNodes,
  716. getNodesByQualifiedName: () => [],
  717. getNodesByKind: () => [],
  718. fileExists: () => false,
  719. readFile: (p) => {
  720. if (p === 'package.json') {
  721. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  722. }
  723. return null;
  724. },
  725. getProjectRoot: () => '/test',
  726. getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
  727. };
  728. const frameworks = detectFrameworks(context);
  729. const reactResolver = frameworks.find((f) => f.name === 'react');
  730. expect(reactResolver).toBeDefined();
  731. const ref = {
  732. fromNodeId: 'component:src/App.tsx:App:1',
  733. referenceName: 'Button',
  734. referenceKind: 'renders' as const,
  735. line: 10,
  736. column: 5,
  737. filePath: 'src/App.tsx',
  738. // Refs extracted from .tsx files carry language 'tsx' — component
  739. // resolution is gated to JSX-capable refs (#764: PascalCase TYPE refs
  740. // from plain .ts files were resolving to arbitrary same-named classes).
  741. language: 'tsx' as const,
  742. };
  743. const result = reactResolver!.resolve(ref, context);
  744. expect(result).not.toBeNull();
  745. expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
  746. // The same PascalCase name referenced from a plain .ts file is a TYPE
  747. // reference, not a component usage — component resolution must decline
  748. // and leave it to proximity-aware name matching (#764: a .ts GraphQL
  749. // types file's own `Account` alias was losing to an arbitrary same-named
  750. // class in another monorepo package).
  751. const tsRef = { ...ref, filePath: 'src/models.ts', language: 'typescript' as const };
  752. expect(reactResolver!.resolve(tsRef, context)).toBeNull();
  753. });
  754. it('should resolve custom hook references', () => {
  755. const mockNodes: Node[] = [
  756. {
  757. id: 'hook:src/hooks/useAuth.ts:useAuth:1',
  758. kind: 'function',
  759. name: 'useAuth',
  760. qualifiedName: 'src/hooks/useAuth.ts::useAuth',
  761. filePath: 'src/hooks/useAuth.ts',
  762. language: 'typescript',
  763. startLine: 1,
  764. endLine: 20,
  765. startColumn: 0,
  766. endColumn: 0,
  767. updatedAt: Date.now(),
  768. },
  769. ];
  770. const context: ResolutionContext = {
  771. getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
  772. getNodesByName: () => mockNodes,
  773. getNodesByQualifiedName: () => [],
  774. getNodesByKind: () => [],
  775. fileExists: () => false,
  776. readFile: (p) => {
  777. if (p === 'package.json') {
  778. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  779. }
  780. return null;
  781. },
  782. getProjectRoot: () => '/test',
  783. getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
  784. };
  785. const frameworks = detectFrameworks(context);
  786. const reactResolver = frameworks.find((f) => f.name === 'react');
  787. const ref = {
  788. fromNodeId: 'component:src/App.tsx:App:1',
  789. referenceName: 'useAuth',
  790. referenceKind: 'calls' as const,
  791. line: 5,
  792. column: 10,
  793. filePath: 'src/App.tsx',
  794. language: 'typescript' as const,
  795. };
  796. const result = reactResolver!.resolve(ref, context);
  797. expect(result).not.toBeNull();
  798. expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
  799. });
  800. });
  801. describe('Integration Tests', () => {
  802. it('should create resolver from CodeGraph instance', async () => {
  803. // Create a simple TypeScript project
  804. fs.writeFileSync(
  805. path.join(tempDir, 'package.json'),
  806. JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
  807. );
  808. const srcDir = path.join(tempDir, 'src');
  809. fs.mkdirSync(srcDir);
  810. // Create utility file
  811. fs.writeFileSync(
  812. path.join(srcDir, 'utils.ts'),
  813. `export function formatDate(date: Date): string {
  814. return date.toISOString();
  815. }
  816. export function parseDate(str: string): Date {
  817. return new Date(str);
  818. }`
  819. );
  820. // Create main file that uses utils
  821. fs.writeFileSync(
  822. path.join(srcDir, 'main.ts'),
  823. `import { formatDate, parseDate } from './utils';
  824. function processDate(input: string): string {
  825. const date = parseDate(input);
  826. return formatDate(date);
  827. }`
  828. );
  829. // Initialize and index
  830. cg = await CodeGraph.init(tempDir, { index: true });
  831. // Check that resolver detected React framework
  832. const frameworks = cg.getDetectedFrameworks();
  833. expect(frameworks).toContain('react');
  834. // Get stats to verify indexing worked
  835. const stats = cg.getStats();
  836. expect(stats.fileCount).toBe(2);
  837. expect(stats.nodeCount).toBeGreaterThan(0);
  838. });
  839. it('should resolve references after indexing', async () => {
  840. // Create a project with references
  841. const srcDir = path.join(tempDir, 'src');
  842. fs.mkdirSync(srcDir, { recursive: true });
  843. fs.writeFileSync(
  844. path.join(srcDir, 'helper.ts'),
  845. `export function helperFunction(): void {
  846. console.log('helper');
  847. }`
  848. );
  849. fs.writeFileSync(
  850. path.join(srcDir, 'main.ts'),
  851. `import { helperFunction } from './helper';
  852. function main(): void {
  853. helperFunction();
  854. }`
  855. );
  856. cg = await CodeGraph.init(tempDir, { index: true });
  857. // Run reference resolution
  858. const result = cg.resolveReferences();
  859. // Should have attempted resolution
  860. expect(result.stats.total).toBeGreaterThanOrEqual(0);
  861. });
  862. it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
  863. // Python has no `new` keyword — `Foo()` is the standard
  864. // instantiation syntax. Extraction can't tell that apart from
  865. // a function call without symbol info, so it emits a `calls`
  866. // ref. Resolution promotes it to `instantiates` once the
  867. // target is known to be a class.
  868. const srcDir = path.join(tempDir, 'src');
  869. fs.mkdirSync(srcDir, { recursive: true });
  870. fs.writeFileSync(
  871. path.join(srcDir, 'app.py'),
  872. `class UserService:
  873. def __init__(self):
  874. self.db = None
  875. def bootstrap():
  876. return UserService()
  877. `
  878. );
  879. cg = await CodeGraph.init(tempDir, { index: true });
  880. cg.resolveReferences();
  881. const bootstrap = cg
  882. .getNodesByKind('function')
  883. .find((n) => n.name === 'bootstrap');
  884. expect(bootstrap).toBeDefined();
  885. const outgoing = cg.getOutgoingEdges(bootstrap!.id);
  886. const instantiates = outgoing.find((e) => e.kind === 'instantiates');
  887. expect(instantiates).toBeDefined();
  888. // Same edge must NOT also appear as a `calls` edge — promotion
  889. // replaces the kind, doesn't duplicate.
  890. const callsToUserService = outgoing.filter(
  891. (e) => e.kind === 'calls' && e.target === instantiates!.target
  892. );
  893. expect(callsToUserService).toHaveLength(0);
  894. });
  895. it('records instantiates for C++ stack/brace construction, targeting the class (#1035)', async () => {
  896. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init)
  897. // carry the constructor args directly on the declarator — there's no
  898. // call/new node — so they recorded no `instantiates` edge, while heap
  899. // `new Calculator(0)` did. Both stack forms now do.
  900. fs.writeFileSync(
  901. path.join(tempDir, 'm.cpp'),
  902. `class Calculator { public: Calculator(int seed) {} int add(int a, int b){ return a+b; } };
  903. class Widget { public: Widget(int a, int b) {} };
  904. int runStack(int a, int b) { Calculator calc(0); return calc.add(a, b); }
  905. int runBrace() { Widget w{1, 2}; return 0; }
  906. int runHeap(int a, int b) { Calculator* c = new Calculator(0); return c->add(a, b); }
  907. void noise() { int x(5); int y{6}; Calculator deferred; }
  908. `
  909. );
  910. cg = await CodeGraph.init(tempDir, { index: true });
  911. const fn = (name: string) => cg.getNodesByKind('function').find((n) => n.name === name)!;
  912. const instTargets = (name: string) =>
  913. cg
  914. .getOutgoingEdges(fn(name).id)
  915. .filter((e) => e.kind === 'instantiates')
  916. .map((e) => cg.getNode(e.target)!);
  917. // Direct-init (the issue) and brace-init both instantiate, targeting the
  918. // CLASS node — not the same-named constructor method.
  919. const stack = instTargets('runStack');
  920. expect(stack.map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  921. expect(instTargets('runBrace').map((n) => `${n.kind}:${n.name}`)).toContain('class:Widget');
  922. // Heap still works (regression guard).
  923. expect(instTargets('runHeap').map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  924. // Primitives (`int x(0)`/`int y{6}`) and bare default construction
  925. // (`Calculator deferred;`) must NOT mint an instantiates edge.
  926. expect(instTargets('noise')).toHaveLength(0);
  927. });
  928. it('resolves a cross-file static method call to the method, not the class (#825)', async () => {
  929. // `Foo.bar()` where `Foo` is an imported class must link to the static
  930. // method `Foo::bar`, NOT to the class `Foo`. Previously the import
  931. // resolver dropped the `.bar` member and resolved to `Foo`, which the
  932. // calls→instantiates promotion then turned into `run instantiates Foo`,
  933. // leaving the static method with zero callers and a hollow impact radius.
  934. fs.writeFileSync(
  935. path.join(tempDir, 'helpers.ts'),
  936. `export class Foo {\n static bar(x: number) { return x + 1; }\n}\n`
  937. );
  938. fs.writeFileSync(
  939. path.join(tempDir, 'caller.ts'),
  940. `import { Foo } from './helpers';\nexport function run() { return Foo.bar(41); }\n`
  941. );
  942. cg = await CodeGraph.init(tempDir, { index: true });
  943. cg.resolveReferences();
  944. const bar = cg.getNodesByKind('method').find((n) => n.name === 'bar');
  945. const foo = cg.getNodesByKind('class').find((n) => n.name === 'Foo');
  946. const run = cg.getNodesByKind('function').find((n) => n.name === 'run');
  947. expect(bar).toBeDefined();
  948. expect(foo).toBeDefined();
  949. expect(run).toBeDefined();
  950. // `run` is reported as a caller of the static method `Foo.bar`.
  951. const barCallers = cg.getCallers(bar!.id).map((c) => c.node.name);
  952. expect(barCallers).toContain('run');
  953. // And the call is NOT mis-promoted to `run instantiates Foo`.
  954. const outgoing = cg.getOutgoingEdges(run!.id);
  955. expect(
  956. outgoing.filter((e) => e.kind === 'instantiates' && e.target === foo!.id)
  957. ).toHaveLength(0);
  958. // The real edge is a `calls` edge to the method.
  959. expect(
  960. outgoing.some((e) => e.kind === 'calls' && e.target === bar!.id)
  961. ).toBe(true);
  962. });
  963. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  964. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  965. // external (isExternalImport returned true for any non-`/internal/`
  966. // import without `.`-prefix) and resolution fell through to name-match
  967. // with path proximity — recall on cross-package callers was ~<1%.
  968. fs.writeFileSync(
  969. path.join(tempDir, 'go.mod'),
  970. 'module github.com/example/myproject\n\ngo 1.21\n'
  971. );
  972. const pkgaDir = path.join(tempDir, 'pkga');
  973. const pkgbDir = path.join(tempDir, 'pkgb');
  974. const pkgcDir = path.join(tempDir, 'pkgc');
  975. fs.mkdirSync(pkgaDir);
  976. fs.mkdirSync(pkgbDir);
  977. fs.mkdirSync(pkgcDir);
  978. // Same-name exported function in two packages — only the imported one
  979. // should resolve. Exercises disambiguation, not just connectivity.
  980. fs.writeFileSync(
  981. path.join(pkgaDir, 'conv.go'),
  982. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  983. );
  984. fs.writeFileSync(
  985. path.join(pkgbDir, 'conv.go'),
  986. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  987. );
  988. fs.writeFileSync(
  989. path.join(pkgcDir, 'use.go'),
  990. `package pkgc
  991. import "github.com/example/myproject/pkga"
  992. func UsePkga() {
  993. pkga.Convert(5)
  994. }
  995. `
  996. );
  997. cg = await CodeGraph.init(tempDir, { index: true });
  998. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  999. expect(usePkga).toBeDefined();
  1000. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  1001. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  1002. expect(callEdges).toHaveLength(1);
  1003. const target = cg.getNode(callEdges[0]!.target);
  1004. expect(target?.name).toBe('Convert');
  1005. // Critical: the resolver must pick the imported pkga's Convert,
  1006. // not pkgb's. With the broken (pre-fix) resolver this lands on
  1007. // whichever Convert happens to be cheaper under path proximity.
  1008. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  1009. });
  1010. it('resolves Go aliased imports across packages (#388)', async () => {
  1011. fs.writeFileSync(
  1012. path.join(tempDir, 'go.mod'),
  1013. 'module github.com/example/myproject\n\ngo 1.21\n'
  1014. );
  1015. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  1016. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  1017. fs.writeFileSync(
  1018. path.join(tempDir, 'pkgb', 'lib.go'),
  1019. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  1020. );
  1021. fs.writeFileSync(
  1022. path.join(tempDir, 'pkgd', 'use.go'),
  1023. `package pkgd
  1024. import (
  1025. "fmt"
  1026. alias "github.com/example/myproject/pkgb"
  1027. )
  1028. func UseAliased() {
  1029. fmt.Println("hi")
  1030. alias.Compute(3)
  1031. }
  1032. `
  1033. );
  1034. cg = await CodeGraph.init(tempDir, { index: true });
  1035. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  1036. expect(useAliased).toBeDefined();
  1037. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  1038. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  1039. expect(calls).toHaveLength(1);
  1040. const target = cg.getNode(calls[0]!.target);
  1041. expect(target?.name).toBe('Compute');
  1042. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  1043. });
  1044. it('resolves Python module-attribute calls after `from pkg import module` (#578)', async () => {
  1045. // Pre-#578, a `module.func()` call where `module` was bound via
  1046. // `from pkg import module` dropped its `calls` edge. The file→file import
  1047. // edge resolved (resolveModuleImportToFile falls back to a dotted-module
  1048. // file lookup for absolute package paths), but resolvePythonModuleMember
  1049. // had no such fallback — resolveImportPath returns null for an absolute
  1050. // package path like `pkg.module`, so the member never resolved and
  1051. // callers/callees/impact on the target came back empty. Same root-cause
  1052. // class as the Go cross-package qualified call (#388).
  1053. fs.mkdirSync(path.join(tempDir, 'pkg'));
  1054. fs.writeFileSync(path.join(tempDir, 'pkg', '__init__.py'), '');
  1055. fs.writeFileSync(
  1056. path.join(tempDir, 'pkg', 'module.py'),
  1057. 'def func():\n return 1\n'
  1058. );
  1059. fs.writeFileSync(
  1060. path.join(tempDir, 'main.py'),
  1061. `from pkg import module
  1062. import os
  1063. def caller():
  1064. return module.func()
  1065. def external_caller():
  1066. return os.getcwd()
  1067. `
  1068. );
  1069. cg = await CodeGraph.init(tempDir, { index: true });
  1070. const caller = cg.getNodesByKind('function').filter((n) => n.name === 'caller')[0];
  1071. expect(caller).toBeDefined();
  1072. const calls = cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls');
  1073. // module.func() must resolve to the real function in the submodule file.
  1074. expect(calls).toHaveLength(1);
  1075. const target = cg.getNode(calls[0]!.target);
  1076. expect(target?.name).toBe('func');
  1077. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkg/module.py');
  1078. // The flip side of the fix: an attribute call through a *stdlib* module
  1079. // (`os.getcwd()`) must still create no edge — the fallback only matches
  1080. // real in-repo module files.
  1081. const externalCaller = cg.getNodesByKind('function').filter((n) => n.name === 'external_caller')[0];
  1082. expect(externalCaller).toBeDefined();
  1083. const externalCalls = cg.getOutgoingEdges(externalCaller!.id).filter((e) => e.kind === 'calls');
  1084. expect(externalCalls).toHaveLength(0);
  1085. });
  1086. it('attaches Go methods to their receiver type across files (#583, cross-file half)', async () => {
  1087. // In Go a type's methods are commonly declared in a different file from the
  1088. // `type` declaration (`type Box` in box.go, `func (b *Box) Get()` in
  1089. // box_methods.go). Extraction only attaches the struct→method `contains`
  1090. // edge when the type is in the SAME file (the owner lookup is file-scoped),
  1091. // so a cross-file method was orphaned from its struct — breaking member
  1092. // outlines and any callers/callees/impact traversal through `contains`. A
  1093. // resolution-phase pass now links them within the package (= directory).
  1094. fs.writeFileSync(
  1095. path.join(tempDir, 'box.go'),
  1096. 'package main\n\ntype Box struct{ v int }\n'
  1097. );
  1098. fs.writeFileSync(
  1099. path.join(tempDir, 'box_methods.go'),
  1100. 'package main\n\nfunc (b *Box) Get() int { return b.v }\nfunc (b *Box) Set(x int) { b.v = x }\n'
  1101. );
  1102. // Generic receiver declared cross-file too — exercises #583 half A
  1103. // (generic `*Stack[T]` receiver parsing) and half B (cross-file) together.
  1104. fs.writeFileSync(
  1105. path.join(tempDir, 'stack.go'),
  1106. 'package main\n\ntype Stack[T any] struct {\n\titems []T\n}\n'
  1107. );
  1108. fs.writeFileSync(
  1109. path.join(tempDir, 'stack_push.go'),
  1110. 'package main\n\nfunc (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }\n'
  1111. );
  1112. // A same-named type in another package must NOT capture this package's
  1113. // methods — the link is scoped to the receiver type's own directory.
  1114. fs.mkdirSync(path.join(tempDir, 'other'));
  1115. fs.writeFileSync(
  1116. path.join(tempDir, 'other', 'box.go'),
  1117. 'package other\n\ntype Box struct{ w int }\n'
  1118. );
  1119. cg = await CodeGraph.init(tempDir, { index: true });
  1120. const methodsOf = (typeName: string, file: string): string[] => {
  1121. const node = cg
  1122. .getNodesByKind('struct')
  1123. .find((n) => n.name === typeName && n.filePath.replace(/\\/g, '/') === file);
  1124. expect(node, `${typeName} @ ${file}`).toBeDefined();
  1125. return cg
  1126. .getOutgoingEdges(node!.id)
  1127. .filter((e) => e.kind === 'contains')
  1128. .map((e) => cg.getNode(e.target))
  1129. .filter((n) => !!n && n.kind === 'method')
  1130. .map((n) => n!.name)
  1131. .sort();
  1132. };
  1133. // Cross-file (non-generic) methods now attach to their struct.
  1134. expect(methodsOf('Box', 'box.go')).toEqual(['Get', 'Set']);
  1135. // Generic + cross-file.
  1136. expect(methodsOf('Stack', 'stack.go')).toEqual(['Push']);
  1137. // Cross-package isolation: other/Box defines no methods of its own.
  1138. expect(methodsOf('Box', 'other/box.go')).toEqual([]);
  1139. });
  1140. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  1141. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  1142. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  1143. // because the type_alias had no `stop` node — only the unrelated
  1144. // class did. Now type_alias produces member nodes (property/method),
  1145. // so the camelCase receiver↔type word overlap pulls the call to
  1146. // `RecorderHandle::stop` instead of the look-alike class.
  1147. fs.mkdirSync(path.join(tempDir, 'voice'));
  1148. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  1149. fs.writeFileSync(
  1150. path.join(tempDir, 'voice', 'recorder.ts'),
  1151. `export type RecorderHandle = {
  1152. wavPath: string;
  1153. stop: () => Promise<{ ok: true }>;
  1154. };
  1155. `
  1156. );
  1157. fs.writeFileSync(
  1158. path.join(tempDir, 'voice', 'controller.ts'),
  1159. `import type { RecorderHandle } from "./recorder";
  1160. export async function finaliseRecording(recorder: RecorderHandle) {
  1161. return await recorder.stop();
  1162. }
  1163. `
  1164. );
  1165. fs.writeFileSync(
  1166. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  1167. `export class StdioMcpClient {
  1168. private stopped = false;
  1169. async stop(): Promise<void> { this.stopped = true; }
  1170. }
  1171. `
  1172. );
  1173. cg = await CodeGraph.init(tempDir, { index: true });
  1174. const handleStop = cg
  1175. .getNodesByKind('method')
  1176. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  1177. expect(handleStop).toBeDefined();
  1178. const clientStop = cg
  1179. .getNodesByKind('method')
  1180. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  1181. expect(clientStop).toBeDefined();
  1182. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  1183. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  1184. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  1185. // The class method must have NO callers — voice/'s call must NOT
  1186. // mis-attribute. A non-empty list would mean the false-positive
  1187. // path is still firing.
  1188. expect(clientCallers).toHaveLength(0);
  1189. // Function-typed property surfaces as a `method` node, not `property`,
  1190. // because `stop()` semantics at the call site are method semantics.
  1191. expect(handleStop!.kind).toBe('method');
  1192. });
  1193. it('Java import disambiguates same-name classes across modules (#314)', async () => {
  1194. // Pre-#314 the import resolver had no Java branch at all, so a
  1195. // multi-module Maven repo where `dao/converter/FooConverter` and
  1196. // `service/converter/FooConverter` both export a `convert` method
  1197. // resolved by file-path proximity — picking whichever class was
  1198. // closer to the caller, which is wrong any time the caller lives
  1199. // in an equidistant cross-cutting module.
  1200. const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
  1201. const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
  1202. const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
  1203. fs.mkdirSync(daoDir, { recursive: true });
  1204. fs.mkdirSync(serviceDir, { recursive: true });
  1205. fs.mkdirSync(webDir, { recursive: true });
  1206. fs.writeFileSync(
  1207. path.join(daoDir, 'FooConverter.java'),
  1208. `package com.example.dao.converter;
  1209. public class FooConverter { public String convert(String x) { return "dao:" + x; } }
  1210. `
  1211. );
  1212. fs.writeFileSync(
  1213. path.join(serviceDir, 'FooConverter.java'),
  1214. `package com.example.service.converter;
  1215. public class FooConverter { public String convert(String x) { return "svc:" + x; } }
  1216. `
  1217. );
  1218. // The caller imports the SERVICE version — even though dao is
  1219. // alphabetically/lexically first in the candidate list, the
  1220. // import must trump that order.
  1221. fs.writeFileSync(
  1222. path.join(webDir, 'Handler.java'),
  1223. `package com.example.web;
  1224. import com.example.service.converter.FooConverter;
  1225. public class Handler {
  1226. private FooConverter fooConverter;
  1227. public String use() { return fooConverter.convert("input"); }
  1228. }
  1229. `
  1230. );
  1231. cg = await CodeGraph.init(tempDir, { index: true });
  1232. const use = cg
  1233. .getNodesByKind('method')
  1234. .find((n) => n.qualifiedName === 'com.example.web::Handler::use');
  1235. expect(use).toBeDefined();
  1236. const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
  1237. expect(calls.length).toBeGreaterThanOrEqual(1);
  1238. const target = cg.getNode(calls[0]!.target);
  1239. expect(target?.name).toBe('convert');
  1240. expect(target?.filePath.replace(/\\/g, '/')).toBe(
  1241. 'service/src/main/java/com/example/service/converter/FooConverter.java'
  1242. );
  1243. });
  1244. it('C# extracts references from method/property/field types (#381)', async () => {
  1245. // Pre-#381, every C# project produced ZERO `references` edges:
  1246. // csharp.ts was missing returnField, and the type-leaf walker
  1247. // only recognized TS/Java's `type_identifier` nodes — C# uses
  1248. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  1249. const srcDir = path.join(tempDir, 'src');
  1250. fs.mkdirSync(srcDir, { recursive: true });
  1251. fs.writeFileSync(
  1252. path.join(srcDir, 'Dtos.cs'),
  1253. `namespace MyApp;
  1254. public class SessionInfoDto { public string Id { get; set; } = ""; }
  1255. public class UserDto { public string Name { get; set; } = ""; }
  1256. `
  1257. );
  1258. fs.writeFileSync(
  1259. path.join(srcDir, 'Service.cs'),
  1260. `using System.Threading.Tasks;
  1261. namespace MyApp;
  1262. public class DataExporter
  1263. {
  1264. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  1265. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  1266. public SessionInfoDto Latest { get; set; } = new();
  1267. private UserDto _cached;
  1268. }
  1269. `
  1270. );
  1271. cg = await CodeGraph.init(tempDir, { index: true });
  1272. const sessionDto = cg
  1273. .getNodesByKind('class')
  1274. .find((n) => n.name === 'SessionInfoDto');
  1275. const userDto = cg
  1276. .getNodesByKind('class')
  1277. .find((n) => n.name === 'UserDto');
  1278. expect(sessionDto).toBeDefined();
  1279. expect(userDto).toBeDefined();
  1280. const sessionIncoming = cg
  1281. .getIncomingEdges(sessionDto!.id)
  1282. .filter((e) => e.kind === 'references');
  1283. const userIncoming = cg
  1284. .getIncomingEdges(userDto!.id)
  1285. .filter((e) => e.kind === 'references');
  1286. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  1287. // UserDto: Build param, BuildAsync param, _cached field.
  1288. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  1289. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  1290. });
  1291. it('C# primary-constructor parameters record their type dependencies (#237)', async () => {
  1292. // C# 12 primary constructors declare a type's injected dependencies inline
  1293. // (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache)`). Each
  1294. // ctor parameter's type is recorded as a `references` edge from the class,
  1295. // so a DI-registered contract reached only through a primary ctor is no
  1296. // longer reported as having no dependents.
  1297. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1298. fs.writeFileSync(
  1299. path.join(tempDir, 'src', 'Contracts.cs'),
  1300. `namespace App;
  1301. public interface IRepo { }
  1302. public class ICache { }
  1303. `
  1304. );
  1305. fs.writeFileSync(
  1306. path.join(tempDir, 'src', 'OrderService.cs'),
  1307. `namespace App;
  1308. public sealed class OrderService(IRepo repo, [FromKeyedServices("primary")] ICache cache)
  1309. {
  1310. public void Run() { }
  1311. }
  1312. `
  1313. );
  1314. cg = await CodeGraph.init(tempDir, { index: true });
  1315. const svc = cg.getNodesByKind('class').find((n) => n.name === 'OrderService');
  1316. expect(svc).toBeDefined();
  1317. // The class itself must index (it used to vanish under the old grammar).
  1318. const out = cg.getOutgoingEdges(svc!.id).filter((e) => e.kind === 'references');
  1319. const depNames = out.map((e) => cg.getNode(e.target)?.name);
  1320. expect(depNames).toContain('IRepo');
  1321. expect(depNames).toContain('ICache'); // the keyed-DI ([FromKeyedServices]) dependency
  1322. });
  1323. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  1324. fs.writeFileSync(
  1325. path.join(tempDir, 'go.mod'),
  1326. 'module github.com/example/myproject\n\ngo 1.21\n'
  1327. );
  1328. fs.writeFileSync(
  1329. path.join(tempDir, 'main.go'),
  1330. `package main
  1331. import "fmt"
  1332. func main() {
  1333. fmt.Println("hi")
  1334. }
  1335. `
  1336. );
  1337. cg = await CodeGraph.init(tempDir, { index: true });
  1338. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  1339. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  1340. // No spurious in-project edge — fmt.* must stay unresolved/external.
  1341. expect(calls).toHaveLength(0);
  1342. });
  1343. });
  1344. describe('Same-name method disambiguation (#1079)', () => {
  1345. // resolveMethodOnType picks among several methods that share a
  1346. // `Type::method` qualifiedName. The precedence is:
  1347. // 1. preferredFqn (Java/Kotlin import — target is intentionally in
  1348. // ANOTHER file, #314),
  1349. // 2. the call site's OWN file (language-agnostic, #1079),
  1350. // 3. matches[0] (first-indexed) as a last resort.
  1351. const methodNode = (
  1352. id: string,
  1353. filePath: string,
  1354. language: Node['language'] = 'cpp',
  1355. qualifiedName = 'Logger::log',
  1356. name = 'log',
  1357. ): Node => ({
  1358. id, kind: 'method', name, qualifiedName, filePath, language,
  1359. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  1360. });
  1361. const callRef = (filePath: string, language: Node['language'] = 'cpp'): UnresolvedRef => ({
  1362. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1363. line: 2, column: 0, filePath, language,
  1364. });
  1365. const ctxFor = (candidates: Node[]): ResolutionContext => ({
  1366. getNodesInFile: () => [],
  1367. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1368. getNodesByQualifiedName: () => [],
  1369. getNodesByKind: () => [],
  1370. fileExists: () => false,
  1371. readFile: () => null,
  1372. getProjectRoot: () => '',
  1373. getAllFiles: () => [],
  1374. });
  1375. it('prefers the definition in the call site\'s own file (#1079)', () => {
  1376. // matches[0] is the a/ definition; the call comes from b/, so it must
  1377. // resolve to b/ — not collapse onto the first-indexed match.
  1378. const logA = methodNode('m:a', 'a/svc.cpp');
  1379. const logB = methodNode('m:b', 'b/svc.cpp');
  1380. const result = resolveMethodOnType(
  1381. 'Logger', 'log', callRef('b/svc.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1382. );
  1383. expect(result?.targetNodeId).toBe('m:b');
  1384. });
  1385. it('lets an import FQN pin a cross-file target over the same-file preference (#314)', () => {
  1386. // Java: two `Bar::doIt` in different packages. The import FQN pins the
  1387. // alpha package; even though the call site lives in beta's file, the FQN
  1388. // must win — the same-file preference runs only AFTER preferredFqn.
  1389. const alpha = methodNode('m:alpha', 'com/example/alpha/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1390. const beta = methodNode('m:beta', 'com/example/beta/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1391. const result = resolveMethodOnType(
  1392. 'Bar', 'doIt', callRef('com/example/beta/Bar.java', 'java'),
  1393. ctxFor([alpha, beta]), 0.9, 'instance-method', 'com.example.alpha.Bar',
  1394. );
  1395. expect(result?.targetNodeId).toBe('m:alpha');
  1396. });
  1397. it('falls back to the first match when nothing disambiguates', () => {
  1398. // Call site is a third file: no FQN, no same-file candidate → matches[0].
  1399. const logA = methodNode('m:a', 'a/svc.cpp');
  1400. const logB = methodNode('m:b', 'b/svc.cpp');
  1401. const result = resolveMethodOnType(
  1402. 'Logger', 'log', callRef('c/other.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1403. );
  1404. expect(result?.targetNodeId).toBe('m:a');
  1405. });
  1406. it('resolves C++ calls end-to-end to same-named classes in different files (#1079)', async () => {
  1407. // The exact repro from the issue: two files, each with its own
  1408. // `Logger::log`. Before the fix both callers pointed at the first def.
  1409. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1410. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1411. fs.writeFileSync(
  1412. path.join(tempDir, 'a', 'svc.cpp'),
  1413. `class Logger { public: void log() { int a = 1; } };\nvoid useA() { Logger lg; lg.log(); }\n`,
  1414. );
  1415. fs.writeFileSync(
  1416. path.join(tempDir, 'b', 'svc.cpp'),
  1417. `class Logger { public: void log() { int b = 2; } };\nvoid useB() { Logger lg; lg.log(); }\n`,
  1418. );
  1419. cg = await CodeGraph.init(tempDir, { index: true });
  1420. cg.resolveReferences();
  1421. const logInDir = (dir: string) =>
  1422. cg.getNodesByKind('method').find(
  1423. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1424. )!;
  1425. const callTargets = (fnName: string) =>
  1426. cg
  1427. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1428. .filter((e) => e.kind === 'calls')
  1429. .map((e) => e.target);
  1430. const logA = logInDir('a');
  1431. const logB = logInDir('b');
  1432. expect(logA).toBeDefined();
  1433. expect(logB).toBeDefined();
  1434. expect(logA.id).not.toBe(logB.id);
  1435. // Each caller resolves to the Logger::log in its OWN file.
  1436. expect(callTargets('useA')).toContain(logA.id);
  1437. expect(callTargets('useB')).toContain(logB.id);
  1438. });
  1439. it('preferCallSiteFile puts same-file candidates first and is otherwise a no-op', () => {
  1440. const a = methodNode('m:a', 'a/svc.cpp');
  1441. const b = methodNode('m:b', 'b/svc.cpp');
  1442. // Same-file first; the rest keep their original order (stable).
  1443. expect(preferCallSiteFile([a, b], 'b/svc.cpp').map((n) => n.id)).toEqual(['m:b', 'm:a']);
  1444. expect(preferCallSiteFile([a, b], 'a/svc.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1445. // No same-file match → unchanged; <2 candidates → returned as-is.
  1446. expect(preferCallSiteFile([a, b], 'c/other.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1447. expect(preferCallSiteFile([a], 'z/none.cpp')).toHaveLength(1);
  1448. });
  1449. it('matchByQualifiedName prefers the same-file target when a qualified name is ambiguous (#1079)', () => {
  1450. // Two `Logger::log` definitions; an explicit `Logger::log()` call from b/
  1451. // must resolve to b/'s definition, not the first-indexed one.
  1452. const a = methodNode('m:a', 'a/svc.cpp');
  1453. const b = methodNode('m:b', 'b/svc.cpp');
  1454. const ctx: ResolutionContext = {
  1455. getNodesInFile: () => [],
  1456. getNodesByName: (name) => [a, b].filter((n) => n.name === name),
  1457. getNodesByQualifiedName: (q) => (q === 'Logger::log' ? [a, b] : []),
  1458. getNodesByKind: () => [],
  1459. fileExists: () => false,
  1460. readFile: () => null,
  1461. getProjectRoot: () => '',
  1462. getAllFiles: () => [],
  1463. };
  1464. const ref: UnresolvedRef = {
  1465. fromNodeId: 'caller', referenceName: 'Logger::log', referenceKind: 'calls',
  1466. line: 2, column: 0, filePath: 'b/svc.cpp', language: 'cpp',
  1467. };
  1468. expect(matchByQualifiedName(ref, ctx)?.targetNodeId).toBe('m:b');
  1469. });
  1470. it('resolves a static/class-receiver call to the class in the caller\'s file (#1079)', async () => {
  1471. // `Logger.log()` — the receiver is the class NAME, so this routes through
  1472. // the class-name-receiver strategy (not the C++ instance path). It was
  1473. // file-blind across languages; verified here on TypeScript.
  1474. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1475. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1476. fs.writeFileSync(
  1477. path.join(tempDir, 'a', 'svc.ts'),
  1478. `class Logger { static log() { return 1; } }\nexport function useA() { return Logger.log(); }\n`,
  1479. );
  1480. fs.writeFileSync(
  1481. path.join(tempDir, 'b', 'svc.ts'),
  1482. `class Logger { static log() { return 2; } }\nexport function useB() { return Logger.log(); }\n`,
  1483. );
  1484. cg = await CodeGraph.init(tempDir, { index: true });
  1485. cg.resolveReferences();
  1486. const logInDir = (dir: string) =>
  1487. cg.getNodesByKind('method').find(
  1488. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.ts`),
  1489. )!;
  1490. const callTargets = (fnName: string) =>
  1491. cg
  1492. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1493. .filter((e) => e.kind === 'calls')
  1494. .map((e) => e.target);
  1495. const logA = logInDir('a');
  1496. const logB = logInDir('b');
  1497. expect(logA?.id).not.toBe(logB?.id);
  1498. expect(callTargets('useA')).toContain(logA.id);
  1499. expect(callTargets('useB')).toContain(logB.id);
  1500. });
  1501. it('resolves an explicitly-qualified call to the definition in the caller\'s file (#1079)', async () => {
  1502. // `Logger::log()` with two `Logger::log` definitions routes through the
  1503. // qualified-name strategy, whose partial match previously picked the first.
  1504. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1505. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1506. fs.writeFileSync(
  1507. path.join(tempDir, 'a', 'svc.cpp'),
  1508. `class Logger { public: static void log() { int a = 1; } };\nvoid useA() { Logger::log(); }\n`,
  1509. );
  1510. fs.writeFileSync(
  1511. path.join(tempDir, 'b', 'svc.cpp'),
  1512. `class Logger { public: static void log() { int b = 2; } };\nvoid useB() { Logger::log(); }\n`,
  1513. );
  1514. cg = await CodeGraph.init(tempDir, { index: true });
  1515. cg.resolveReferences();
  1516. const logInDir = (dir: string) =>
  1517. cg.getNodesByKind('method').find(
  1518. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1519. )!;
  1520. const callTargets = (fnName: string) =>
  1521. cg
  1522. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1523. .filter((e) => e.kind === 'calls')
  1524. .map((e) => e.target);
  1525. const logA = logInDir('a');
  1526. const logB = logInDir('b');
  1527. expect(logA?.id).not.toBe(logB?.id);
  1528. expect(callTargets('useA')).toContain(logA.id);
  1529. expect(callTargets('useB')).toContain(logB.id);
  1530. });
  1531. });
  1532. describe('Watchdog-safe resolution on collision-heavy repos (#1122)', () => {
  1533. // On a large Java-style repo, per-ref resolution cost is unbounded in the
  1534. // worst case (a colliding method name whose candidate set misses the LRU
  1535. // re-fetches tens of thousands of rows, and receiver inference re-splits
  1536. // the whole source file). v1.2.0 yielded only every 500 refs, so a dense
  1537. // pocket multiplied that cost past the #850 watchdog window and a VALID
  1538. // `init` was SIGKILLed at "Resolving refs". These pin the three guards:
  1539. // per-ref yield checkpoints, the (type, method) match memo, and the
  1540. // per-file lines cache with its generated/minified-line skip.
  1541. const methodNode = (
  1542. id: string,
  1543. filePath: string,
  1544. qualifiedName: string,
  1545. name: string,
  1546. language: Node['language'] = 'typescript',
  1547. kind: Node['kind'] = 'method',
  1548. ): Node => ({
  1549. id, kind, name, qualifiedName, filePath, language,
  1550. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  1551. });
  1552. it('resolveMethodOnType consults the method-match memo and still disambiguates per call site', () => {
  1553. const logA = methodNode('m:a', 'a/svc.ts', 'Logger::log', 'log');
  1554. const logB = methodNode('m:b', 'b/svc.ts', 'Logger::log', 'log');
  1555. const shared = [logA, logB]; // one cached array served to every caller
  1556. let memoCalls = 0;
  1557. let rawNameLookups = 0;
  1558. const ctx: ResolutionContext = {
  1559. getNodesInFile: () => [],
  1560. getNodesByName: () => { rawNameLookups++; return shared; },
  1561. getMethodMatches: () => { memoCalls++; return shared; },
  1562. getNodesByQualifiedName: () => [],
  1563. getNodesByKind: () => [],
  1564. fileExists: () => false,
  1565. readFile: () => null,
  1566. getProjectRoot: () => '',
  1567. getAllFiles: () => [],
  1568. };
  1569. const refFrom = (filePath: string): UnresolvedRef => ({
  1570. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1571. line: 2, column: 0, filePath, language: 'typescript',
  1572. });
  1573. // Both call sites read the SAME memoized array, yet each still resolves
  1574. // to its own file — per-ref disambiguation runs after the memo (#1079).
  1575. const fromA = resolveMethodOnType('Logger', 'log', refFrom('a/svc.ts'), ctx, 0.9, 'instance-method');
  1576. const fromB = resolveMethodOnType('Logger', 'log', refFrom('b/svc.ts'), ctx, 0.9, 'instance-method');
  1577. expect(fromA?.targetNodeId).toBe('m:a');
  1578. expect(fromB?.targetNodeId).toBe('m:b');
  1579. expect(memoCalls).toBe(2);
  1580. expect(rawNameLookups).toBe(0); // memo bypasses the unbounded name fetch
  1581. });
  1582. it('the production resolver context memoizes method matches per (language, type, method)', async () => {
  1583. fs.writeFileSync(
  1584. path.join(tempDir, 'svc.ts'),
  1585. `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n`,
  1586. );
  1587. cg = await CodeGraph.init(tempDir, { index: true });
  1588. const resolver = (cg as unknown as { resolver: ReferenceResolver }).resolver;
  1589. const ctx = (resolver as unknown as { context: ResolutionContext }).context;
  1590. const first = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1591. const second = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1592. expect(first.map((n) => n.qualifiedName)).toEqual(['Logger::log']);
  1593. // Same array instance = served from the memo, not recomputed.
  1594. expect(second).toBe(first);
  1595. resolver.clearCaches();
  1596. const afterClear = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1597. expect(afterClear).not.toBe(first);
  1598. expect(afterClear.map((n) => n.qualifiedName)).toEqual(['Logger::log']);
  1599. });
  1600. it('resolveBatchYielding offers a yield checkpoint for every ref', async () => {
  1601. fs.writeFileSync(
  1602. path.join(tempDir, 'a.ts'),
  1603. `export function fnA() { return 1; }\nexport function fnB() { return fnA(); }\nexport function fnC() { return fnB(); }\n`,
  1604. );
  1605. fs.writeFileSync(
  1606. path.join(tempDir, 'b.ts'),
  1607. `import { fnA } from './a';\nexport function fnD() { return fnA(); }\n`,
  1608. );
  1609. cg = await CodeGraph.init(tempDir, { index: true });
  1610. const resolver = (cg as unknown as { resolver: ReferenceResolver }).resolver;
  1611. // `init({ index: true })` already ran resolution, so feed the batch
  1612. // directly — resolveBatchYielding takes it as an argument; whether each
  1613. // ref resolves is irrelevant to the checkpoint contract.
  1614. const refs: UnresolvedReference[] = ['fnA', 'fnB', 'nosuchFn', 'fnA', 'alsoMissing'].map((name, i) => ({
  1615. fromNodeId: `caller-${i}`,
  1616. referenceName: name,
  1617. referenceKind: 'calls',
  1618. line: i + 1,
  1619. column: 0,
  1620. filePath: 'a.ts',
  1621. language: 'typescript',
  1622. }));
  1623. let checkpoints = 0;
  1624. const countingYield = async () => { checkpoints++; };
  1625. const result = await (resolver as unknown as {
  1626. resolveBatchYielding(batch: UnresolvedReference[], maybeYield: () => Promise<void>): Promise<{ stats: { total: number } }>;
  1627. }).resolveBatchYielding(refs, countingYield);
  1628. // One checkpoint per ref: a pocket of pathologically slow refs can never
  1629. // run more than ONE ref past the yield budget before the heartbeat gets
  1630. // a window — the #1122 kill required 500.
  1631. expect(checkpoints).toBe(refs.length);
  1632. expect(result.stats.total).toBe(refs.length);
  1633. });
  1634. it('receiver inference reads lines through getFileLines when the context provides it', () => {
  1635. const loggerClass = methodNode('c:logger', 'svc.ts', 'Logger', 'Logger', 'typescript', 'class');
  1636. const logMethod = methodNode('m:log', 'svc.ts', 'Logger::log', 'log');
  1637. const otherLog = methodNode('m:other', 'other.ts', 'Other::log', 'log');
  1638. const byName: Record<string, Node[]> = {
  1639. Logger: [loggerClass],
  1640. log: [logMethod, otherLog], // ambiguous bare name → only inference can resolve
  1641. };
  1642. const lines = ['const lg = new Logger();', 'lg.log();'];
  1643. const ctx: ResolutionContext = {
  1644. getNodesInFile: () => [],
  1645. getNodesByName: (name) => byName[name] ?? [],
  1646. getNodesByQualifiedName: () => [],
  1647. getNodesByKind: () => [],
  1648. fileExists: () => false,
  1649. // Reading the raw source must not be needed when lines are provided.
  1650. readFile: () => { throw new Error('readFile must not be called when getFileLines exists'); },
  1651. getFileLines: () => lines,
  1652. getProjectRoot: () => '',
  1653. getAllFiles: () => [],
  1654. };
  1655. const ref: UnresolvedRef = {
  1656. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1657. line: 2, column: 0, filePath: 'svc.ts', language: 'typescript',
  1658. };
  1659. expect(matchMethodCall(ref, ctx)?.targetNodeId).toBe('m:log');
  1660. });
  1661. it('receiver inference skips generated/minified lines instead of regex-scanning them', () => {
  1662. const loggerClass = methodNode('c:logger', 'svc.ts', 'Logger', 'Logger', 'typescript', 'class');
  1663. const logMethod = methodNode('m:log', 'svc.ts', 'Logger::log', 'log');
  1664. const otherLog = methodNode('m:other', 'other.ts', 'Other::log', 'log');
  1665. const byName: Record<string, Node[]> = {
  1666. Logger: [loggerClass],
  1667. log: [logMethod, otherLog],
  1668. };
  1669. const ctxWithLines = (lines: string[]): ResolutionContext => ({
  1670. getNodesInFile: () => [],
  1671. getNodesByName: (name) => byName[name] ?? [],
  1672. getNodesByQualifiedName: () => [],
  1673. getNodesByKind: () => [],
  1674. fileExists: () => false,
  1675. readFile: () => null,
  1676. getFileLines: () => lines,
  1677. getProjectRoot: () => '',
  1678. getAllFiles: () => [],
  1679. });
  1680. const ref: UnresolvedRef = {
  1681. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1682. line: 1, column: 0, filePath: 'svc.ts', language: 'typescript',
  1683. };
  1684. // Control: the declaration on a normal-length line resolves.
  1685. const normal = matchMethodCall(ref, ctxWithLines(['const lg = new Logger(); lg.log();']));
  1686. expect(normal?.targetNodeId).toBe('m:log');
  1687. // The same declaration buried in a >10K-char generated/minified line is
  1688. // skipped — no resolution, and no per-ref regex pass over the huge line.
  1689. const minified = 'var pad="' + 'x'.repeat(10_000) + '";const lg = new Logger(); lg.log();';
  1690. expect(matchMethodCall(ref, ctxWithLines([minified]))).toBeNull();
  1691. });
  1692. });
  1693. describe('Local-variable receiver-type inference (#1108)', () => {
  1694. // `lg.log()` where `lg` is a local whose type is inferred from its
  1695. // declaration/initializer. Before this, only C++ resolved these; every
  1696. // other language produced no method edge. Each case is one file with a
  1697. // single Logger + a caller using a local-variable receiver — a correct
  1698. // resolution makes the caller a caller of `log`.
  1699. const cases: Array<{ lang: string; file: string; src: string }> = [
  1700. { lang: 'TypeScript (= new T)', file: 'svc.ts',
  1701. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1702. { lang: 'JavaScript (= new T)', file: 'svc.js',
  1703. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1704. { lang: 'Python (= T())', file: 'svc.py',
  1705. src: `class Logger:\n def log(self):\n return 1\ndef use():\n lg = Logger()\n return lg.log()\n` },
  1706. { lang: 'Java (T x = new T)', file: 'Svc.java',
  1707. src: `class Logger { void log() { int a = 1; } }\nclass Use { void run() { Logger lg = new Logger(); lg.log(); } }\n` },
  1708. { lang: 'C# (var x = new T)', file: 'Svc.cs',
  1709. src: `class Logger { void Log() { int a = 1; } }\nclass Use { void Run() { var lg = new Logger(); lg.Log(); } }\n` },
  1710. { lang: 'Kotlin (val x = T())', file: 'Svc.kt',
  1711. src: `class Logger { fun log(): Int { return 1 } }\nfun use(): Int { val lg = Logger(); return lg.log() }\n` },
  1712. { lang: 'Swift (let x = T())', file: 'svc.swift',
  1713. src: `class Logger { func log() -> Int { return 1 } }\nfunc use() -> Int { let lg = Logger(); return lg.log() }\n` },
  1714. { lang: 'Go (x := T{})', file: 'svc.go',
  1715. src: `package a\ntype Logger struct{}\nfunc (l Logger) Log() int { return 1 }\nfunc Use() int { lg := Logger{}; return lg.Log() }\n` },
  1716. { lang: 'Rust (let x = T{})', file: 'svc.rs',
  1717. src: `pub struct Logger { n: i32 }\nimpl Logger { pub fn log(&self) -> i32 { self.n } }\npub fn use_it() -> i32 { let lg = Logger { n: 1 }; lg.log() }\n` },
  1718. { lang: 'Dart (var x = T())', file: 'svc.dart',
  1719. src: `class Logger { int log() { return 1; } }\nint use() { var lg = Logger(); return lg.log(); }\n` },
  1720. { lang: 'PHP ($x = new T)', file: 'svc.php',
  1721. src: `<?php\nclass Logger { function log() { return 1; } }\nfunction useIt() { $lg = new Logger(); return $lg->log(); }\n` },
  1722. { lang: 'Scala (val x = new T)', file: 'Svc.scala',
  1723. src: `class Logger { def log(): Int = 1 }\nobject A { def use(): Int = { val lg = new Logger(); lg.log() } }\n` },
  1724. { lang: 'Ruby (x = T.new)', file: 'svc.rb',
  1725. src: `class Logger\n def log\n 1\n end\nend\ndef use\n lg = Logger.new\n lg.log\nend\n` },
  1726. { lang: 'Lua (x = T.new(); x:log())', file: 'svc.lua',
  1727. src: `local Logger = {}\nLogger.__index = Logger\nfunction Logger.new() return setmetatable({}, Logger) end\nfunction Logger:log() return 1 end\nlocal function use() local lg = Logger.new(); return lg:log() end\nreturn use\n` },
  1728. { lang: 'Luau (x = T.new(); x:log())', file: 'svc.luau',
  1729. src: `local Logger = {}\nLogger.__index = Logger\nfunction Logger.new() return setmetatable({}, Logger) end\nfunction Logger:log(): number return 1 end\nlocal function use(): number local lg = Logger.new(); return lg:log() end\nreturn use\n` },
  1730. { lang: 'R (x <- T$new(); x$log())', file: 'svc.R',
  1731. src: `Logger <- R6::R6Class("Logger", public = list(log = function() 1))\nuse <- function() { lg <- Logger$new(); lg$log() }\n` },
  1732. { lang: 'Pascal (var x: T; x.Method)', file: 'svc.pas',
  1733. src: `unit A;\ninterface\ntype TLogger = class function Log: Integer; end;\nimplementation\nfunction TLogger.Log: Integer; begin Result := 1; end;\nprocedure Use;\nvar lg: TLogger;\nbegin\n lg := TLogger.Create;\n lg.Log;\nend;\nend.\n` },
  1734. ];
  1735. for (const c of cases) {
  1736. it(`resolves a local-variable method call — ${c.lang}`, async () => {
  1737. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1738. cg = await CodeGraph.init(tempDir, { index: true });
  1739. cg.resolveReferences();
  1740. const logMethod = cg
  1741. .getNodesByKind('method')
  1742. .find((n) => n.name.toLowerCase() === 'log');
  1743. expect(logMethod, `${c.lang}: log method should be indexed`).toBeDefined();
  1744. // The enclosing caller resolves through the local variable to `log`.
  1745. const callers = cg.getCallers(logMethod!.id).map((x) => x.node.name);
  1746. expect(
  1747. callers.length,
  1748. `${c.lang}: log should have a caller (got [${callers.join(', ')}])`,
  1749. ).toBeGreaterThan(0);
  1750. });
  1751. }
  1752. it('Ruby: builds receiver.method and keeps Foo.new as an instantiation', async () => {
  1753. // The Ruby extractor previously took the receiver as the callee and
  1754. // dropped the method name (`lg.log()` -> a call to `lg`). Now it builds
  1755. // `lg.log`, while `Logger.new` must still record an instantiation.
  1756. fs.writeFileSync(
  1757. path.join(tempDir, 'svc.rb'),
  1758. `class Logger\n def log\n 1\n end\nend\ndef run\n lg = Logger.new\n lg.log\nend\n`,
  1759. );
  1760. cg = await CodeGraph.init(tempDir, { index: true });
  1761. cg.resolveReferences();
  1762. const run = cg.getNodesByKind('function').find((n) => n.name === 'run')!;
  1763. const logMethod = cg.getNodesByKind('method').find((n) => n.name === 'log')!;
  1764. const logger = cg.getNodesByKind('class').find((n) => n.name === 'Logger')!;
  1765. const out = cg.getOutgoingEdges(run.id);
  1766. // lg.log resolved to the method (the receiver-type inference kicked in).
  1767. expect(out.some((e) => e.kind === 'calls' && e.target === logMethod.id)).toBe(true);
  1768. // Logger.new is still an instantiation of the class.
  1769. expect(out.some((e) => e.kind === 'instantiates' && e.target === logger.id)).toBe(true);
  1770. });
  1771. it('TypeScript: infers a typed-parameter receiver, disambiguating same-named methods (#1125)', async () => {
  1772. // A typed function parameter used as a receiver — `function use(lg: Logger)`
  1773. // — never matched the old TS/JS pattern (it required a const|let|var
  1774. // prefix), so `lg.log()` fell through to no edge once a second class shared
  1775. // the method name. Two ambiguous classes are load-bearing here: a
  1776. // single-class version resolves via a same-name fallback even without
  1777. // inference, so only the collision proves type inference actually fired.
  1778. fs.writeFileSync(
  1779. path.join(tempDir, 'svc.ts'),
  1780. `class Logger { log() { return 1; } }\n` +
  1781. `class Other { log() { return 2; } }\n` +
  1782. `export function use(lg: Logger) { return lg.log(); }\n` +
  1783. `export function useOther(o: Other) { return o.log(); }\n`,
  1784. );
  1785. cg = await CodeGraph.init(tempDir, { index: true });
  1786. cg.resolveReferences();
  1787. const classes = cg.getNodesByKind('class');
  1788. const logger = classes.find((n) => n.name === 'Logger')!;
  1789. const other = classes.find((n) => n.name === 'Other')!;
  1790. const logs = cg.getNodesByKind('method').filter((n) => n.name === 'log');
  1791. expect(logs.length, 'both log methods should be indexed').toBe(2);
  1792. // Associate each same-named `log` with its class by line containment.
  1793. const inClass = (m: (typeof logs)[number], c: typeof logger) =>
  1794. m.startLine >= c.startLine && m.startLine <= (c.endLine ?? c.startLine);
  1795. const loggerLog = logs.find((m) => inClass(m, logger))!;
  1796. const otherLog = logs.find((m) => inClass(m, other))!;
  1797. expect(loggerLog, "Logger's log").toBeDefined();
  1798. expect(otherLog, "Other's log").toBeDefined();
  1799. const loggerCallers = cg.getCallers(loggerLog.id).map((x) => x.node.name);
  1800. const otherCallers = cg.getCallers(otherLog.id).map((x) => x.node.name);
  1801. // Each typed-param call routes to its OWN class's method, not the other's.
  1802. expect(loggerCallers).toContain('use');
  1803. expect(loggerCallers).not.toContain('useOther');
  1804. expect(otherCallers).toContain('useOther');
  1805. expect(otherCallers).not.toContain('use');
  1806. });
  1807. // The same typed-parameter gap existed in every language whose pattern set
  1808. // only matched keyword-anchored locals (let/var/:=/= new), not the bare
  1809. // parameter form — Rust, Go, Dart, PHP (#1125). Each case: two classes
  1810. // sharing a method name + two functions taking one as a typed param; a
  1811. // correct fix routes each call to its OWN type's method (the collision is
  1812. // load-bearing — a single class resolves via the same-name fallback either
  1813. // way). Method↔type association is by qualifiedName, robust where the method
  1814. // lives outside the type's line range (Rust `impl`, Go method decl).
  1815. const typedParamCases: Array<{
  1816. lang: string; file: string; method: string; callerA: string; callerB: string; src: string;
  1817. }> = [
  1818. { lang: 'Rust (fn f(x: &T))', file: 'svc.rs', method: 'log', callerA: 'use_it', callerB: 'use_other',
  1819. src: `pub struct Logger { n: i32 }\nimpl Logger { pub fn log(&self) -> i32 { self.n } }\npub struct Other { n: i32 }\nimpl Other { pub fn log(&self) -> i32 { self.n } }\npub fn use_it(lg: &Logger) -> i32 { lg.log() }\npub fn use_other(o: &Other) -> i32 { o.log() }\n` },
  1820. { lang: 'Go (func f(x T))', file: 'svc.go', method: 'Log', callerA: 'UseIt', callerB: 'UseOther',
  1821. src: `package a\ntype Logger struct{}\nfunc (l Logger) Log() int { return 1 }\ntype Other struct{}\nfunc (o Other) Log() int { return 2 }\nfunc UseIt(lg Logger) int { return lg.Log() }\nfunc UseOther(o Other) int { return o.Log() }\n` },
  1822. { lang: 'Dart (T f(U x))', file: 'svc.dart', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1823. src: `class Logger { int log() { return 1; } }\nclass Other { int log() { return 2; } }\nint useIt(Logger lg) { return lg.log(); }\nint useOther(Other o) { return o.log(); }\n` },
  1824. { lang: 'PHP (f(T $x))', file: 'svc.php', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1825. src: `<?php\nclass Logger { function log() { return 1; } }\nclass Other { function log() { return 2; } }\nfunction useIt(Logger $lg) { return $lg->log(); }\nfunction useOther(Other $o) { return $o->log(); }\n` },
  1826. ];
  1827. for (const c of typedParamCases) {
  1828. it(`infers a typed-parameter receiver, disambiguating same-named methods — ${c.lang} (#1125)`, async () => {
  1829. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1830. cg = await CodeGraph.init(tempDir, { index: true });
  1831. cg.resolveReferences();
  1832. const methods = cg.getNodesByKind('method').filter((n) => n.name === c.method);
  1833. expect(methods.length, `${c.lang}: both ${c.method} methods indexed`).toBe(2);
  1834. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1835. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1836. expect(loggerLog, `${c.lang}: Logger's ${c.method}`).toBeDefined();
  1837. expect(otherLog, `${c.lang}: Other's ${c.method}`).toBeDefined();
  1838. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1839. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1840. expect(loggerCallers, `${c.lang}: Logger callers`).toContain(c.callerA);
  1841. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain(c.callerB);
  1842. expect(otherCallers, `${c.lang}: Other callers`).toContain(c.callerB);
  1843. expect(otherCallers, `${c.lang}: Other callers`).not.toContain(c.callerA);
  1844. });
  1845. }
  1846. // Lua/Luau: a PascalCase method call (`lg:Log()`, the Roblox convention)
  1847. // is the identical `receiver:Name` shape as a Luau type annotation, so it
  1848. // self-matched the annotation pattern on the call's own line and inferred
  1849. // "type = Log" (#1124). Two things are load-bearing in these fixtures:
  1850. // the declaration sits on an EARLIER line than the call (on one line,
  1851. // pattern order resolves it — the `.new` pattern wins first), and TWO
  1852. // classes share the method name (a single class resolves via the
  1853. // same-name fallback even when inference misfires). Luau's `useLogger`
  1854. // takes a typed param instead of calling `.new()`, pinning that the
  1855. // gated pattern still matches a genuine annotation.
  1856. const pascalMethodCases: Array<{ lang: string; file: string; src: string }> = [
  1857. { lang: 'Lua', file: 'svc.lua',
  1858. src: `local Logger = {}\nLogger.__index = Logger\nfunction Logger.new() return setmetatable({}, Logger) end\nfunction Logger:Log() return 1 end\n\nlocal Other = {}\nOther.__index = Other\nfunction Other.new() return setmetatable({}, Other) end\nfunction Other:Log() return 2 end\n\nlocal function useLogger()\n\tlocal lg = Logger.new()\n\treturn lg:Log()\nend\n\nlocal function useOther()\n\tlocal o = Other.new()\n\treturn o:Log()\nend\n\nreturn useLogger, useOther\n` },
  1859. { lang: 'Luau', file: 'svc.luau',
  1860. src: `local Logger = {}\nLogger.__index = Logger\nfunction Logger.new() return setmetatable({}, Logger) end\nfunction Logger:Log(): number return 1 end\n\nlocal Other = {}\nOther.__index = Other\nfunction Other.new() return setmetatable({}, Other) end\nfunction Other:Log(): number return 2 end\n\nlocal function useLogger(lg: Logger): number\n\treturn lg:Log()\nend\n\nlocal function useOther(): number\n\tlocal o = Other.new()\n\treturn o:Log()\nend\n\nreturn useLogger, useOther\n` },
  1861. ];
  1862. for (const c of pascalMethodCases) {
  1863. it(`resolves a PascalCase method call without self-matching the annotation pattern — ${c.lang} (#1124)`, async () => {
  1864. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1865. cg = await CodeGraph.init(tempDir, { index: true });
  1866. cg.resolveReferences();
  1867. const methods = cg.getNodesByKind('method').filter((n) => n.name === 'Log');
  1868. expect(methods.length, `${c.lang}: both Log methods indexed`).toBe(2);
  1869. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1870. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1871. expect(loggerLog, `${c.lang}: Logger's Log`).toBeDefined();
  1872. expect(otherLog, `${c.lang}: Other's Log`).toBeDefined();
  1873. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1874. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1875. expect(loggerCallers, `${c.lang}: Logger callers`).toContain('useLogger');
  1876. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain('useOther');
  1877. expect(otherCallers, `${c.lang}: Other callers`).toContain('useOther');
  1878. expect(otherCallers, `${c.lang}: Other callers`).not.toContain('useLogger');
  1879. });
  1880. }
  1881. });
  1882. describe('Name Matcher: kind bias for new ref kinds', () => {
  1883. const baseContext = (candidates: Node[]): ResolutionContext => ({
  1884. getNodesInFile: () => [],
  1885. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1886. getNodesByQualifiedName: () => [],
  1887. getNodesByKind: () => [],
  1888. fileExists: () => true,
  1889. readFile: () => null,
  1890. getProjectRoot: () => '/test',
  1891. getAllFiles: () => [],
  1892. getNodesByLowerName: () => [],
  1893. getImportMappings: () => [],
  1894. });
  1895. it('prefers a class candidate over a function for `instantiates` refs', () => {
  1896. // A class and a function share a name across the codebase.
  1897. // Without the kind bias, the function (which gets the +25 `calls`
  1898. // bonus historically applied to all candidates of that kind) would
  1899. // win. Now the instantiates branch reverses it.
  1900. const fn: Node = {
  1901. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  1902. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  1903. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1904. };
  1905. const cls: Node = {
  1906. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  1907. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  1908. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1909. };
  1910. const ref = {
  1911. fromNodeId: 'func:main.ts:bootstrap:1',
  1912. referenceName: 'Logger',
  1913. referenceKind: 'instantiates' as const,
  1914. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  1915. };
  1916. const result = matchReference(ref, baseContext([fn, cls]));
  1917. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  1918. });
  1919. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  1920. const variable: Node = {
  1921. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  1922. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  1923. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1924. };
  1925. const decorator: Node = {
  1926. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  1927. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  1928. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1929. };
  1930. const ref = {
  1931. fromNodeId: 'class:svc.ts:UserService:1',
  1932. referenceName: 'Inject',
  1933. referenceKind: 'decorates' as const,
  1934. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  1935. };
  1936. const result = matchReference(ref, baseContext([variable, decorator]));
  1937. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  1938. });
  1939. });
  1940. describe('tsconfig path aliases', () => {
  1941. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  1942. // Two same-named exports in different directories. Without alias
  1943. // resolution, name-matcher would pick whichever it finds first;
  1944. // with alias resolution, the import path uniquely picks one.
  1945. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1946. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  1947. fs.writeFileSync(
  1948. path.join(tempDir, 'src/utils/format.ts'),
  1949. `export function pickMe(): number { return 1; }\n`
  1950. );
  1951. fs.writeFileSync(
  1952. path.join(tempDir, 'src/legacy/format.ts'),
  1953. `export function pickMe(): number { return 99; }\n`
  1954. );
  1955. fs.writeFileSync(
  1956. path.join(tempDir, 'src/main.ts'),
  1957. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  1958. );
  1959. fs.writeFileSync(
  1960. path.join(tempDir, 'tsconfig.json'),
  1961. JSON.stringify({
  1962. compilerOptions: {
  1963. baseUrl: './src',
  1964. paths: { '@utils/*': ['utils/*'] },
  1965. },
  1966. })
  1967. );
  1968. cg = await CodeGraph.init(tempDir, { index: true });
  1969. cg.resolveReferences();
  1970. // The two pickMe nodes live in different files. The aliased
  1971. // import should attach the call edge to the @utils-mapped one,
  1972. // not the legacy duplicate.
  1973. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  1974. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  1975. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  1976. expect(utilsNode).toBeDefined();
  1977. expect(legacyNode).toBeDefined();
  1978. const utilsCallers = cg.getCallers(utilsNode!.id);
  1979. const legacyCallers = cg.getCallers(legacyNode!.id);
  1980. expect(utilsCallers.length).toBeGreaterThan(0);
  1981. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1982. // The legacy node should NOT have a caller from src/main.ts —
  1983. // the alias correctly picked the utils version.
  1984. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  1985. });
  1986. it('falls back gracefully when tsconfig is absent', async () => {
  1987. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1988. fs.writeFileSync(
  1989. path.join(tempDir, 'src/a.ts'),
  1990. `export function aFn(): void {}\n`
  1991. );
  1992. fs.writeFileSync(
  1993. path.join(tempDir, 'src/b.ts'),
  1994. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  1995. );
  1996. cg = await CodeGraph.init(tempDir, { index: true });
  1997. // No tsconfig present — index should still complete and the
  1998. // relative-import-based call edge should be created.
  1999. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  2000. expect(aFn).toBeDefined();
  2001. const callers = cg.getCallers(aFn!.id);
  2002. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  2003. });
  2004. });
  2005. describe('re-export chain following', () => {
  2006. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  2007. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  2008. // Without chain following, `signIn` resolves to nothing because
  2009. // none of the barrel files declare it directly.
  2010. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  2011. fs.writeFileSync(
  2012. path.join(tempDir, 'src/services/auth.ts'),
  2013. `export function signIn(): void {}\n`
  2014. );
  2015. fs.writeFileSync(
  2016. path.join(tempDir, 'src/services/index.ts'),
  2017. `export { signIn } from './auth';\n`
  2018. );
  2019. fs.writeFileSync(
  2020. path.join(tempDir, 'src/all.ts'),
  2021. `export * from './services/index';\n`
  2022. );
  2023. fs.writeFileSync(
  2024. path.join(tempDir, 'src/main.ts'),
  2025. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  2026. );
  2027. cg = await CodeGraph.init(tempDir, { index: true });
  2028. cg.resolveReferences();
  2029. const signInNode = cg
  2030. .getNodesByKind('function')
  2031. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  2032. expect(signInNode).toBeDefined();
  2033. const callers = cg.getCallers(signInNode!.id);
  2034. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2035. });
  2036. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  2037. // The chase has to look up `foo` in the upstream module even
  2038. // though the importer asked for `bar` — exercises the rename
  2039. // branch of findExportedSymbol.
  2040. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2041. fs.writeFileSync(
  2042. path.join(tempDir, 'src/auth.ts'),
  2043. `export function signIn(): void {}\n`
  2044. );
  2045. fs.writeFileSync(
  2046. path.join(tempDir, 'src/index.ts'),
  2047. `export { signIn as login } from './auth';\n`
  2048. );
  2049. fs.writeFileSync(
  2050. path.join(tempDir, 'src/main.ts'),
  2051. `import { login } from './index';\nexport function go(): void { login(); }\n`
  2052. );
  2053. cg = await CodeGraph.init(tempDir, { index: true });
  2054. cg.resolveReferences();
  2055. const signInNode = cg
  2056. .getNodesByKind('function')
  2057. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  2058. expect(signInNode).toBeDefined();
  2059. const callers = cg.getCallers(signInNode!.id);
  2060. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2061. });
  2062. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  2063. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  2064. // .svelte component (extracted as kind 'component', the default
  2065. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  2066. // component's real name (`RealButton`) so the name-matcher fallback
  2067. // can't coincidentally connect them — the only path to the edge is
  2068. // the import-chase, which must match a `component` (not just
  2069. // function/class) for the default export. Otherwise the
  2070. // consumer↔component edge is never created and `callers` returns a
  2071. // false 0.
  2072. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2073. fs.writeFileSync(
  2074. path.join(tempDir, 'src/lib/RealButton.svelte'),
  2075. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2076. );
  2077. fs.writeFileSync(
  2078. path.join(tempDir, 'src/lib/index.ts'),
  2079. `export { default as Foo } from './RealButton.svelte';\n`
  2080. );
  2081. fs.writeFileSync(
  2082. path.join(tempDir, 'src/Bar.svelte'),
  2083. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  2084. );
  2085. cg = await CodeGraph.init(tempDir, { index: true });
  2086. cg.resolveReferences();
  2087. const fooNode = cg
  2088. .getNodesByKind('component')
  2089. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  2090. expect(fooNode).toBeDefined();
  2091. const callers = cg.getCallers(fooNode!.id);
  2092. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  2093. });
  2094. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  2095. // The canonical Astro shape: a page imports a layout/component in
  2096. // frontmatter and uses it as a template tag; the component's template
  2097. // calls an imported .ts util. Both hops must produce graph edges or
  2098. // an Astro project is invisible to callers/impact.
  2099. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  2100. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  2101. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  2102. fs.writeFileSync(
  2103. path.join(tempDir, 'src/utils/format.ts'),
  2104. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  2105. );
  2106. fs.writeFileSync(
  2107. path.join(tempDir, 'src/components/PostCard.astro'),
  2108. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  2109. );
  2110. fs.writeFileSync(
  2111. path.join(tempDir, 'src/pages/index.astro'),
  2112. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  2113. );
  2114. cg = await CodeGraph.init(tempDir, { index: true });
  2115. cg.resolveReferences();
  2116. // Hop 1: page → component (template tag through the frontmatter import)
  2117. const cardNode = cg
  2118. .getNodesByKind('component')
  2119. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  2120. expect(cardNode).toBeDefined();
  2121. const cardCallers = cg.getCallers(cardNode!.id);
  2122. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  2123. // Hop 2: component template call → .ts util
  2124. const fmtNode = cg
  2125. .getNodesByKind('function')
  2126. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  2127. expect(fmtNode).toBeDefined();
  2128. const fmtCallers = cg.getCallers(fmtNode!.id);
  2129. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  2130. });
  2131. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  2132. // `import { helper } from '.'` (or './') must map to the
  2133. // directory's index.ts before the re-export chase can run. The
  2134. // barrel renames `realHelper` → `helper` so the name-matcher can't
  2135. // mask a path-resolution failure: only the bare-dir resolution +
  2136. // rename chase can connect the edge.
  2137. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2138. fs.writeFileSync(
  2139. path.join(tempDir, 'src/util.ts'),
  2140. `export function realHelper(): void {}\n`
  2141. );
  2142. fs.writeFileSync(
  2143. path.join(tempDir, 'src/index.ts'),
  2144. `export { realHelper as helper } from './util';\n`
  2145. );
  2146. fs.writeFileSync(
  2147. path.join(tempDir, 'src/main.ts'),
  2148. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  2149. );
  2150. fs.writeFileSync(
  2151. path.join(tempDir, 'src/main2.ts'),
  2152. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  2153. );
  2154. cg = await CodeGraph.init(tempDir, { index: true });
  2155. cg.resolveReferences();
  2156. const helperNode = cg
  2157. .getNodesByKind('function')
  2158. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  2159. expect(helperNode).toBeDefined();
  2160. const callers = cg.getCallers(helperNode!.id);
  2161. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2162. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  2163. });
  2164. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  2165. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  2166. // `widgets/` subdir index, which re-exports a .svelte component.
  2167. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  2168. // only workspace-package resolution can connect the edge.
  2169. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  2170. fs.writeFileSync(
  2171. path.join(tempDir, 'package.json'),
  2172. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  2173. );
  2174. fs.writeFileSync(
  2175. path.join(tempDir, 'packages/ui/package.json'),
  2176. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  2177. );
  2178. fs.writeFileSync(
  2179. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  2180. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2181. );
  2182. fs.writeFileSync(
  2183. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  2184. `export { default as Thing } from './Widget.svelte';\n`
  2185. );
  2186. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  2187. fs.writeFileSync(
  2188. path.join(tempDir, 'app/App.svelte'),
  2189. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  2190. );
  2191. cg = await CodeGraph.init(tempDir, { index: true });
  2192. cg.resolveReferences();
  2193. const buttonNode = cg
  2194. .getNodesByKind('component')
  2195. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  2196. expect(buttonNode).toBeDefined();
  2197. const callers = cg.getCallers(buttonNode!.id);
  2198. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  2199. });
  2200. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  2201. // The same import-resolution gaps (no SFC import mappings, no SFC
  2202. // extension list, barrel parsed in the consumer's language) broke
  2203. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  2204. // The barrel renames `realRun` → `run` so only the import-chase (not
  2205. // the name-matcher) can connect the call.
  2206. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2207. fs.writeFileSync(
  2208. path.join(tempDir, 'src/util.ts'),
  2209. `export function realRun(): void {}\n`
  2210. );
  2211. fs.writeFileSync(
  2212. path.join(tempDir, 'src/index.ts'),
  2213. `export { realRun as run } from './util';\n`
  2214. );
  2215. fs.writeFileSync(
  2216. path.join(tempDir, 'src/App.vue'),
  2217. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  2218. );
  2219. cg = await CodeGraph.init(tempDir, { index: true });
  2220. cg.resolveReferences();
  2221. const runNode = cg
  2222. .getNodesByKind('function')
  2223. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  2224. expect(runNode).toBeDefined();
  2225. const callers = cg.getCallers(runNode!.id);
  2226. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2227. });
  2228. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  2229. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  2230. // component re-exported under an alias (`Thing`) that differs from its
  2231. // real name (`Widget`), and the consumer uses it ONLY in markup
  2232. // (`<Thing />`). Requires both the new template-tag extraction AND the
  2233. // barrel default-export chase to connect the edge.
  2234. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2235. fs.writeFileSync(
  2236. path.join(tempDir, 'src/lib/Widget.vue'),
  2237. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  2238. );
  2239. fs.writeFileSync(
  2240. path.join(tempDir, 'src/lib/index.ts'),
  2241. `export { default as Thing } from './Widget.vue';\n`
  2242. );
  2243. fs.writeFileSync(
  2244. path.join(tempDir, 'src/App.vue'),
  2245. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  2246. );
  2247. cg = await CodeGraph.init(tempDir, { index: true });
  2248. cg.resolveReferences();
  2249. const widgetNode = cg
  2250. .getNodesByKind('component')
  2251. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  2252. expect(widgetNode).toBeDefined();
  2253. const callers = cg.getCallers(widgetNode!.id);
  2254. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2255. });
  2256. });
  2257. describe('C/C++ Import Resolution', () => {
  2258. afterEach(() => {
  2259. clearCppIncludeDirCache();
  2260. });
  2261. it('should resolve C include to header in same directory', () => {
  2262. const context: ResolutionContext = {
  2263. getNodesInFile: () => [],
  2264. getNodesByName: () => [],
  2265. getNodesByQualifiedName: () => [],
  2266. getNodesByKind: () => [],
  2267. fileExists: (p) => p === 'utils.h',
  2268. readFile: () => null,
  2269. getProjectRoot: () => '',
  2270. getAllFiles: () => ['utils.h', 'main.c'],
  2271. };
  2272. const result = resolveImportPath(
  2273. 'utils.h',
  2274. 'main.c',
  2275. 'c',
  2276. context
  2277. );
  2278. expect(result).toBe('utils.h');
  2279. });
  2280. it('should resolve C++ include with .hpp extension', () => {
  2281. const context: ResolutionContext = {
  2282. getNodesInFile: () => [],
  2283. getNodesByName: () => [],
  2284. getNodesByQualifiedName: () => [],
  2285. getNodesByKind: () => [],
  2286. fileExists: (p) => p === 'include/myclass.hpp',
  2287. readFile: () => null,
  2288. getProjectRoot: () => '',
  2289. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2290. getCppIncludeDirs: () => ['include'],
  2291. };
  2292. const result = resolveImportPath(
  2293. 'myclass.hpp',
  2294. 'src/main.cpp',
  2295. 'cpp',
  2296. context
  2297. );
  2298. expect(result).toBe('include/myclass.hpp');
  2299. });
  2300. it('should resolve include with subdirectory path', () => {
  2301. const context: ResolutionContext = {
  2302. getNodesInFile: () => [],
  2303. getNodesByName: () => [],
  2304. getNodesByQualifiedName: () => [],
  2305. getNodesByKind: () => [],
  2306. fileExists: (p) => p === 'utils/helpers.h',
  2307. readFile: () => null,
  2308. getProjectRoot: () => '',
  2309. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  2310. };
  2311. const result = resolveImportPath(
  2312. 'utils/helpers.h',
  2313. 'main.c',
  2314. 'c',
  2315. context
  2316. );
  2317. expect(result).toBe('utils/helpers.h');
  2318. });
  2319. it('should resolve include via include directories', () => {
  2320. const context: ResolutionContext = {
  2321. getNodesInFile: () => [],
  2322. getNodesByName: () => [],
  2323. getNodesByQualifiedName: () => [],
  2324. getNodesByKind: () => [],
  2325. fileExists: (p) => p === 'include/myheader.h',
  2326. readFile: () => null,
  2327. getProjectRoot: () => '',
  2328. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  2329. getCppIncludeDirs: () => ['include'],
  2330. };
  2331. const result = resolveImportPath(
  2332. 'myheader.h',
  2333. 'src/main.cpp',
  2334. 'cpp',
  2335. context
  2336. );
  2337. expect(result).toBe('include/myheader.h');
  2338. });
  2339. it('should resolve include trying multiple extensions', () => {
  2340. const context: ResolutionContext = {
  2341. getNodesInFile: () => [],
  2342. getNodesByName: () => [],
  2343. getNodesByQualifiedName: () => [],
  2344. getNodesByKind: () => [],
  2345. // myclass.h does not exist, but myclass.hpp does
  2346. fileExists: (p) => p === 'include/myclass.hpp',
  2347. readFile: () => null,
  2348. getProjectRoot: () => '',
  2349. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2350. getCppIncludeDirs: () => ['include'],
  2351. };
  2352. const result = resolveImportPath(
  2353. 'myclass',
  2354. 'src/main.cpp',
  2355. 'cpp',
  2356. context
  2357. );
  2358. expect(result).toBe('include/myclass.hpp');
  2359. });
  2360. it('should return null for system headers', () => {
  2361. const context: ResolutionContext = {
  2362. getNodesInFile: () => [],
  2363. getNodesByName: () => [],
  2364. getNodesByQualifiedName: () => [],
  2365. getNodesByKind: () => [],
  2366. fileExists: () => true,
  2367. readFile: () => null,
  2368. getProjectRoot: () => '',
  2369. getAllFiles: () => [],
  2370. };
  2371. // C standard library header
  2372. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  2373. // C++ standard library header
  2374. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  2375. // C++ C-wrapper header
  2376. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  2377. });
  2378. it('should return null for single-component third-party paths that cannot be resolved', () => {
  2379. const context: ResolutionContext = {
  2380. getNodesInFile: () => [],
  2381. getNodesByName: () => [],
  2382. getNodesByQualifiedName: () => [],
  2383. getNodesByKind: () => [],
  2384. fileExists: () => false,
  2385. readFile: () => null,
  2386. getProjectRoot: () => '',
  2387. getAllFiles: () => [],
  2388. getCppIncludeDirs: () => [],
  2389. };
  2390. // Third-party bare header without path — not resolvable, returns null
  2391. const result = resolveImportPath(
  2392. 'openssl/ssl.h',
  2393. 'main.cpp',
  2394. 'cpp',
  2395. context
  2396. );
  2397. expect(result).toBeNull();
  2398. });
  2399. it('should not filter project headers with path separators', () => {
  2400. const context: ResolutionContext = {
  2401. getNodesInFile: () => [],
  2402. getNodesByName: () => [],
  2403. getNodesByQualifiedName: () => [],
  2404. getNodesByKind: () => [],
  2405. fileExists: (p) => p === 'mylib/utils.h',
  2406. readFile: () => null,
  2407. getProjectRoot: () => '',
  2408. getAllFiles: () => ['mylib/utils.h'],
  2409. };
  2410. // Path with separator should NOT be filtered as external
  2411. const result = resolveImportPath(
  2412. 'mylib/utils.h',
  2413. 'main.c',
  2414. 'c',
  2415. context
  2416. );
  2417. expect(result).toBe('mylib/utils.h');
  2418. });
  2419. it('should extract C/C++ import mappings from #include directives', () => {
  2420. const code = `#include <iostream>
  2421. #include "myheader.h"
  2422. #include "utils/helpers.hpp"`;
  2423. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  2424. expect(mappings.length).toBe(3);
  2425. expect(mappings[0]).toEqual({
  2426. localName: 'iostream',
  2427. exportedName: '*',
  2428. source: 'iostream',
  2429. isDefault: false,
  2430. isNamespace: true,
  2431. });
  2432. expect(mappings[1]).toEqual({
  2433. localName: 'myheader',
  2434. exportedName: '*',
  2435. source: 'myheader.h',
  2436. isDefault: false,
  2437. isNamespace: true,
  2438. });
  2439. expect(mappings[2]).toEqual({
  2440. localName: 'helpers',
  2441. exportedName: '*',
  2442. source: 'utils/helpers.hpp',
  2443. isDefault: false,
  2444. isNamespace: true,
  2445. });
  2446. });
  2447. it('should discover include directories from compile_commands.json', () => {
  2448. // Create a temp project with compile_commands.json
  2449. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2450. try {
  2451. const compileDb = [
  2452. {
  2453. directory: tempProject,
  2454. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  2455. file: 'src/main.cpp',
  2456. },
  2457. ];
  2458. fs.writeFileSync(
  2459. path.join(tempProject, 'compile_commands.json'),
  2460. JSON.stringify(compileDb)
  2461. );
  2462. // Create the include dirs so they exist
  2463. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2464. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  2465. clearCppIncludeDirCache();
  2466. const dirs = loadCppIncludeDirs(tempProject);
  2467. // Should find include and src/lib (relative to project root)
  2468. // /usr/include is absolute and outside project, should be excluded
  2469. expect(dirs).toContain('include');
  2470. expect(dirs).toContain('src/lib');
  2471. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  2472. } finally {
  2473. fs.rmSync(tempProject, { recursive: true });
  2474. }
  2475. });
  2476. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  2477. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2478. try {
  2479. // Create include/ and src/ directories with headers
  2480. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2481. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  2482. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2483. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  2484. // Create a directory without headers — should not be included
  2485. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  2486. clearCppIncludeDirCache();
  2487. const dirs = loadCppIncludeDirs(tempProject);
  2488. expect(dirs).toContain('include');
  2489. expect(dirs).toContain('src');
  2490. expect(dirs).not.toContain('docs');
  2491. } finally {
  2492. fs.rmSync(tempProject, { recursive: true });
  2493. }
  2494. });
  2495. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  2496. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  2497. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  2498. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  2499. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  2500. // than missing real resolutions. The test pins this so a later
  2501. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  2502. // trade-off explicitly.
  2503. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  2504. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2505. try {
  2506. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  2507. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  2508. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  2509. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  2510. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  2511. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  2512. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  2513. clearCppIncludeDirCache();
  2514. const dirs = loadCppIncludeDirs(tempProject);
  2515. // Both included — Obj-C dirs are intentionally allowed.
  2516. expect(dirs).toContain('cppmod');
  2517. expect(dirs).toContain('iosmod');
  2518. } finally {
  2519. fs.rmSync(tempProject, { recursive: true });
  2520. }
  2521. });
  2522. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  2523. // in the actual indexing pipeline (not just a phantom file→import-node
  2524. // edge). This pins the include-dir resolution path so the headline PR
  2525. // feature can't silently regress to a no-op in the indexing flow.
  2526. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  2527. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  2528. try {
  2529. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2530. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2531. fs.writeFileSync(
  2532. path.join(tempProject, 'include', 'utils.h'),
  2533. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  2534. );
  2535. fs.writeFileSync(
  2536. path.join(tempProject, 'src', 'main.cpp'),
  2537. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  2538. );
  2539. clearCppIncludeDirCache();
  2540. cg = await CodeGraph.init(tempProject, { index: true });
  2541. // Sanity: file nodes exist for the header and the cpp.
  2542. const allFiles = cg.getStats();
  2543. expect(allFiles.fileCount).toBe(2);
  2544. // The `#include "utils.h"` edge should target the real
  2545. // `include/utils.h` file node — not a floating `import` node
  2546. // living inside main.cpp.
  2547. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2548. const rows = db.getDb().prepare(`
  2549. select dst.kind as dstKind, dst.file_path as dstPath
  2550. from edges e
  2551. join nodes src on e.source = src.id
  2552. join nodes dst on e.target = dst.id
  2553. where e.kind = 'imports'
  2554. and src.kind = 'file'
  2555. and src.file_path = 'src/main.cpp'
  2556. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2557. const resolvedToHeader = rows.find(
  2558. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  2559. );
  2560. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  2561. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  2562. const stdlibFile = rows.find(
  2563. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  2564. );
  2565. expect(stdlibFile).toBeUndefined();
  2566. } finally {
  2567. fs.rmSync(tempProject, { recursive: true, force: true });
  2568. }
  2569. });
  2570. });
  2571. describe('C++ templated base-class inheritance (#1043)', () => {
  2572. // A class deriving from a TEMPLATE — `class D : public Base<int>` (or a CRTP
  2573. // `class W : public CRTPBase<W>`, or a qualified `class Q : public ns::Tpl<int>`)
  2574. // recorded its base as the full instantiation text (`Base<int>`), which never
  2575. // name-matched the template, indexed as the bare node `Base`. The `<…>` args
  2576. // are now stripped so the `extends` edge resolves end-to-end.
  2577. it('resolves an extends edge to a templated base (plain, CRTP, struct, multi-base)', async () => {
  2578. fs.writeFileSync(
  2579. path.join(tempDir, 'lib.hpp'),
  2580. `#pragma once
  2581. template<typename T> class Base { public: void foo(); };
  2582. template<typename Derived> class CRTPBase {};
  2583. class Plain {};
  2584. class Widget : public Base<int> {}; // plain template base
  2585. class App : public CRTPBase<App> {}; // CRTP (curiously-recurring)
  2586. struct Node : public Base<double> {}; // struct inheriting a template
  2587. class Both : public Base<char>, public Plain {}; // templated + plain in one clause
  2588. `
  2589. );
  2590. cg = await CodeGraph.init(tempDir, { index: true });
  2591. const db = DatabaseConnection.open(path.join(tempDir, '.codegraph', 'codegraph.db'));
  2592. const edges = db
  2593. .getDb()
  2594. .prepare(
  2595. `select src.name as fromName, dst.name as toName
  2596. from edges e
  2597. join nodes src on e.source = src.id
  2598. join nodes dst on e.target = dst.id
  2599. where e.kind = 'extends'`
  2600. )
  2601. .all() as Array<{ fromName: string; toName: string }>;
  2602. const has = (from: string, to: string) =>
  2603. edges.some((r) => r.fromName === from && r.toName === to);
  2604. // Every templated base now resolves to the bare template node.
  2605. expect(has('Widget', 'Base'), 'Widget : Base<int>').toBe(true);
  2606. expect(has('App', 'CRTPBase'), 'App : CRTPBase<App> (CRTP)').toBe(true);
  2607. expect(has('Node', 'Base'), 'struct Node : Base<double>').toBe(true);
  2608. // A mixed clause resolves BOTH the templated and the plain base.
  2609. expect(has('Both', 'Base'), 'Both : Base<char>').toBe(true);
  2610. expect(has('Both', 'Plain'), 'Both : Plain (non-templated, regression guard)').toBe(true);
  2611. });
  2612. });
  2613. describe('PHP Include Resolution', () => {
  2614. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  2615. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  2616. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  2617. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  2618. });
  2619. // include paths: contain a slash or a file extension
  2620. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  2621. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  2622. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  2623. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  2624. // so they must NOT be treated as includes (would mis-connect to a
  2625. // same-named Closure.php / Bar.php file).
  2626. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  2627. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  2628. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  2629. // scoped to PHP imports only
  2630. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  2631. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  2632. });
  2633. it('resolves require_once to a file→file imports edge (#660)', async () => {
  2634. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  2635. try {
  2636. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2637. fs.writeFileSync(
  2638. path.join(tempProject, 'src', 'lib.php'),
  2639. `<?php\nfunction greet() { return "hi"; }\n`
  2640. );
  2641. fs.writeFileSync(
  2642. path.join(tempProject, 'src', 'page.php'),
  2643. `<?php\nrequire_once("lib.php");\necho greet();\n`
  2644. );
  2645. cg = await CodeGraph.init(tempProject, { index: true });
  2646. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  2647. // to the real src/lib.php file node — a file→file `imports` edge, so
  2648. // callers(lib.php) now includes page.php.
  2649. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2650. const rows = db.getDb().prepare(`
  2651. select dst.kind as dstKind, dst.file_path as dstPath
  2652. from edges e
  2653. join nodes src on e.source = src.id
  2654. join nodes dst on e.target = dst.id
  2655. where e.kind = 'imports'
  2656. and src.kind = 'file'
  2657. and src.file_path = 'src/page.php'
  2658. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2659. const resolved = rows.find(
  2660. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  2661. );
  2662. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  2663. } finally {
  2664. fs.rmSync(tempProject, { recursive: true, force: true });
  2665. }
  2666. });
  2667. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  2668. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  2669. try {
  2670. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  2671. fs.writeFileSync(
  2672. path.join(tempProject, 'inc', 'db.php'),
  2673. `<?php\nfunction query() { return 1; }\n`
  2674. );
  2675. fs.writeFileSync(
  2676. path.join(tempProject, 'index.php'),
  2677. `<?php\nrequire "inc/db.php";\nquery();\n`
  2678. );
  2679. cg = await CodeGraph.init(tempProject, { index: true });
  2680. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2681. const rows = db.getDb().prepare(`
  2682. select dst.kind as dstKind, dst.file_path as dstPath
  2683. from edges e
  2684. join nodes src on e.source = src.id
  2685. join nodes dst on e.target = dst.id
  2686. where e.kind = 'imports'
  2687. and src.kind = 'file'
  2688. and src.file_path = 'index.php'
  2689. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2690. expect(
  2691. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  2692. 'index.php → inc/db.php imports edge missing'
  2693. ).toBeDefined();
  2694. } finally {
  2695. fs.rmSync(tempProject, { recursive: true, force: true });
  2696. }
  2697. });
  2698. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  2699. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  2700. try {
  2701. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  2702. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  2703. // but is unrelated — no edge should be created (a wrong edge is worse
  2704. // than a missing one).
  2705. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  2706. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  2707. fs.writeFileSync(
  2708. path.join(tempProject, 'lib', 'inc', 'db.php'),
  2709. `<?php\nfunction unrelated() {}\n`
  2710. );
  2711. fs.writeFileSync(
  2712. path.join(tempProject, 'app', 'page.php'),
  2713. `<?php\nrequire "inc/db.php";\n`
  2714. );
  2715. cg = await CodeGraph.init(tempProject, { index: true });
  2716. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2717. const rows = db.getDb().prepare(`
  2718. select dst.kind as dstKind, dst.file_path as dstPath
  2719. from edges e
  2720. join nodes src on e.source = src.id
  2721. join nodes dst on e.target = dst.id
  2722. where e.kind = 'imports'
  2723. and src.kind = 'file'
  2724. and src.file_path = 'app/page.php'
  2725. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2726. expect(
  2727. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  2728. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  2729. ).toBeUndefined();
  2730. } finally {
  2731. fs.rmSync(tempProject, { recursive: true, force: true });
  2732. }
  2733. });
  2734. });
  2735. describe('C++ chained-call receiver resolution (#645)', () => {
  2736. async function indexCpp(files: Record<string, string>): Promise<void> {
  2737. for (const [name, content] of Object.entries(files)) {
  2738. fs.writeFileSync(path.join(tempDir, name), content);
  2739. }
  2740. cg = await CodeGraph.init(tempDir, { index: true });
  2741. }
  2742. function callerNamesOf(qualifiedName: string): string[] {
  2743. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2744. if (!target) return [];
  2745. const names = cg
  2746. .getIncomingEdges(target.id)
  2747. .filter((e) => e.kind === 'calls')
  2748. .map((e) => cg.getNode(e.source)?.name)
  2749. .filter((n): n is string => !!n);
  2750. return [...new Set(names)].sort();
  2751. }
  2752. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  2753. // Two classes share writeLog; Logger sorts first so it wins any name-only
  2754. // tie. All three call forms target Metrics.
  2755. await indexCpp({
  2756. 'logger.hpp': `#pragma once
  2757. #include <string>
  2758. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  2759. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  2760. `,
  2761. 'impl.cpp': `#include "logger.hpp"
  2762. Logger& Logger::instance() { static Logger l; return l; }
  2763. Metrics& Metrics::instance() { static Metrics m; return m; }
  2764. void Logger::writeLog(const std::string&) {}
  2765. void Metrics::writeLog(const std::string&) {}
  2766. `,
  2767. 'app.cpp': `#include "logger.hpp"
  2768. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  2769. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  2770. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  2771. `,
  2772. });
  2773. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  2774. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  2775. });
  2776. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  2777. await indexCpp({
  2778. 'types.hpp': `#pragma once
  2779. #include <memory>
  2780. struct Widget { void draw(); };
  2781. struct Session { void run(); };
  2782. struct View { void render(); };
  2783. class WidgetFactory { public: static Widget create(); };
  2784. class Manager { public: View view(); };
  2785. Session* openSession();
  2786. // Decoy that sorts first and has all three methods — must never win.
  2787. struct Aaa { void draw(); void run(); void render(); };
  2788. `,
  2789. 'impl.cpp': `#include "types.hpp"
  2790. void Widget::draw() {}
  2791. void Session::run() {}
  2792. void View::render() {}
  2793. void Aaa::draw() {}
  2794. void Aaa::run() {}
  2795. void Aaa::render() {}
  2796. Widget WidgetFactory::create() { return Widget(); }
  2797. View Manager::view() { return View(); }
  2798. Session* openSession() { return nullptr; }
  2799. `,
  2800. 'app.cpp': `#include "types.hpp"
  2801. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  2802. void freefunc() { openSession()->run(); } // -> Session::run
  2803. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  2804. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  2805. `,
  2806. });
  2807. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  2808. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  2809. expect(callerNamesOf('View::render')).toEqual(['member']);
  2810. // The first-sorted decoy never captures any of them.
  2811. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2812. expect(callerNamesOf('Aaa::run')).toEqual([]);
  2813. expect(callerNamesOf('Aaa::render')).toEqual([]);
  2814. });
  2815. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  2816. await indexCpp({
  2817. 'types.hpp': `#pragma once
  2818. struct Widget { void draw(); };
  2819. struct Other { void onlyOther(); };
  2820. class WidgetFactory { public: static Widget create(); };
  2821. `,
  2822. 'impl.cpp': `#include "types.hpp"
  2823. void Widget::draw() {}
  2824. void Other::onlyOther() {}
  2825. Widget WidgetFactory::create() { return Widget(); }
  2826. `,
  2827. 'app.cpp': `#include "types.hpp"
  2828. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  2829. void wrong() { WidgetFactory::create().onlyOther(); }
  2830. `,
  2831. });
  2832. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2833. });
  2834. });
  2835. describe('PHP chained static-factory call resolution (#608)', () => {
  2836. function callerNamesOf(qualifiedName: string): string[] {
  2837. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2838. if (!target) return [];
  2839. const names = cg
  2840. .getIncomingEdges(target.id)
  2841. .filter((e) => e.kind === 'calls')
  2842. .map((e) => cg.getNode(e.source)?.name)
  2843. .filter((n): n is string => !!n);
  2844. return [...new Set(names)].sort();
  2845. }
  2846. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  2847. fs.writeFileSync(
  2848. path.join(tempDir, 'ApiClient.php'),
  2849. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  2850. );
  2851. fs.writeFileSync(
  2852. path.join(tempDir, 'DispatchOrder.php'),
  2853. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  2854. );
  2855. cg = await CodeGraph.init(tempDir, { index: true });
  2856. // The chained call's edge attaches to the factory result's method.
  2857. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  2858. });
  2859. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  2860. fs.writeFileSync(
  2861. path.join(tempDir, 'lib.php'),
  2862. `<?php\nclass ApiClient { public static function for(string $c): self { return new self; } }\nclass Other { public function onlyOther(): void {} }\nclass Caller { public function go(): void { ApiClient::for('x')->onlyOther(); } }\n`
  2863. );
  2864. cg = await CodeGraph.init(tempDir, { index: true });
  2865. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  2866. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2867. });
  2868. });
  2869. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  2870. function callerNamesOf(qualifiedName: string): string[] {
  2871. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2872. if (!target) return [];
  2873. const names = cg
  2874. .getIncomingEdges(target.id)
  2875. .filter((e) => e.kind === 'calls')
  2876. .map((e) => cg.getNode(e.source)?.name)
  2877. .filter((n): n is string => !!n);
  2878. return [...new Set(names)].sort();
  2879. }
  2880. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  2881. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  2882. fs.writeFileSync(
  2883. path.join(tempDir, 'Main.java'),
  2884. `class Aaa { void bar() {} }
  2885. class Foo {
  2886. static Foo getInstance() { return new Foo(); }
  2887. void bar() {}
  2888. }
  2889. class Caller {
  2890. void run() { Foo.getInstance().bar(); }
  2891. }
  2892. `
  2893. );
  2894. cg = await CodeGraph.init(tempDir, { index: true });
  2895. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2896. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2897. });
  2898. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2899. // The factory call carries an argument; the extractor must normalize the
  2900. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  2901. fs.writeFileSync(
  2902. path.join(tempDir, 'Main.java'),
  2903. `class Config {}
  2904. class Foo {
  2905. static Foo create(Config c) { return new Foo(); }
  2906. void build() {}
  2907. }
  2908. class Caller {
  2909. void run() { Foo.create(new Config()).build(); }
  2910. }
  2911. `
  2912. );
  2913. cg = await CodeGraph.init(tempDir, { index: true });
  2914. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2915. });
  2916. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2917. fs.writeFileSync(
  2918. path.join(tempDir, 'Main.java'),
  2919. `class Foo {
  2920. static Foo getInstance() { return new Foo(); }
  2921. }
  2922. class Other { void onlyOther() {} }
  2923. class Caller {
  2924. void run() { Foo.getInstance().onlyOther(); }
  2925. }
  2926. `
  2927. );
  2928. cg = await CodeGraph.init(tempDir, { index: true });
  2929. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2930. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2931. });
  2932. });
  2933. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  2934. function callerNamesOf(qualifiedName: string): string[] {
  2935. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2936. if (!target) return [];
  2937. const names = cg
  2938. .getIncomingEdges(target.id)
  2939. .filter((e) => e.kind === 'calls')
  2940. .map((e) => cg.getNode(e.source)?.name)
  2941. .filter((n): n is string => !!n);
  2942. return [...new Set(names)].sort();
  2943. }
  2944. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  2945. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  2946. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  2947. fs.writeFileSync(
  2948. path.join(tempDir, 'Main.kt'),
  2949. `class Aaa { fun bar() {} }
  2950. class Foo {
  2951. companion object {
  2952. fun getInstance(): Foo = Foo()
  2953. }
  2954. fun bar() {}
  2955. }
  2956. class Caller {
  2957. fun run() { Foo.getInstance().bar() }
  2958. }
  2959. `
  2960. );
  2961. cg = await CodeGraph.init(tempDir, { index: true });
  2962. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2963. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2964. });
  2965. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2966. fs.writeFileSync(
  2967. path.join(tempDir, 'Main.kt'),
  2968. `class Config
  2969. class Foo {
  2970. companion object {
  2971. fun create(c: Config): Foo = Foo()
  2972. }
  2973. fun build() {}
  2974. }
  2975. class Caller {
  2976. fun run() { Foo.create(Config()).build() }
  2977. }
  2978. `
  2979. );
  2980. cg = await CodeGraph.init(tempDir, { index: true });
  2981. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2982. });
  2983. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  2984. fs.writeFileSync(
  2985. path.join(tempDir, 'Main.kt'),
  2986. `class Foo {
  2987. companion object {
  2988. fun getInstance(): Foo = Foo()
  2989. }
  2990. }
  2991. class Other { fun onlyOther() {} }
  2992. class Caller {
  2993. fun run() { Foo.getInstance().onlyOther() }
  2994. }
  2995. `
  2996. );
  2997. cg = await CodeGraph.init(tempDir, { index: true });
  2998. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2999. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3000. });
  3001. });
  3002. describe('C# chained static-factory call resolution (#645/#608 mechanism)', () => {
  3003. function callerNamesOf(qualifiedName: string): string[] {
  3004. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3005. if (!target) return [];
  3006. const names = cg
  3007. .getIncomingEdges(target.id)
  3008. .filter((e) => e.kind === 'calls')
  3009. .map((e) => cg.getNode(e.source)?.name)
  3010. .filter((n): n is string => !!n);
  3011. return [...new Set(names)].sort();
  3012. }
  3013. it('resolves Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  3014. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  3015. fs.writeFileSync(
  3016. path.join(tempDir, 'Main.cs'),
  3017. `class Aaa { void Bar() {} }
  3018. class Foo {
  3019. static Foo Create() { return new Foo(); }
  3020. void Bar() {}
  3021. }
  3022. class Caller {
  3023. void Run() { Foo.Create().Bar(); }
  3024. }
  3025. `
  3026. );
  3027. cg = await CodeGraph.init(tempDir, { index: true });
  3028. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  3029. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  3030. });
  3031. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  3032. fs.writeFileSync(
  3033. path.join(tempDir, 'Main.cs'),
  3034. `class Config {}
  3035. class Foo {
  3036. static Foo Make(Config c) { return new Foo(); }
  3037. void Build() {}
  3038. }
  3039. class Caller {
  3040. void Run() { Foo.Make(new Config()).Build(); }
  3041. }
  3042. `
  3043. );
  3044. cg = await CodeGraph.init(tempDir, { index: true });
  3045. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  3046. });
  3047. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3048. fs.writeFileSync(
  3049. path.join(tempDir, 'Main.cs'),
  3050. `class Foo {
  3051. static Foo Create() { return new Foo(); }
  3052. }
  3053. class Other { void OnlyOther() {} }
  3054. class Caller {
  3055. void Run() { Foo.Create().OnlyOther(); }
  3056. }
  3057. `
  3058. );
  3059. cg = await CodeGraph.init(tempDir, { index: true });
  3060. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3061. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3062. });
  3063. });
  3064. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  3065. function callerNamesOf(qualifiedName: string): string[] {
  3066. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3067. if (!target) return [];
  3068. const names = cg
  3069. .getIncomingEdges(target.id)
  3070. .filter((e) => e.kind === 'calls')
  3071. .map((e) => cg.getNode(e.source)?.name)
  3072. .filter((n): n is string => !!n);
  3073. return [...new Set(names)].sort();
  3074. }
  3075. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  3076. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  3077. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  3078. fs.writeFileSync(
  3079. path.join(tempDir, 'Main.swift'),
  3080. `class Aaa { func draw() {} }
  3081. class Foo {
  3082. static func make() -> Foo { return Foo() }
  3083. func draw() {}
  3084. }
  3085. func runCaller() { Foo.make().draw() }
  3086. `
  3087. );
  3088. cg = await CodeGraph.init(tempDir, { index: true });
  3089. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  3090. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  3091. });
  3092. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  3093. fs.writeFileSync(
  3094. path.join(tempDir, 'Main.swift'),
  3095. `class Config {}
  3096. class Foo {
  3097. static func build(_ c: Config) -> Foo { return Foo() }
  3098. func draw() {}
  3099. func render() {}
  3100. }
  3101. func runCaller() {
  3102. Foo().draw()
  3103. Foo.build(Config()).render()
  3104. }
  3105. `
  3106. );
  3107. cg = await CodeGraph.init(tempDir, { index: true });
  3108. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  3109. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  3110. });
  3111. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3112. fs.writeFileSync(
  3113. path.join(tempDir, 'Main.swift'),
  3114. `class Foo {
  3115. static func make() -> Foo { return Foo() }
  3116. }
  3117. class Other { func onlyOther() {} }
  3118. func runCaller() { Foo.make().onlyOther() }
  3119. `
  3120. );
  3121. cg = await CodeGraph.init(tempDir, { index: true });
  3122. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3123. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3124. });
  3125. });
  3126. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  3127. function callerNamesOf(qualifiedName: string): string[] {
  3128. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3129. if (!target) return [];
  3130. const names = cg
  3131. .getIncomingEdges(target.id)
  3132. .filter((e) => e.kind === 'calls')
  3133. .map((e) => cg.getNode(e.source)?.name)
  3134. .filter((n): n is string => !!n);
  3135. return [...new Set(names)].sort();
  3136. }
  3137. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  3138. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  3139. // its own. Decoy.draw must never win. Needs the conformance second pass.
  3140. fs.writeFileSync(
  3141. path.join(tempDir, 'Main.java'),
  3142. `class Base { void draw() {} }
  3143. class Widget extends Base {}
  3144. class Decoy { void draw() {} }
  3145. class Factory { static Widget create() { return new Widget(); } }
  3146. class Caller {
  3147. void run() { Factory.create().draw(); }
  3148. }
  3149. `
  3150. );
  3151. cg = await CodeGraph.init(tempDir, { index: true });
  3152. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  3153. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3154. });
  3155. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  3156. fs.writeFileSync(
  3157. path.join(tempDir, 'Main.java'),
  3158. `interface Drawable { default void draw() {} }
  3159. class Widget implements Drawable {}
  3160. class Decoy { void draw() {} }
  3161. class Factory { static Widget create() { return new Widget(); } }
  3162. class Caller {
  3163. void run() { Factory.create().draw(); }
  3164. }
  3165. `
  3166. );
  3167. cg = await CodeGraph.init(tempDir, { index: true });
  3168. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  3169. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3170. });
  3171. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  3172. fs.writeFileSync(
  3173. path.join(tempDir, 'Main.java'),
  3174. `class Base {}
  3175. class Widget extends Base {}
  3176. class Other { void onlyOther() {} }
  3177. class Factory { static Widget create() { return new Widget(); } }
  3178. class Caller {
  3179. void run() { Factory.create().onlyOther(); }
  3180. }
  3181. `
  3182. );
  3183. cg = await CodeGraph.init(tempDir, { index: true });
  3184. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  3185. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3186. });
  3187. });
  3188. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  3189. function callerNamesOf(qualifiedName: string): string[] {
  3190. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3191. if (!target) return [];
  3192. const names = cg
  3193. .getIncomingEdges(target.id)
  3194. .filter((e) => e.kind === 'calls')
  3195. .map((e) => cg.getNode(e.source)?.name)
  3196. .filter((n): n is string => !!n);
  3197. return [...new Set(names)].sort();
  3198. }
  3199. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  3200. fs.writeFileSync(
  3201. path.join(tempDir, 'main.rs'),
  3202. `struct Aaa { _x: i32 }
  3203. impl Aaa { fn bar(&self) {} }
  3204. struct Foo { _x: i32 }
  3205. impl Foo {
  3206. fn new() -> Foo { Foo { _x: 0 } }
  3207. fn make() -> Self { Foo { _x: 0 } }
  3208. fn bar(&self) {}
  3209. }
  3210. fn caller() {
  3211. Foo::new().bar();
  3212. Foo::make().bar();
  3213. }
  3214. `
  3215. );
  3216. cg = await CodeGraph.init(tempDir, { index: true });
  3217. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  3218. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  3219. });
  3220. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  3221. fs.writeFileSync(
  3222. path.join(tempDir, 'main.rs'),
  3223. `struct Config;
  3224. struct Foo { _x: i32 }
  3225. impl Foo {
  3226. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  3227. fn build(&self) {}
  3228. }
  3229. fn caller() { Foo::with(Config).build(); }
  3230. `
  3231. );
  3232. cg = await CodeGraph.init(tempDir, { index: true });
  3233. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  3234. });
  3235. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  3236. fs.writeFileSync(
  3237. path.join(tempDir, 'main.rs'),
  3238. `struct Foo { _x: i32 }
  3239. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3240. struct Decoy { _x: i32 }
  3241. impl Decoy { fn draw(&self) {} }
  3242. trait Drawable { fn draw(&self) {} }
  3243. impl Drawable for Foo {}
  3244. fn caller() { Foo::new().draw(); }
  3245. `
  3246. );
  3247. cg = await CodeGraph.init(tempDir, { index: true });
  3248. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  3249. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3250. });
  3251. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  3252. fs.writeFileSync(
  3253. path.join(tempDir, 'main.rs'),
  3254. `struct Foo { _x: i32 }
  3255. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3256. struct Other { _x: i32 }
  3257. impl Other { fn only_other(&self) {} }
  3258. fn caller() { Foo::new().only_other(); }
  3259. `
  3260. );
  3261. cg = await CodeGraph.init(tempDir, { index: true });
  3262. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  3263. expect(callerNamesOf('Other::only_other')).toEqual([]);
  3264. });
  3265. });
  3266. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  3267. function callerNamesOf(qualifiedName: string): string[] {
  3268. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3269. if (!target) return [];
  3270. const names = cg
  3271. .getIncomingEdges(target.id)
  3272. .filter((e) => e.kind === 'calls')
  3273. .map((e) => cg.getNode(e.source)?.name)
  3274. .filter((n): n is string => !!n);
  3275. return [...new Set(names)].sort();
  3276. }
  3277. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  3278. fs.writeFileSync(
  3279. path.join(tempDir, 'main.go'),
  3280. `package main
  3281. type Aaa struct{}
  3282. func (a *Aaa) Bar() {}
  3283. type Foo struct{}
  3284. func New() *Foo { return &Foo{} }
  3285. func (f *Foo) Bar() {}
  3286. func caller() { New().Bar() }
  3287. `
  3288. );
  3289. cg = await CodeGraph.init(tempDir, { index: true });
  3290. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  3291. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  3292. });
  3293. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  3294. fs.writeFileSync(
  3295. path.join(tempDir, 'main.go'),
  3296. `package main
  3297. type Config struct{}
  3298. type Foo struct{}
  3299. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  3300. func (f *Foo) Build() {}
  3301. func caller() { With(Config{}).Build() }
  3302. `
  3303. );
  3304. cg = await CodeGraph.init(tempDir, { index: true });
  3305. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  3306. });
  3307. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  3308. fs.writeFileSync(
  3309. path.join(tempDir, 'main.go'),
  3310. `package main
  3311. type Base struct{}
  3312. func (b *Base) Embedded() {}
  3313. type Decoy struct{}
  3314. func (d *Decoy) Embedded() {}
  3315. type Widget struct{ Base }
  3316. func NewWidget() *Widget { return &Widget{} }
  3317. func caller() { NewWidget().Embedded() }
  3318. `
  3319. );
  3320. cg = await CodeGraph.init(tempDir, { index: true });
  3321. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  3322. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  3323. });
  3324. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  3325. fs.writeFileSync(
  3326. path.join(tempDir, 'main.go'),
  3327. `package main
  3328. type Foo struct{}
  3329. func New() *Foo { return &Foo{} }
  3330. type Other struct{}
  3331. func (o *Other) OnlyOther() {}
  3332. func caller() { New().OnlyOther() }
  3333. `
  3334. );
  3335. cg = await CodeGraph.init(tempDir, { index: true });
  3336. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3337. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3338. });
  3339. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  3340. // `engine` is a package-level VARIABLE holding a func value, not a factory
  3341. // FUNCTION — so its return type can't be recovered and the chain falls back
  3342. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  3343. // Regression for the runaway this fallback originally caused: it resolved
  3344. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  3345. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  3346. // no-oped, the offset-0 batch never drained, and edges inserted forever
  3347. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  3348. // the original ref, and a non-progress guard backstops the loop.
  3349. fs.writeFileSync(
  3350. path.join(tempDir, 'main.go'),
  3351. `package main
  3352. type Server struct{}
  3353. func (s *Server) ServeHTTP() {}
  3354. var engine = func() *Server { return &Server{} }
  3355. func caller() { engine().ServeHTTP() }
  3356. `
  3357. );
  3358. cg = await CodeGraph.init(tempDir, { index: true });
  3359. // Recall: the variable-inner chain still finds the method by bare name.
  3360. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  3361. // No runaway: a single call site yields a single edge, not millions.
  3362. const target = cg
  3363. .getNodesByKind('method')
  3364. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  3365. const rawCalls = cg
  3366. .getIncomingEdges(target.id)
  3367. .filter((e) => e.kind === 'calls');
  3368. expect(rawCalls.length).toBeLessThan(5);
  3369. });
  3370. });
  3371. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  3372. function callerNamesOf(qualifiedName: string): string[] {
  3373. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3374. if (!target) return [];
  3375. const names = cg
  3376. .getIncomingEdges(target.id)
  3377. .filter((e) => e.kind === 'calls')
  3378. .map((e) => cg.getNode(e.source)?.name)
  3379. .filter((n): n is string => !!n);
  3380. return [...new Set(names)].sort();
  3381. }
  3382. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  3383. fs.writeFileSync(
  3384. path.join(tempDir, 'Main.scala'),
  3385. `object Foo {
  3386. def create(): Bar = new Bar()
  3387. }
  3388. class Bar {
  3389. def doIt(): Unit = {}
  3390. }
  3391. class Decoy {
  3392. def doIt(): Unit = {}
  3393. }
  3394. object Main {
  3395. def run(): Unit = { Foo.create().doIt() }
  3396. }
  3397. `
  3398. );
  3399. cg = await CodeGraph.init(tempDir, { index: true });
  3400. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3401. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3402. });
  3403. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  3404. fs.writeFileSync(
  3405. path.join(tempDir, 'Main.scala'),
  3406. `class Point(x: Int) {
  3407. def dist(): Int = x
  3408. }
  3409. class Other {
  3410. def dist(): Int = 0
  3411. }
  3412. object Main {
  3413. def run(): Unit = { Point(3).dist() }
  3414. }
  3415. `
  3416. );
  3417. cg = await CodeGraph.init(tempDir, { index: true });
  3418. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  3419. expect(callerNamesOf('Other::dist')).toEqual([]);
  3420. });
  3421. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  3422. fs.writeFileSync(
  3423. path.join(tempDir, 'Main.scala'),
  3424. `trait Base {
  3425. def shared(): Unit = {}
  3426. }
  3427. class Widget extends Base
  3428. class Decoy {
  3429. def shared(): Unit = {}
  3430. }
  3431. object Factory {
  3432. def make(): Widget = new Widget()
  3433. }
  3434. object Main {
  3435. def run(): Unit = { Factory.make().shared() }
  3436. }
  3437. `
  3438. );
  3439. cg = await CodeGraph.init(tempDir, { index: true });
  3440. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  3441. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  3442. });
  3443. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3444. fs.writeFileSync(
  3445. path.join(tempDir, 'Main.scala'),
  3446. `object Foo {
  3447. def create(): Bar = new Bar()
  3448. }
  3449. class Bar {
  3450. }
  3451. class Other {
  3452. def onlyOther(): Unit = {}
  3453. }
  3454. object Main {
  3455. def run(): Unit = { Foo.create().onlyOther() }
  3456. }
  3457. `
  3458. );
  3459. cg = await CodeGraph.init(tempDir, { index: true });
  3460. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3461. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3462. });
  3463. });
  3464. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  3465. function callerNamesOf(qualifiedName: string): string[] {
  3466. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3467. if (!target) return [];
  3468. const names = cg
  3469. .getIncomingEdges(target.id)
  3470. .filter((e) => e.kind === 'calls')
  3471. .map((e) => cg.getNode(e.source)?.name)
  3472. .filter((n): n is string => !!n);
  3473. return [...new Set(names)].sort();
  3474. }
  3475. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  3476. fs.writeFileSync(
  3477. path.join(tempDir, 'main.dart'),
  3478. `class Foo {
  3479. static Bar makeBar() => Bar();
  3480. }
  3481. class Bar {
  3482. void doIt() {}
  3483. }
  3484. class Decoy {
  3485. void doIt() {}
  3486. }
  3487. void run() {
  3488. Foo.makeBar().doIt();
  3489. }
  3490. `
  3491. );
  3492. cg = await CodeGraph.init(tempDir, { index: true });
  3493. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3494. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3495. });
  3496. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  3497. fs.writeFileSync(
  3498. path.join(tempDir, 'main.dart'),
  3499. `class Foo {
  3500. Foo._();
  3501. factory Foo.create() => Foo._();
  3502. void ship() {}
  3503. }
  3504. class Decoy {
  3505. void ship() {}
  3506. }
  3507. void run() {
  3508. Foo.create().ship();
  3509. }
  3510. `
  3511. );
  3512. cg = await CodeGraph.init(tempDir, { index: true });
  3513. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  3514. // so `ship` resolves on Foo, not the same-named Decoy.
  3515. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  3516. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  3517. });
  3518. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  3519. fs.writeFileSync(
  3520. path.join(tempDir, 'main.dart'),
  3521. `class Bar {
  3522. void doIt() {}
  3523. }
  3524. class Decoy {
  3525. void doIt() {}
  3526. }
  3527. void run() {
  3528. Bar().doIt();
  3529. }
  3530. `
  3531. );
  3532. cg = await CodeGraph.init(tempDir, { index: true });
  3533. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3534. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3535. });
  3536. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  3537. fs.writeFileSync(
  3538. path.join(tempDir, 'main.dart'),
  3539. `class Base {
  3540. void render() {}
  3541. }
  3542. class Widget extends Base {
  3543. static Widget make() => Widget();
  3544. }
  3545. class Decoy {
  3546. void render() {}
  3547. }
  3548. void run() {
  3549. Widget.make().render();
  3550. }
  3551. `
  3552. );
  3553. cg = await CodeGraph.init(tempDir, { index: true });
  3554. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3555. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3556. });
  3557. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3558. fs.writeFileSync(
  3559. path.join(tempDir, 'main.dart'),
  3560. `class Foo {
  3561. static Bar makeBar() => Bar();
  3562. }
  3563. class Bar {
  3564. }
  3565. class Other {
  3566. void onlyOther() {}
  3567. }
  3568. void run() {
  3569. Foo.makeBar().onlyOther();
  3570. }
  3571. `
  3572. );
  3573. cg = await CodeGraph.init(tempDir, { index: true });
  3574. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3575. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3576. });
  3577. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  3578. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  3579. // swallows the record return type, so `reduce()` looks like a single-
  3580. // identifier constructor_signature. It must NOT be skipped as an unnamed
  3581. // ctor (its name doesn't match the class); its body call must attribute to
  3582. // `reduce`, not the class.
  3583. fs.writeFileSync(
  3584. path.join(tempDir, 'main.dart'),
  3585. `class Base {}
  3586. class Action extends Base {
  3587. Action({required int x});
  3588. @override
  3589. (int, String) reduce() {
  3590. return (compute(), "y");
  3591. }
  3592. int compute() => 1;
  3593. }
  3594. `
  3595. );
  3596. cg = await CodeGraph.init(tempDir, { index: true });
  3597. // reduce must be a node and its body call must resolve to Action::compute.
  3598. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  3599. });
  3600. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  3601. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  3602. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  3603. // never hijacked into a call to a phantom constructor method.
  3604. fs.writeFileSync(
  3605. path.join(tempDir, 'main.dart'),
  3606. `class Widget {
  3607. final int x;
  3608. Widget(this.x);
  3609. }
  3610. void run() {
  3611. Widget(3);
  3612. }
  3613. `
  3614. );
  3615. cg = await CodeGraph.init(tempDir, { index: true });
  3616. // No Foo::Foo phantom method node.
  3617. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  3618. // The construction resolves to the class as an `instantiates` edge.
  3619. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  3620. const incoming = cg.getIncomingEdges(widget.id);
  3621. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  3622. });
  3623. });
  3624. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  3625. function callerNamesOf(qualifiedName: string): string[] {
  3626. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3627. if (!target) return [];
  3628. const names = cg
  3629. .getIncomingEdges(target.id)
  3630. .filter((e) => e.kind === 'calls')
  3631. .map((e) => cg.getNode(e.source)?.name)
  3632. .filter((n): n is string => !!n);
  3633. return [...new Set(names)].sort();
  3634. }
  3635. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  3636. fs.writeFileSync(
  3637. path.join(tempDir, 'main.m'),
  3638. `@interface Bar : NSObject
  3639. - (void)doIt;
  3640. @end
  3641. @implementation Bar
  3642. - (void)doIt {}
  3643. @end
  3644. @interface Decoy : NSObject
  3645. - (void)doIt;
  3646. @end
  3647. @implementation Decoy
  3648. - (void)doIt {}
  3649. @end
  3650. @interface Foo : NSObject
  3651. + (Bar *)create;
  3652. @end
  3653. @implementation Foo
  3654. + (Bar *)create { return nil; }
  3655. - (void)run { [[Foo create] doIt]; }
  3656. @end
  3657. `
  3658. );
  3659. cg = await CodeGraph.init(tempDir, { index: true });
  3660. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3661. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3662. });
  3663. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  3664. fs.writeFileSync(
  3665. path.join(tempDir, 'main.m'),
  3666. `@interface Base : NSObject
  3667. - (void)render;
  3668. @end
  3669. @implementation Base
  3670. - (void)render {}
  3671. @end
  3672. @interface Widget : Base
  3673. @end
  3674. @implementation Widget
  3675. @end
  3676. @interface Decoy : NSObject
  3677. - (void)render;
  3678. @end
  3679. @implementation Decoy
  3680. - (void)render {}
  3681. @end
  3682. @interface Factory : NSObject
  3683. + (Widget *)make;
  3684. @end
  3685. @implementation Factory
  3686. + (Widget *)make { return nil; }
  3687. - (void)run { [[Factory make] render]; }
  3688. @end
  3689. `
  3690. );
  3691. cg = await CodeGraph.init(tempDir, { index: true });
  3692. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3693. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3694. });
  3695. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3696. fs.writeFileSync(
  3697. path.join(tempDir, 'main.m'),
  3698. `@interface Bar : NSObject
  3699. @end
  3700. @implementation Bar
  3701. @end
  3702. @interface Other : NSObject
  3703. - (void)onlyOther;
  3704. @end
  3705. @implementation Other
  3706. - (void)onlyOther {}
  3707. @end
  3708. @interface Foo : NSObject
  3709. + (Bar *)create;
  3710. @end
  3711. @implementation Foo
  3712. + (Bar *)create { return nil; }
  3713. - (void)run { [[Foo create] onlyOther]; }
  3714. @end
  3715. `
  3716. );
  3717. cg = await CodeGraph.init(tempDir, { index: true });
  3718. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3719. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3720. });
  3721. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  3722. // The factory returns `nonnull instancetype` — the nullability qualifier must
  3723. // be skipped (not captured AS the type), and an instancetype class-message
  3724. // factory returns the receiver class, so clearAll resolves on Cache, never a
  3725. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  3726. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  3727. fs.writeFileSync(
  3728. path.join(tempDir, 'main.m'),
  3729. `@interface Cache : NSObject
  3730. + (nonnull instancetype)shared;
  3731. - (void)clearAll;
  3732. @end
  3733. @implementation Cache
  3734. + (nonnull instancetype)shared { return nil; }
  3735. - (void)clearAll {}
  3736. @end
  3737. @interface Decoy : NSObject
  3738. - (void)clearAll;
  3739. @end
  3740. @implementation Decoy
  3741. - (void)clearAll {}
  3742. @end
  3743. @interface Caller : NSObject
  3744. - (void)run;
  3745. @end
  3746. @implementation Caller
  3747. - (void)run { [[Cache shared] clearAll]; }
  3748. @end
  3749. `
  3750. );
  3751. cg = await CodeGraph.init(tempDir, { index: true });
  3752. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  3753. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  3754. });
  3755. });
  3756. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  3757. function callerNamesOf(qualifiedName: string): string[] {
  3758. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3759. if (!target) return [];
  3760. const names = cg
  3761. .getIncomingEdges(target.id)
  3762. .filter((e) => e.kind === 'calls')
  3763. .map((e) => cg.getNode(e.source)?.name)
  3764. .filter((n): n is string => !!n);
  3765. return [...new Set(names)].sort();
  3766. }
  3767. function isCalled(qn: string): boolean {
  3768. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  3769. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  3770. }
  3771. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  3772. fs.writeFileSync(
  3773. path.join(tempDir, 'main.pas'),
  3774. `unit Main;
  3775. interface
  3776. type
  3777. TBar = class
  3778. procedure DoIt;
  3779. end;
  3780. TDecoy = class
  3781. procedure DoIt;
  3782. end;
  3783. TFoo = class
  3784. class function GetInstance: TBar;
  3785. end;
  3786. implementation
  3787. procedure TBar.DoIt; begin end;
  3788. procedure TDecoy.DoIt; begin end;
  3789. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3790. procedure Run;
  3791. begin
  3792. TFoo.GetInstance().DoIt();
  3793. end;
  3794. end.
  3795. `
  3796. );
  3797. cg = await CodeGraph.init(tempDir, { index: true });
  3798. expect(isCalled('TBar::DoIt')).toBe(true);
  3799. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3800. });
  3801. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  3802. fs.writeFileSync(
  3803. path.join(tempDir, 'main.pas'),
  3804. `unit Main;
  3805. interface
  3806. type
  3807. TFoo = class
  3808. constructor Create;
  3809. procedure Configure;
  3810. end;
  3811. TDecoy = class
  3812. procedure Configure;
  3813. end;
  3814. implementation
  3815. constructor TFoo.Create; begin end;
  3816. procedure TFoo.Configure; begin end;
  3817. procedure TDecoy.Configure; begin end;
  3818. procedure Run;
  3819. begin
  3820. TFoo.Create().Configure();
  3821. end;
  3822. end.
  3823. `
  3824. );
  3825. cg = await CodeGraph.init(tempDir, { index: true });
  3826. // A constructor returns its own class (no `: TBar` annotation), so Configure
  3827. // resolves on TFoo, not the same-named decoy.
  3828. expect(isCalled('TFoo::Configure')).toBe(true);
  3829. expect(isCalled('TDecoy::Configure')).toBe(false);
  3830. });
  3831. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  3832. fs.writeFileSync(
  3833. path.join(tempDir, 'main.pas'),
  3834. `unit Main;
  3835. interface
  3836. type
  3837. TFoo = class
  3838. procedure DoIt;
  3839. end;
  3840. TDecoy = class
  3841. procedure DoIt;
  3842. end;
  3843. implementation
  3844. procedure TFoo.DoIt; begin end;
  3845. procedure TDecoy.DoIt; begin end;
  3846. procedure Run(obj: TObject);
  3847. begin
  3848. TFoo(obj).DoIt();
  3849. end;
  3850. end.
  3851. `
  3852. );
  3853. cg = await CodeGraph.init(tempDir, { index: true });
  3854. expect(isCalled('TFoo::DoIt')).toBe(true);
  3855. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3856. });
  3857. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3858. fs.writeFileSync(
  3859. path.join(tempDir, 'main.pas'),
  3860. `unit Main;
  3861. interface
  3862. type
  3863. TBar = class
  3864. end;
  3865. TOther = class
  3866. procedure OnlyOther;
  3867. end;
  3868. TFoo = class
  3869. class function GetInstance: TBar;
  3870. end;
  3871. implementation
  3872. procedure TOther.OnlyOther; begin end;
  3873. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3874. procedure Run;
  3875. begin
  3876. TFoo.GetInstance().OnlyOther();
  3877. end;
  3878. end.
  3879. `
  3880. );
  3881. cg = await CodeGraph.init(tempDir, { index: true });
  3882. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  3883. expect(isCalled('TOther::OnlyOther')).toBe(false);
  3884. });
  3885. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  3886. fs.writeFileSync(
  3887. path.join(tempDir, 'main.pas'),
  3888. `unit Main;
  3889. interface
  3890. type
  3891. TFoo = class
  3892. procedure DoThing;
  3893. procedure Reset;
  3894. end;
  3895. implementation
  3896. procedure TFoo.DoThing; begin end;
  3897. procedure TFoo.Reset; begin end;
  3898. procedure Run(f: TFoo);
  3899. begin
  3900. f.DoThing;
  3901. f.Reset;
  3902. end;
  3903. end.
  3904. `
  3905. );
  3906. cg = await CodeGraph.init(tempDir, { index: true });
  3907. expect(isCalled('TFoo::DoThing')).toBe(true);
  3908. expect(isCalled('TFoo::Reset')).toBe(true);
  3909. });
  3910. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  3911. fs.writeFileSync(
  3912. path.join(tempDir, 'main.pas'),
  3913. `unit Main;
  3914. interface
  3915. type
  3916. TBar = class
  3917. procedure DoIt;
  3918. end;
  3919. TDecoy = class
  3920. procedure DoIt;
  3921. end;
  3922. TFoo = class
  3923. class function GetInstance: TBar;
  3924. end;
  3925. implementation
  3926. procedure TBar.DoIt; begin end;
  3927. procedure TDecoy.DoIt; begin end;
  3928. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3929. procedure Run;
  3930. begin
  3931. TFoo.GetInstance.DoIt;
  3932. end;
  3933. end.
  3934. `
  3935. );
  3936. cg = await CodeGraph.init(tempDir, { index: true });
  3937. expect(isCalled('TBar::DoIt')).toBe(true);
  3938. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3939. });
  3940. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  3941. fs.writeFileSync(
  3942. path.join(tempDir, 'main.pas'),
  3943. `unit Main;
  3944. interface
  3945. type
  3946. TFoo = class
  3947. function GetValue: Integer;
  3948. procedure SetValue(v: Integer);
  3949. property Value: Integer read GetValue write SetValue;
  3950. end;
  3951. implementation
  3952. function TFoo.GetValue: Integer; begin Result := 0; end;
  3953. procedure TFoo.SetValue(v: Integer); begin end;
  3954. procedure Run(f: TFoo);
  3955. var x: Integer;
  3956. begin
  3957. f.Value := 5;
  3958. x := f.Value;
  3959. end;
  3960. end.
  3961. `
  3962. );
  3963. cg = await CodeGraph.init(tempDir, { index: true });
  3964. // A property read/write is a bare dot in assignment position, not a statement,
  3965. // so it must not be mis-extracted as a call to the property's getter/setter.
  3966. expect(isCalled('TFoo::GetValue')).toBe(false);
  3967. expect(isCalled('TFoo::SetValue')).toBe(false);
  3968. });
  3969. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  3970. fs.writeFileSync(
  3971. path.join(tempDir, 'main.pas'),
  3972. `unit Main;
  3973. interface
  3974. type
  3975. TTgt = class
  3976. procedure Hit;
  3977. end;
  3978. TFoo = class
  3979. procedure DoStuff;
  3980. end;
  3981. implementation
  3982. procedure TTgt.Hit; begin end;
  3983. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  3984. procedure Helper; var t: TTgt; begin t.Hit; end;
  3985. `
  3986. );
  3987. cg = await CodeGraph.init(tempDir, { index: true });
  3988. // `Helper` is implementation-only (no interface decl, not a method), but its
  3989. // body's call must attribute to `Helper`, not the file/module — alongside the
  3990. // method `DoStuff`.
  3991. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  3992. });
  3993. });
  3994. });