resolution.test.ts 184 KB

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