1
0

resolution.test.ts 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102
  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('promotes calls→instantiates when target resolves to a C++ union', async () => {
  924. // `Packet()` value-initializes the union. The extractor emits a calls
  925. // reference for that expression, so resolution must preserve the
  926. // class-like promotion that unions received when they were structs.
  927. fs.writeFileSync(
  928. path.join(tempDir, 'packet.cpp'),
  929. `union Packet { unsigned int raw; };
  930. void initialize() { Packet(); }
  931. `
  932. );
  933. cg = await CodeGraph.init(tempDir, { index: true });
  934. cg.resolveReferences();
  935. const packet = cg.getNodesByKind('union').find((n) => n.name === 'Packet');
  936. const initialize = cg.getNodesByKind('function').find((n) => n.name === 'initialize');
  937. expect(packet).toBeDefined();
  938. expect(initialize).toBeDefined();
  939. const outgoing = cg.getOutgoingEdges(initialize!.id);
  940. expect(outgoing.some((e) => e.kind === 'instantiates' && e.target === packet!.id)).toBe(true);
  941. expect(outgoing.some((e) => e.kind === 'calls' && e.target === packet!.id)).toBe(false);
  942. });
  943. it('resolves a static call through an imported C++ union to its member', async () => {
  944. fs.writeFileSync(
  945. path.join(tempDir, 'ops.hpp'),
  946. `union Ops {
  947. static int run() { return 1; }
  948. };
  949. `
  950. );
  951. fs.writeFileSync(
  952. path.join(tempDir, 'main.cpp'),
  953. `#include "ops.hpp"
  954. int invoke() { return Ops::run(); }
  955. `
  956. );
  957. cg = await CodeGraph.init(tempDir, { index: true });
  958. cg.resolveReferences();
  959. const invoke = cg.getNodesByKind('function').find((n) => n.name === 'invoke');
  960. const run = cg.getNodesByKind('method').find((n) => n.name === 'run');
  961. expect(invoke).toBeDefined();
  962. expect(run).toBeDefined();
  963. const outgoing = cg.getOutgoingEdges(invoke!.id);
  964. expect(outgoing.some((e) => e.kind === 'calls' && e.target === run!.id)).toBe(true);
  965. });
  966. it('bridges a Rust trait method to a union implementor (interface-impl)', async () => {
  967. // A Rust union can `impl Trait` exactly as a struct can. Trait-dispatch
  968. // synthesis enumerates concrete kinds explicitly, so a union implementor
  969. // only becomes a candidate if `union` is in that list. Making unions
  970. // first-class nodes is not enough on its own: without this, `Reg` has an
  971. // `implements` edge and is still silently dropped from the fan-out, so
  972. // "who implements this trait" answers wrongly rather than incompletely
  973. // — the struct beside it resolves and the union does not (#1515).
  974. fs.writeFileSync(
  975. path.join(tempDir, 'lib.rs'),
  976. `pub union Reg { pub raw: u32 }
  977. pub struct Ctl { pub n: u32 }
  978. pub trait Describe { fn describe(&self) -> String; }
  979. impl Describe for Reg { fn describe(&self) -> String { "reg".into() } }
  980. impl Describe for Ctl { fn describe(&self) -> String { "ctl".into() } }
  981. `
  982. );
  983. cg = await CodeGraph.init(tempDir, { index: true });
  984. const methods = cg.getNodesByKind('method');
  985. const traitMethod = methods.find((n) => n.qualifiedName === 'Describe::describe');
  986. const unionImpl = methods.find((n) => n.qualifiedName === 'Reg::describe');
  987. const structImpl = methods.find((n) => n.qualifiedName === 'Ctl::describe');
  988. expect(traitMethod, 'trait method should be in the graph').toBeDefined();
  989. expect(unionImpl, 'union impl method should be in the graph').toBeDefined();
  990. expect(structImpl, 'struct impl method should be in the graph').toBeDefined();
  991. const synth = cg
  992. .getOutgoingEdges(traitMethod!.id)
  993. .filter((e) => e.kind === 'calls' && e.provenance === 'heuristic');
  994. const targets = new Set(synth.map((e) => e.target));
  995. // The struct implementor bridged before unions were nodes at all; it is
  996. // the control that proves the synthesizer ran for this trait.
  997. expect(targets.has(structImpl!.id), 'struct implementor should bridge').toBe(true);
  998. expect(targets.has(unionImpl!.id), 'union implementor should bridge').toBe(true);
  999. const unionEdge = synth.find((e) => e.target === unionImpl!.id);
  1000. expect(
  1001. (unionEdge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy
  1002. ).toBe('interface-impl');
  1003. });
  1004. it('records instantiates for C++ stack/brace construction, targeting the class (#1035)', async () => {
  1005. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init)
  1006. // carry the constructor args directly on the declarator — there's no
  1007. // call/new node — so they recorded no `instantiates` edge, while heap
  1008. // `new Calculator(0)` did. Both stack forms now do.
  1009. fs.writeFileSync(
  1010. path.join(tempDir, 'm.cpp'),
  1011. `class Calculator { public: Calculator(int seed) {} int add(int a, int b){ return a+b; } };
  1012. class Widget { public: Widget(int a, int b) {} };
  1013. int runStack(int a, int b) { Calculator calc(0); return calc.add(a, b); }
  1014. int runBrace() { Widget w{1, 2}; return 0; }
  1015. int runHeap(int a, int b) { Calculator* c = new Calculator(0); return c->add(a, b); }
  1016. void noise() { int x(5); int y{6}; Calculator deferred; }
  1017. `
  1018. );
  1019. cg = await CodeGraph.init(tempDir, { index: true });
  1020. const fn = (name: string) => cg.getNodesByKind('function').find((n) => n.name === name)!;
  1021. const instTargets = (name: string) =>
  1022. cg
  1023. .getOutgoingEdges(fn(name).id)
  1024. .filter((e) => e.kind === 'instantiates')
  1025. .map((e) => cg.getNode(e.target)!);
  1026. // Direct-init (the issue) and brace-init both instantiate, targeting the
  1027. // CLASS node — not the same-named constructor method.
  1028. const stack = instTargets('runStack');
  1029. expect(stack.map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  1030. expect(instTargets('runBrace').map((n) => `${n.kind}:${n.name}`)).toContain('class:Widget');
  1031. // Heap still works (regression guard).
  1032. expect(instTargets('runHeap').map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  1033. // Primitives (`int x(0)`/`int y{6}`) and bare default construction
  1034. // (`Calculator deferred;`) must NOT mint an instantiates edge.
  1035. expect(instTargets('noise')).toHaveLength(0);
  1036. });
  1037. it('resolves a cross-file static method call to the method, not the class (#825)', async () => {
  1038. // `Foo.bar()` where `Foo` is an imported class must link to the static
  1039. // method `Foo::bar`, NOT to the class `Foo`. Previously the import
  1040. // resolver dropped the `.bar` member and resolved to `Foo`, which the
  1041. // calls→instantiates promotion then turned into `run instantiates Foo`,
  1042. // leaving the static method with zero callers and a hollow impact radius.
  1043. fs.writeFileSync(
  1044. path.join(tempDir, 'helpers.ts'),
  1045. `export class Foo {\n static bar(x: number) { return x + 1; }\n}\n`
  1046. );
  1047. fs.writeFileSync(
  1048. path.join(tempDir, 'caller.ts'),
  1049. `import { Foo } from './helpers';\nexport function run() { return Foo.bar(41); }\n`
  1050. );
  1051. cg = await CodeGraph.init(tempDir, { index: true });
  1052. cg.resolveReferences();
  1053. const bar = cg.getNodesByKind('method').find((n) => n.name === 'bar');
  1054. const foo = cg.getNodesByKind('class').find((n) => n.name === 'Foo');
  1055. const run = cg.getNodesByKind('function').find((n) => n.name === 'run');
  1056. expect(bar).toBeDefined();
  1057. expect(foo).toBeDefined();
  1058. expect(run).toBeDefined();
  1059. // `run` is reported as a caller of the static method `Foo.bar`.
  1060. const barCallers = cg.getCallers(bar!.id).map((c) => c.node.name);
  1061. expect(barCallers).toContain('run');
  1062. // And the call is NOT mis-promoted to `run instantiates Foo`.
  1063. const outgoing = cg.getOutgoingEdges(run!.id);
  1064. expect(
  1065. outgoing.filter((e) => e.kind === 'instantiates' && e.target === foo!.id)
  1066. ).toHaveLength(0);
  1067. // The real edge is a `calls` edge to the method.
  1068. expect(
  1069. outgoing.some((e) => e.kind === 'calls' && e.target === bar!.id)
  1070. ).toBe(true);
  1071. });
  1072. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  1073. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  1074. // external (isExternalImport returned true for any non-`/internal/`
  1075. // import without `.`-prefix) and resolution fell through to name-match
  1076. // with path proximity — recall on cross-package callers was ~<1%.
  1077. fs.writeFileSync(
  1078. path.join(tempDir, 'go.mod'),
  1079. 'module github.com/example/myproject\n\ngo 1.21\n'
  1080. );
  1081. const pkgaDir = path.join(tempDir, 'pkga');
  1082. const pkgbDir = path.join(tempDir, 'pkgb');
  1083. const pkgcDir = path.join(tempDir, 'pkgc');
  1084. fs.mkdirSync(pkgaDir);
  1085. fs.mkdirSync(pkgbDir);
  1086. fs.mkdirSync(pkgcDir);
  1087. // Same-name exported function in two packages — only the imported one
  1088. // should resolve. Exercises disambiguation, not just connectivity.
  1089. fs.writeFileSync(
  1090. path.join(pkgaDir, 'conv.go'),
  1091. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  1092. );
  1093. fs.writeFileSync(
  1094. path.join(pkgbDir, 'conv.go'),
  1095. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  1096. );
  1097. fs.writeFileSync(
  1098. path.join(pkgcDir, 'use.go'),
  1099. `package pkgc
  1100. import "github.com/example/myproject/pkga"
  1101. func UsePkga() {
  1102. pkga.Convert(5)
  1103. }
  1104. `
  1105. );
  1106. cg = await CodeGraph.init(tempDir, { index: true });
  1107. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  1108. expect(usePkga).toBeDefined();
  1109. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  1110. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  1111. expect(callEdges).toHaveLength(1);
  1112. const target = cg.getNode(callEdges[0]!.target);
  1113. expect(target?.name).toBe('Convert');
  1114. // Critical: the resolver must pick the imported pkga's Convert,
  1115. // not pkgb's. With the broken (pre-fix) resolver this lands on
  1116. // whichever Convert happens to be cheaper under path proximity.
  1117. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  1118. });
  1119. it('resolves Go aliased imports across packages (#388)', async () => {
  1120. fs.writeFileSync(
  1121. path.join(tempDir, 'go.mod'),
  1122. 'module github.com/example/myproject\n\ngo 1.21\n'
  1123. );
  1124. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  1125. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  1126. fs.writeFileSync(
  1127. path.join(tempDir, 'pkgb', 'lib.go'),
  1128. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  1129. );
  1130. fs.writeFileSync(
  1131. path.join(tempDir, 'pkgd', 'use.go'),
  1132. `package pkgd
  1133. import (
  1134. "fmt"
  1135. alias "github.com/example/myproject/pkgb"
  1136. )
  1137. func UseAliased() {
  1138. fmt.Println("hi")
  1139. alias.Compute(3)
  1140. }
  1141. `
  1142. );
  1143. cg = await CodeGraph.init(tempDir, { index: true });
  1144. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  1145. expect(useAliased).toBeDefined();
  1146. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  1147. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  1148. expect(calls).toHaveLength(1);
  1149. const target = cg.getNode(calls[0]!.target);
  1150. expect(target?.name).toBe('Compute');
  1151. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  1152. });
  1153. it('resolves Python module-attribute calls after `from pkg import module` (#578)', async () => {
  1154. // Pre-#578, a `module.func()` call where `module` was bound via
  1155. // `from pkg import module` dropped its `calls` edge. The file→file import
  1156. // edge resolved (resolveModuleImportToFile falls back to a dotted-module
  1157. // file lookup for absolute package paths), but resolvePythonModuleMember
  1158. // had no such fallback — resolveImportPath returns null for an absolute
  1159. // package path like `pkg.module`, so the member never resolved and
  1160. // callers/callees/impact on the target came back empty. Same root-cause
  1161. // class as the Go cross-package qualified call (#388).
  1162. fs.mkdirSync(path.join(tempDir, 'pkg'));
  1163. fs.writeFileSync(path.join(tempDir, 'pkg', '__init__.py'), '');
  1164. fs.writeFileSync(
  1165. path.join(tempDir, 'pkg', 'module.py'),
  1166. 'def func():\n return 1\n'
  1167. );
  1168. fs.writeFileSync(
  1169. path.join(tempDir, 'main.py'),
  1170. `from pkg import module
  1171. import os
  1172. def caller():
  1173. return module.func()
  1174. def external_caller():
  1175. return os.getcwd()
  1176. `
  1177. );
  1178. cg = await CodeGraph.init(tempDir, { index: true });
  1179. const caller = cg.getNodesByKind('function').filter((n) => n.name === 'caller')[0];
  1180. expect(caller).toBeDefined();
  1181. const calls = cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls');
  1182. // module.func() must resolve to the real function in the submodule file.
  1183. expect(calls).toHaveLength(1);
  1184. const target = cg.getNode(calls[0]!.target);
  1185. expect(target?.name).toBe('func');
  1186. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkg/module.py');
  1187. // The flip side of the fix: an attribute call through a *stdlib* module
  1188. // (`os.getcwd()`) must still create no edge — the fallback only matches
  1189. // real in-repo module files.
  1190. const externalCaller = cg.getNodesByKind('function').filter((n) => n.name === 'external_caller')[0];
  1191. expect(externalCaller).toBeDefined();
  1192. const externalCalls = cg.getOutgoingEdges(externalCaller!.id).filter((e) => e.kind === 'calls');
  1193. expect(externalCalls).toHaveLength(0);
  1194. });
  1195. it('attaches Go methods to their receiver type across files (#583, cross-file half)', async () => {
  1196. // In Go a type's methods are commonly declared in a different file from the
  1197. // `type` declaration (`type Box` in box.go, `func (b *Box) Get()` in
  1198. // box_methods.go). Extraction only attaches the struct→method `contains`
  1199. // edge when the type is in the SAME file (the owner lookup is file-scoped),
  1200. // so a cross-file method was orphaned from its struct — breaking member
  1201. // outlines and any callers/callees/impact traversal through `contains`. A
  1202. // resolution-phase pass now links them within the package (= directory).
  1203. fs.writeFileSync(
  1204. path.join(tempDir, 'box.go'),
  1205. 'package main\n\ntype Box struct{ v int }\n'
  1206. );
  1207. fs.writeFileSync(
  1208. path.join(tempDir, 'box_methods.go'),
  1209. 'package main\n\nfunc (b *Box) Get() int { return b.v }\nfunc (b *Box) Set(x int) { b.v = x }\n'
  1210. );
  1211. // Generic receiver declared cross-file too — exercises #583 half A
  1212. // (generic `*Stack[T]` receiver parsing) and half B (cross-file) together.
  1213. fs.writeFileSync(
  1214. path.join(tempDir, 'stack.go'),
  1215. 'package main\n\ntype Stack[T any] struct {\n\titems []T\n}\n'
  1216. );
  1217. fs.writeFileSync(
  1218. path.join(tempDir, 'stack_push.go'),
  1219. 'package main\n\nfunc (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }\n'
  1220. );
  1221. // A same-named type in another package must NOT capture this package's
  1222. // methods — the link is scoped to the receiver type's own directory.
  1223. fs.mkdirSync(path.join(tempDir, 'other'));
  1224. fs.writeFileSync(
  1225. path.join(tempDir, 'other', 'box.go'),
  1226. 'package other\n\ntype Box struct{ w int }\n'
  1227. );
  1228. cg = await CodeGraph.init(tempDir, { index: true });
  1229. const methodsOf = (typeName: string, file: string): string[] => {
  1230. const node = cg
  1231. .getNodesByKind('struct')
  1232. .find((n) => n.name === typeName && n.filePath.replace(/\\/g, '/') === file);
  1233. expect(node, `${typeName} @ ${file}`).toBeDefined();
  1234. return cg
  1235. .getOutgoingEdges(node!.id)
  1236. .filter((e) => e.kind === 'contains')
  1237. .map((e) => cg.getNode(e.target))
  1238. .filter((n) => !!n && n.kind === 'method')
  1239. .map((n) => n!.name)
  1240. .sort();
  1241. };
  1242. // Cross-file (non-generic) methods now attach to their struct.
  1243. expect(methodsOf('Box', 'box.go')).toEqual(['Get', 'Set']);
  1244. // Generic + cross-file.
  1245. expect(methodsOf('Stack', 'stack.go')).toEqual(['Push']);
  1246. // Cross-package isolation: other/Box defines no methods of its own.
  1247. expect(methodsOf('Box', 'other/box.go')).toEqual([]);
  1248. });
  1249. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  1250. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  1251. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  1252. // because the type_alias had no `stop` node — only the unrelated
  1253. // class did. Now type_alias produces member nodes (property/method),
  1254. // so the camelCase receiver↔type word overlap pulls the call to
  1255. // `RecorderHandle::stop` instead of the look-alike class.
  1256. fs.mkdirSync(path.join(tempDir, 'voice'));
  1257. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  1258. fs.writeFileSync(
  1259. path.join(tempDir, 'voice', 'recorder.ts'),
  1260. `export type RecorderHandle = {
  1261. wavPath: string;
  1262. stop: () => Promise<{ ok: true }>;
  1263. };
  1264. `
  1265. );
  1266. fs.writeFileSync(
  1267. path.join(tempDir, 'voice', 'controller.ts'),
  1268. `import type { RecorderHandle } from "./recorder";
  1269. export async function finaliseRecording(recorder: RecorderHandle) {
  1270. return await recorder.stop();
  1271. }
  1272. `
  1273. );
  1274. fs.writeFileSync(
  1275. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  1276. `export class StdioMcpClient {
  1277. private stopped = false;
  1278. async stop(): Promise<void> { this.stopped = true; }
  1279. }
  1280. `
  1281. );
  1282. cg = await CodeGraph.init(tempDir, { index: true });
  1283. const handleStop = cg
  1284. .getNodesByKind('method')
  1285. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  1286. expect(handleStop).toBeDefined();
  1287. const clientStop = cg
  1288. .getNodesByKind('method')
  1289. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  1290. expect(clientStop).toBeDefined();
  1291. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  1292. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  1293. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  1294. // The class method must have NO callers — voice/'s call must NOT
  1295. // mis-attribute. A non-empty list would mean the false-positive
  1296. // path is still firing.
  1297. expect(clientCallers).toHaveLength(0);
  1298. // Function-typed property surfaces as a `method` node, not `property`,
  1299. // because `stop()` semantics at the call site are method semantics.
  1300. expect(handleStop!.kind).toBe('method');
  1301. });
  1302. it('Java import disambiguates same-name classes across modules (#314)', async () => {
  1303. // Pre-#314 the import resolver had no Java branch at all, so a
  1304. // multi-module Maven repo where `dao/converter/FooConverter` and
  1305. // `service/converter/FooConverter` both export a `convert` method
  1306. // resolved by file-path proximity — picking whichever class was
  1307. // closer to the caller, which is wrong any time the caller lives
  1308. // in an equidistant cross-cutting module.
  1309. const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
  1310. const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
  1311. const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
  1312. fs.mkdirSync(daoDir, { recursive: true });
  1313. fs.mkdirSync(serviceDir, { recursive: true });
  1314. fs.mkdirSync(webDir, { recursive: true });
  1315. fs.writeFileSync(
  1316. path.join(daoDir, 'FooConverter.java'),
  1317. `package com.example.dao.converter;
  1318. public class FooConverter { public String convert(String x) { return "dao:" + x; } }
  1319. `
  1320. );
  1321. fs.writeFileSync(
  1322. path.join(serviceDir, 'FooConverter.java'),
  1323. `package com.example.service.converter;
  1324. public class FooConverter { public String convert(String x) { return "svc:" + x; } }
  1325. `
  1326. );
  1327. // The caller imports the SERVICE version — even though dao is
  1328. // alphabetically/lexically first in the candidate list, the
  1329. // import must trump that order.
  1330. fs.writeFileSync(
  1331. path.join(webDir, 'Handler.java'),
  1332. `package com.example.web;
  1333. import com.example.service.converter.FooConverter;
  1334. public class Handler {
  1335. private FooConverter fooConverter;
  1336. public String use() { return fooConverter.convert("input"); }
  1337. }
  1338. `
  1339. );
  1340. cg = await CodeGraph.init(tempDir, { index: true });
  1341. const use = cg
  1342. .getNodesByKind('method')
  1343. .find((n) => n.qualifiedName === 'com.example.web::Handler::use');
  1344. expect(use).toBeDefined();
  1345. const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
  1346. expect(calls.length).toBeGreaterThanOrEqual(1);
  1347. const target = cg.getNode(calls[0]!.target);
  1348. expect(target?.name).toBe('convert');
  1349. expect(target?.filePath.replace(/\\/g, '/')).toBe(
  1350. 'service/src/main/java/com/example/service/converter/FooConverter.java'
  1351. );
  1352. });
  1353. it('C# extracts references from method/property/field types (#381)', async () => {
  1354. // Pre-#381, every C# project produced ZERO `references` edges:
  1355. // csharp.ts was missing returnField, and the type-leaf walker
  1356. // only recognized TS/Java's `type_identifier` nodes — C# uses
  1357. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  1358. const srcDir = path.join(tempDir, 'src');
  1359. fs.mkdirSync(srcDir, { recursive: true });
  1360. fs.writeFileSync(
  1361. path.join(srcDir, 'Dtos.cs'),
  1362. `namespace MyApp;
  1363. public class SessionInfoDto { public string Id { get; set; } = ""; }
  1364. public class UserDto { public string Name { get; set; } = ""; }
  1365. `
  1366. );
  1367. fs.writeFileSync(
  1368. path.join(srcDir, 'Service.cs'),
  1369. `using System.Threading.Tasks;
  1370. namespace MyApp;
  1371. public class DataExporter
  1372. {
  1373. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  1374. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  1375. public SessionInfoDto Latest { get; set; } = new();
  1376. private UserDto _cached;
  1377. }
  1378. `
  1379. );
  1380. cg = await CodeGraph.init(tempDir, { index: true });
  1381. const sessionDto = cg
  1382. .getNodesByKind('class')
  1383. .find((n) => n.name === 'SessionInfoDto');
  1384. const userDto = cg
  1385. .getNodesByKind('class')
  1386. .find((n) => n.name === 'UserDto');
  1387. expect(sessionDto).toBeDefined();
  1388. expect(userDto).toBeDefined();
  1389. const sessionIncoming = cg
  1390. .getIncomingEdges(sessionDto!.id)
  1391. .filter((e) => e.kind === 'references');
  1392. const userIncoming = cg
  1393. .getIncomingEdges(userDto!.id)
  1394. .filter((e) => e.kind === 'references');
  1395. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  1396. // UserDto: Build param, BuildAsync param, _cached field.
  1397. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  1398. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  1399. });
  1400. it('C# primary-constructor parameters record their type dependencies (#237)', async () => {
  1401. // C# 12 primary constructors declare a type's injected dependencies inline
  1402. // (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache)`). Each
  1403. // ctor parameter's type is recorded as a `references` edge from the class,
  1404. // so a DI-registered contract reached only through a primary ctor is no
  1405. // longer reported as having no dependents.
  1406. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1407. fs.writeFileSync(
  1408. path.join(tempDir, 'src', 'Contracts.cs'),
  1409. `namespace App;
  1410. public interface IRepo { }
  1411. public class ICache { }
  1412. `
  1413. );
  1414. fs.writeFileSync(
  1415. path.join(tempDir, 'src', 'OrderService.cs'),
  1416. `namespace App;
  1417. public sealed class OrderService(IRepo repo, [FromKeyedServices("primary")] ICache cache)
  1418. {
  1419. public void Run() { }
  1420. }
  1421. `
  1422. );
  1423. cg = await CodeGraph.init(tempDir, { index: true });
  1424. const svc = cg.getNodesByKind('class').find((n) => n.name === 'OrderService');
  1425. expect(svc).toBeDefined();
  1426. // The class itself must index (it used to vanish under the old grammar).
  1427. const out = cg.getOutgoingEdges(svc!.id).filter((e) => e.kind === 'references');
  1428. const depNames = out.map((e) => cg.getNode(e.target)?.name);
  1429. expect(depNames).toContain('IRepo');
  1430. expect(depNames).toContain('ICache'); // the keyed-DI ([FromKeyedServices]) dependency
  1431. });
  1432. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  1433. fs.writeFileSync(
  1434. path.join(tempDir, 'go.mod'),
  1435. 'module github.com/example/myproject\n\ngo 1.21\n'
  1436. );
  1437. fs.writeFileSync(
  1438. path.join(tempDir, 'main.go'),
  1439. `package main
  1440. import "fmt"
  1441. func main() {
  1442. fmt.Println("hi")
  1443. }
  1444. `
  1445. );
  1446. cg = await CodeGraph.init(tempDir, { index: true });
  1447. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  1448. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  1449. // No spurious in-project edge — fmt.* must stay unresolved/external.
  1450. expect(calls).toHaveLength(0);
  1451. });
  1452. });
  1453. describe('Same-name method disambiguation (#1079)', () => {
  1454. // resolveMethodOnType picks among several methods that share a
  1455. // `Type::method` qualifiedName. The precedence is:
  1456. // 1. preferredFqn (Java/Kotlin import — target is intentionally in
  1457. // ANOTHER file, #314),
  1458. // 2. the call site's OWN file (language-agnostic, #1079),
  1459. // 3. matches[0] (first-indexed) as a last resort.
  1460. const methodNode = (
  1461. id: string,
  1462. filePath: string,
  1463. language: Node['language'] = 'cpp',
  1464. qualifiedName = 'Logger::log',
  1465. name = 'log',
  1466. ): Node => ({
  1467. id, kind: 'method', name, qualifiedName, filePath, language,
  1468. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  1469. });
  1470. const callRef = (filePath: string, language: Node['language'] = 'cpp'): UnresolvedRef => ({
  1471. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1472. line: 2, column: 0, filePath, language,
  1473. });
  1474. const ctxFor = (candidates: Node[]): ResolutionContext => ({
  1475. getNodesInFile: () => [],
  1476. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1477. getNodesByQualifiedName: () => [],
  1478. getNodesByKind: () => [],
  1479. fileExists: () => false,
  1480. readFile: () => null,
  1481. getProjectRoot: () => '',
  1482. getAllFiles: () => [],
  1483. });
  1484. it('prefers the definition in the call site\'s own file (#1079)', () => {
  1485. // matches[0] is the a/ definition; the call comes from b/, so it must
  1486. // resolve to b/ — not collapse onto the first-indexed match.
  1487. const logA = methodNode('m:a', 'a/svc.cpp');
  1488. const logB = methodNode('m:b', 'b/svc.cpp');
  1489. const result = resolveMethodOnType(
  1490. 'Logger', 'log', callRef('b/svc.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1491. );
  1492. expect(result?.targetNodeId).toBe('m:b');
  1493. });
  1494. it('lets an import FQN pin a cross-file target over the same-file preference (#314)', () => {
  1495. // Java: two `Bar::doIt` in different packages. The import FQN pins the
  1496. // alpha package; even though the call site lives in beta's file, the FQN
  1497. // must win — the same-file preference runs only AFTER preferredFqn.
  1498. const alpha = methodNode('m:alpha', 'com/example/alpha/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1499. const beta = methodNode('m:beta', 'com/example/beta/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1500. const result = resolveMethodOnType(
  1501. 'Bar', 'doIt', callRef('com/example/beta/Bar.java', 'java'),
  1502. ctxFor([alpha, beta]), 0.9, 'instance-method', 'com.example.alpha.Bar',
  1503. );
  1504. expect(result?.targetNodeId).toBe('m:alpha');
  1505. });
  1506. it('falls back to the first match when nothing disambiguates', () => {
  1507. // Call site is a third file: no FQN, no same-file candidate → matches[0].
  1508. const logA = methodNode('m:a', 'a/svc.cpp');
  1509. const logB = methodNode('m:b', 'b/svc.cpp');
  1510. const result = resolveMethodOnType(
  1511. 'Logger', 'log', callRef('c/other.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1512. );
  1513. expect(result?.targetNodeId).toBe('m:a');
  1514. });
  1515. it('resolves C++ calls end-to-end to same-named classes in different files (#1079)', async () => {
  1516. // The exact repro from the issue: two files, each with its own
  1517. // `Logger::log`. Before the fix both callers pointed at the first def.
  1518. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1519. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1520. fs.writeFileSync(
  1521. path.join(tempDir, 'a', 'svc.cpp'),
  1522. `class Logger { public: void log() { int a = 1; } };\nvoid useA() { Logger lg; lg.log(); }\n`,
  1523. );
  1524. fs.writeFileSync(
  1525. path.join(tempDir, 'b', 'svc.cpp'),
  1526. `class Logger { public: void log() { int b = 2; } };\nvoid useB() { Logger lg; lg.log(); }\n`,
  1527. );
  1528. cg = await CodeGraph.init(tempDir, { index: true });
  1529. cg.resolveReferences();
  1530. const logInDir = (dir: string) =>
  1531. cg.getNodesByKind('method').find(
  1532. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1533. )!;
  1534. const callTargets = (fnName: string) =>
  1535. cg
  1536. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1537. .filter((e) => e.kind === 'calls')
  1538. .map((e) => e.target);
  1539. const logA = logInDir('a');
  1540. const logB = logInDir('b');
  1541. expect(logA).toBeDefined();
  1542. expect(logB).toBeDefined();
  1543. expect(logA.id).not.toBe(logB.id);
  1544. // Each caller resolves to the Logger::log in its OWN file.
  1545. expect(callTargets('useA')).toContain(logA.id);
  1546. expect(callTargets('useB')).toContain(logB.id);
  1547. });
  1548. it('preferCallSiteFile puts same-file candidates first and is otherwise a no-op', () => {
  1549. const a = methodNode('m:a', 'a/svc.cpp');
  1550. const b = methodNode('m:b', 'b/svc.cpp');
  1551. // Same-file first; the rest keep their original order (stable).
  1552. expect(preferCallSiteFile([a, b], 'b/svc.cpp').map((n) => n.id)).toEqual(['m:b', 'm:a']);
  1553. expect(preferCallSiteFile([a, b], 'a/svc.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1554. // No same-file match → unchanged; <2 candidates → returned as-is.
  1555. expect(preferCallSiteFile([a, b], 'c/other.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1556. expect(preferCallSiteFile([a], 'z/none.cpp')).toHaveLength(1);
  1557. });
  1558. it('matchByQualifiedName prefers the same-file target when a qualified name is ambiguous (#1079)', () => {
  1559. // Two `Logger::log` definitions; an explicit `Logger::log()` call from b/
  1560. // must resolve to b/'s definition, not the first-indexed one.
  1561. const a = methodNode('m:a', 'a/svc.cpp');
  1562. const b = methodNode('m:b', 'b/svc.cpp');
  1563. const ctx: ResolutionContext = {
  1564. getNodesInFile: () => [],
  1565. getNodesByName: (name) => [a, b].filter((n) => n.name === name),
  1566. getNodesByQualifiedName: (q) => (q === 'Logger::log' ? [a, b] : []),
  1567. getNodesByKind: () => [],
  1568. fileExists: () => false,
  1569. readFile: () => null,
  1570. getProjectRoot: () => '',
  1571. getAllFiles: () => [],
  1572. };
  1573. const ref: UnresolvedRef = {
  1574. fromNodeId: 'caller', referenceName: 'Logger::log', referenceKind: 'calls',
  1575. line: 2, column: 0, filePath: 'b/svc.cpp', language: 'cpp',
  1576. };
  1577. expect(matchByQualifiedName(ref, ctx)?.targetNodeId).toBe('m:b');
  1578. });
  1579. it('resolves a static/class-receiver call to the class in the caller\'s file (#1079)', async () => {
  1580. // `Logger.log()` — the receiver is the class NAME, so this routes through
  1581. // the class-name-receiver strategy (not the C++ instance path). It was
  1582. // file-blind across languages; verified here on TypeScript.
  1583. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1584. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1585. fs.writeFileSync(
  1586. path.join(tempDir, 'a', 'svc.ts'),
  1587. `class Logger { static log() { return 1; } }\nexport function useA() { return Logger.log(); }\n`,
  1588. );
  1589. fs.writeFileSync(
  1590. path.join(tempDir, 'b', 'svc.ts'),
  1591. `class Logger { static log() { return 2; } }\nexport function useB() { return Logger.log(); }\n`,
  1592. );
  1593. cg = await CodeGraph.init(tempDir, { index: true });
  1594. cg.resolveReferences();
  1595. const logInDir = (dir: string) =>
  1596. cg.getNodesByKind('method').find(
  1597. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.ts`),
  1598. )!;
  1599. const callTargets = (fnName: string) =>
  1600. cg
  1601. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1602. .filter((e) => e.kind === 'calls')
  1603. .map((e) => e.target);
  1604. const logA = logInDir('a');
  1605. const logB = logInDir('b');
  1606. expect(logA?.id).not.toBe(logB?.id);
  1607. expect(callTargets('useA')).toContain(logA.id);
  1608. expect(callTargets('useB')).toContain(logB.id);
  1609. });
  1610. it('resolves an explicitly-qualified call to the definition in the caller\'s file (#1079)', async () => {
  1611. // `Logger::log()` with two `Logger::log` definitions routes through the
  1612. // qualified-name strategy, whose partial match previously picked the first.
  1613. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1614. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1615. fs.writeFileSync(
  1616. path.join(tempDir, 'a', 'svc.cpp'),
  1617. `class Logger { public: static void log() { int a = 1; } };\nvoid useA() { Logger::log(); }\n`,
  1618. );
  1619. fs.writeFileSync(
  1620. path.join(tempDir, 'b', 'svc.cpp'),
  1621. `class Logger { public: static void log() { int b = 2; } };\nvoid useB() { Logger::log(); }\n`,
  1622. );
  1623. cg = await CodeGraph.init(tempDir, { index: true });
  1624. cg.resolveReferences();
  1625. const logInDir = (dir: string) =>
  1626. cg.getNodesByKind('method').find(
  1627. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1628. )!;
  1629. const callTargets = (fnName: string) =>
  1630. cg
  1631. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1632. .filter((e) => e.kind === 'calls')
  1633. .map((e) => e.target);
  1634. const logA = logInDir('a');
  1635. const logB = logInDir('b');
  1636. expect(logA?.id).not.toBe(logB?.id);
  1637. expect(callTargets('useA')).toContain(logA.id);
  1638. expect(callTargets('useB')).toContain(logB.id);
  1639. });
  1640. });
  1641. describe('Watchdog-safe resolution on collision-heavy repos (#1122)', () => {
  1642. // On a large Java-style repo, per-ref resolution cost is unbounded in the
  1643. // worst case (a colliding method name whose candidate set misses the LRU
  1644. // re-fetches tens of thousands of rows, and receiver inference re-splits
  1645. // the whole source file). v1.2.0 yielded only every 500 refs, so a dense
  1646. // pocket multiplied that cost past the #850 watchdog window and a VALID
  1647. // `init` was SIGKILLed at "Resolving refs". These pin the three guards:
  1648. // per-ref yield checkpoints, the (type, method) match memo, and the
  1649. // per-file lines cache with its generated/minified-line skip.
  1650. const methodNode = (
  1651. id: string,
  1652. filePath: string,
  1653. qualifiedName: string,
  1654. name: string,
  1655. language: Node['language'] = 'typescript',
  1656. kind: Node['kind'] = 'method',
  1657. ): Node => ({
  1658. id, kind, name, qualifiedName, filePath, language,
  1659. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  1660. });
  1661. it('resolveMethodOnType consults the method-match memo and still disambiguates per call site', () => {
  1662. const logA = methodNode('m:a', 'a/svc.ts', 'Logger::log', 'log');
  1663. const logB = methodNode('m:b', 'b/svc.ts', 'Logger::log', 'log');
  1664. const shared = [logA, logB]; // one cached array served to every caller
  1665. let memoCalls = 0;
  1666. let rawNameLookups = 0;
  1667. const ctx: ResolutionContext = {
  1668. getNodesInFile: () => [],
  1669. getNodesByName: () => { rawNameLookups++; return shared; },
  1670. getMethodMatches: () => { memoCalls++; return shared; },
  1671. getNodesByQualifiedName: () => [],
  1672. getNodesByKind: () => [],
  1673. fileExists: () => false,
  1674. readFile: () => null,
  1675. getProjectRoot: () => '',
  1676. getAllFiles: () => [],
  1677. };
  1678. const refFrom = (filePath: string): UnresolvedRef => ({
  1679. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1680. line: 2, column: 0, filePath, language: 'typescript',
  1681. });
  1682. // Both call sites read the SAME memoized array, yet each still resolves
  1683. // to its own file — per-ref disambiguation runs after the memo (#1079).
  1684. const fromA = resolveMethodOnType('Logger', 'log', refFrom('a/svc.ts'), ctx, 0.9, 'instance-method');
  1685. const fromB = resolveMethodOnType('Logger', 'log', refFrom('b/svc.ts'), ctx, 0.9, 'instance-method');
  1686. expect(fromA?.targetNodeId).toBe('m:a');
  1687. expect(fromB?.targetNodeId).toBe('m:b');
  1688. expect(memoCalls).toBe(2);
  1689. expect(rawNameLookups).toBe(0); // memo bypasses the unbounded name fetch
  1690. });
  1691. it('the production resolver context memoizes method matches per (language, type, method)', async () => {
  1692. fs.writeFileSync(
  1693. path.join(tempDir, 'svc.ts'),
  1694. `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n`,
  1695. );
  1696. cg = await CodeGraph.init(tempDir, { index: true });
  1697. const resolver = (cg as unknown as { resolver: ReferenceResolver }).resolver;
  1698. const ctx = (resolver as unknown as { context: ResolutionContext }).context;
  1699. const first = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1700. const second = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1701. expect(first.map((n) => n.qualifiedName)).toEqual(['Logger::log']);
  1702. // Same array instance = served from the memo, not recomputed.
  1703. expect(second).toBe(first);
  1704. resolver.clearCaches();
  1705. const afterClear = ctx.getMethodMatches!('Logger', 'log', 'typescript');
  1706. expect(afterClear).not.toBe(first);
  1707. expect(afterClear.map((n) => n.qualifiedName)).toEqual(['Logger::log']);
  1708. });
  1709. it('resolveBatchYielding offers a yield checkpoint for every ref', async () => {
  1710. fs.writeFileSync(
  1711. path.join(tempDir, 'a.ts'),
  1712. `export function fnA() { return 1; }\nexport function fnB() { return fnA(); }\nexport function fnC() { return fnB(); }\n`,
  1713. );
  1714. fs.writeFileSync(
  1715. path.join(tempDir, 'b.ts'),
  1716. `import { fnA } from './a';\nexport function fnD() { return fnA(); }\n`,
  1717. );
  1718. cg = await CodeGraph.init(tempDir, { index: true });
  1719. const resolver = (cg as unknown as { resolver: ReferenceResolver }).resolver;
  1720. // `init({ index: true })` already ran resolution, so feed the batch
  1721. // directly — resolveBatchYielding takes it as an argument; whether each
  1722. // ref resolves is irrelevant to the checkpoint contract.
  1723. const refs: UnresolvedReference[] = ['fnA', 'fnB', 'nosuchFn', 'fnA', 'alsoMissing'].map((name, i) => ({
  1724. fromNodeId: `caller-${i}`,
  1725. referenceName: name,
  1726. referenceKind: 'calls',
  1727. line: i + 1,
  1728. column: 0,
  1729. filePath: 'a.ts',
  1730. language: 'typescript',
  1731. }));
  1732. let checkpoints = 0;
  1733. const countingYield = async () => { checkpoints++; };
  1734. const result = await (resolver as unknown as {
  1735. resolveBatchYielding(batch: UnresolvedReference[], maybeYield: () => Promise<void>): Promise<{ stats: { total: number } }>;
  1736. }).resolveBatchYielding(refs, countingYield);
  1737. // One checkpoint per ref: a pocket of pathologically slow refs can never
  1738. // run more than ONE ref past the yield budget before the heartbeat gets
  1739. // a window — the #1122 kill required 500.
  1740. expect(checkpoints).toBe(refs.length);
  1741. expect(result.stats.total).toBe(refs.length);
  1742. });
  1743. it('receiver inference reads lines through getFileLines when the context provides it', () => {
  1744. const loggerClass = methodNode('c:logger', 'svc.ts', 'Logger', 'Logger', 'typescript', 'class');
  1745. const logMethod = methodNode('m:log', 'svc.ts', 'Logger::log', 'log');
  1746. const otherLog = methodNode('m:other', 'other.ts', 'Other::log', 'log');
  1747. const byName: Record<string, Node[]> = {
  1748. Logger: [loggerClass],
  1749. log: [logMethod, otherLog], // ambiguous bare name → only inference can resolve
  1750. };
  1751. const lines = ['const lg = new Logger();', 'lg.log();'];
  1752. const ctx: ResolutionContext = {
  1753. getNodesInFile: () => [],
  1754. getNodesByName: (name) => byName[name] ?? [],
  1755. getNodesByQualifiedName: () => [],
  1756. getNodesByKind: () => [],
  1757. fileExists: () => false,
  1758. // Reading the raw source must not be needed when lines are provided.
  1759. readFile: () => { throw new Error('readFile must not be called when getFileLines exists'); },
  1760. getFileLines: () => lines,
  1761. getProjectRoot: () => '',
  1762. getAllFiles: () => [],
  1763. };
  1764. const ref: UnresolvedRef = {
  1765. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1766. line: 2, column: 0, filePath: 'svc.ts', language: 'typescript',
  1767. };
  1768. expect(matchMethodCall(ref, ctx)?.targetNodeId).toBe('m:log');
  1769. });
  1770. it('receiver inference skips generated/minified lines instead of regex-scanning them', () => {
  1771. const loggerClass = methodNode('c:logger', 'svc.ts', 'Logger', 'Logger', 'typescript', 'class');
  1772. const logMethod = methodNode('m:log', 'svc.ts', 'Logger::log', 'log');
  1773. const otherLog = methodNode('m:other', 'other.ts', 'Other::log', 'log');
  1774. const byName: Record<string, Node[]> = {
  1775. Logger: [loggerClass],
  1776. log: [logMethod, otherLog],
  1777. };
  1778. const ctxWithLines = (lines: string[]): ResolutionContext => ({
  1779. getNodesInFile: () => [],
  1780. getNodesByName: (name) => byName[name] ?? [],
  1781. getNodesByQualifiedName: () => [],
  1782. getNodesByKind: () => [],
  1783. fileExists: () => false,
  1784. readFile: () => null,
  1785. getFileLines: () => lines,
  1786. getProjectRoot: () => '',
  1787. getAllFiles: () => [],
  1788. });
  1789. const ref: UnresolvedRef = {
  1790. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1791. line: 1, column: 0, filePath: 'svc.ts', language: 'typescript',
  1792. };
  1793. // Control: the declaration on a normal-length line resolves.
  1794. const normal = matchMethodCall(ref, ctxWithLines(['const lg = new Logger(); lg.log();']));
  1795. expect(normal?.targetNodeId).toBe('m:log');
  1796. // The same declaration buried in a >10K-char generated/minified line is
  1797. // skipped — no resolution, and no per-ref regex pass over the huge line.
  1798. const minified = 'var pad="' + 'x'.repeat(10_000) + '";const lg = new Logger(); lg.log();';
  1799. expect(matchMethodCall(ref, ctxWithLines([minified]))).toBeNull();
  1800. });
  1801. });
  1802. describe('Local-variable receiver-type inference (#1108)', () => {
  1803. // `lg.log()` where `lg` is a local whose type is inferred from its
  1804. // declaration/initializer. Before this, only C++ resolved these; every
  1805. // other language produced no method edge. Each case is one file with a
  1806. // single Logger + a caller using a local-variable receiver — a correct
  1807. // resolution makes the caller a caller of `log`.
  1808. const cases: Array<{ lang: string; file: string; src: string }> = [
  1809. { lang: 'TypeScript (= new T)', file: 'svc.ts',
  1810. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1811. { lang: 'JavaScript (= new T)', file: 'svc.js',
  1812. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1813. { lang: 'Python (= T())', file: 'svc.py',
  1814. src: `class Logger:\n def log(self):\n return 1\ndef use():\n lg = Logger()\n return lg.log()\n` },
  1815. { lang: 'Java (T x = new T)', file: 'Svc.java',
  1816. src: `class Logger { void log() { int a = 1; } }\nclass Use { void run() { Logger lg = new Logger(); lg.log(); } }\n` },
  1817. { lang: 'C# (var x = new T)', file: 'Svc.cs',
  1818. src: `class Logger { void Log() { int a = 1; } }\nclass Use { void Run() { var lg = new Logger(); lg.Log(); } }\n` },
  1819. { lang: 'Kotlin (val x = T())', file: 'Svc.kt',
  1820. src: `class Logger { fun log(): Int { return 1 } }\nfun use(): Int { val lg = Logger(); return lg.log() }\n` },
  1821. { lang: 'Swift (let x = T())', file: 'svc.swift',
  1822. src: `class Logger { func log() -> Int { return 1 } }\nfunc use() -> Int { let lg = Logger(); return lg.log() }\n` },
  1823. { lang: 'Go (x := T{})', file: 'svc.go',
  1824. src: `package a\ntype Logger struct{}\nfunc (l Logger) Log() int { return 1 }\nfunc Use() int { lg := Logger{}; return lg.Log() }\n` },
  1825. { lang: 'Rust (let x = T{})', file: 'svc.rs',
  1826. 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` },
  1827. { lang: 'Dart (var x = T())', file: 'svc.dart',
  1828. src: `class Logger { int log() { return 1; } }\nint use() { var lg = Logger(); return lg.log(); }\n` },
  1829. { lang: 'PHP ($x = new T)', file: 'svc.php',
  1830. src: `<?php\nclass Logger { function log() { return 1; } }\nfunction useIt() { $lg = new Logger(); return $lg->log(); }\n` },
  1831. { lang: 'Scala (val x = new T)', file: 'Svc.scala',
  1832. src: `class Logger { def log(): Int = 1 }\nobject A { def use(): Int = { val lg = new Logger(); lg.log() } }\n` },
  1833. { lang: 'Ruby (x = T.new)', file: 'svc.rb',
  1834. src: `class Logger\n def log\n 1\n end\nend\ndef use\n lg = Logger.new\n lg.log\nend\n` },
  1835. { lang: 'Lua (x = T.new(); x:log())', file: 'svc.lua',
  1836. 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` },
  1837. { lang: 'Luau (x = T.new(); x:log())', file: 'svc.luau',
  1838. 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` },
  1839. { lang: 'R (x <- T$new(); x$log())', file: 'svc.R',
  1840. src: `Logger <- R6::R6Class("Logger", public = list(log = function() 1))\nuse <- function() { lg <- Logger$new(); lg$log() }\n` },
  1841. { lang: 'Pascal (var x: T; x.Method)', file: 'svc.pas',
  1842. 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` },
  1843. ];
  1844. for (const c of cases) {
  1845. it(`resolves a local-variable method call — ${c.lang}`, async () => {
  1846. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1847. cg = await CodeGraph.init(tempDir, { index: true });
  1848. cg.resolveReferences();
  1849. const logMethod = cg
  1850. .getNodesByKind('method')
  1851. .find((n) => n.name.toLowerCase() === 'log');
  1852. expect(logMethod, `${c.lang}: log method should be indexed`).toBeDefined();
  1853. // The enclosing caller resolves through the local variable to `log`.
  1854. const callers = cg.getCallers(logMethod!.id).map((x) => x.node.name);
  1855. expect(
  1856. callers.length,
  1857. `${c.lang}: log should have a caller (got [${callers.join(', ')}])`,
  1858. ).toBeGreaterThan(0);
  1859. });
  1860. }
  1861. it('Ruby: builds receiver.method and keeps Foo.new as an instantiation', async () => {
  1862. // The Ruby extractor previously took the receiver as the callee and
  1863. // dropped the method name (`lg.log()` -> a call to `lg`). Now it builds
  1864. // `lg.log`, while `Logger.new` must still record an instantiation.
  1865. fs.writeFileSync(
  1866. path.join(tempDir, 'svc.rb'),
  1867. `class Logger\n def log\n 1\n end\nend\ndef run\n lg = Logger.new\n lg.log\nend\n`,
  1868. );
  1869. cg = await CodeGraph.init(tempDir, { index: true });
  1870. cg.resolveReferences();
  1871. const run = cg.getNodesByKind('function').find((n) => n.name === 'run')!;
  1872. const logMethod = cg.getNodesByKind('method').find((n) => n.name === 'log')!;
  1873. const logger = cg.getNodesByKind('class').find((n) => n.name === 'Logger')!;
  1874. const out = cg.getOutgoingEdges(run.id);
  1875. // lg.log resolved to the method (the receiver-type inference kicked in).
  1876. expect(out.some((e) => e.kind === 'calls' && e.target === logMethod.id)).toBe(true);
  1877. // Logger.new is still an instantiation of the class.
  1878. expect(out.some((e) => e.kind === 'instantiates' && e.target === logger.id)).toBe(true);
  1879. });
  1880. it('TypeScript: infers a typed-parameter receiver, disambiguating same-named methods (#1125)', async () => {
  1881. // A typed function parameter used as a receiver — `function use(lg: Logger)`
  1882. // — never matched the old TS/JS pattern (it required a const|let|var
  1883. // prefix), so `lg.log()` fell through to no edge once a second class shared
  1884. // the method name. Two ambiguous classes are load-bearing here: a
  1885. // single-class version resolves via a same-name fallback even without
  1886. // inference, so only the collision proves type inference actually fired.
  1887. fs.writeFileSync(
  1888. path.join(tempDir, 'svc.ts'),
  1889. `class Logger { log() { return 1; } }\n` +
  1890. `class Other { log() { return 2; } }\n` +
  1891. `export function use(lg: Logger) { return lg.log(); }\n` +
  1892. `export function useOther(o: Other) { return o.log(); }\n`,
  1893. );
  1894. cg = await CodeGraph.init(tempDir, { index: true });
  1895. cg.resolveReferences();
  1896. const classes = cg.getNodesByKind('class');
  1897. const logger = classes.find((n) => n.name === 'Logger')!;
  1898. const other = classes.find((n) => n.name === 'Other')!;
  1899. const logs = cg.getNodesByKind('method').filter((n) => n.name === 'log');
  1900. expect(logs.length, 'both log methods should be indexed').toBe(2);
  1901. // Associate each same-named `log` with its class by line containment.
  1902. const inClass = (m: (typeof logs)[number], c: typeof logger) =>
  1903. m.startLine >= c.startLine && m.startLine <= (c.endLine ?? c.startLine);
  1904. const loggerLog = logs.find((m) => inClass(m, logger))!;
  1905. const otherLog = logs.find((m) => inClass(m, other))!;
  1906. expect(loggerLog, "Logger's log").toBeDefined();
  1907. expect(otherLog, "Other's log").toBeDefined();
  1908. const loggerCallers = cg.getCallers(loggerLog.id).map((x) => x.node.name);
  1909. const otherCallers = cg.getCallers(otherLog.id).map((x) => x.node.name);
  1910. // Each typed-param call routes to its OWN class's method, not the other's.
  1911. expect(loggerCallers).toContain('use');
  1912. expect(loggerCallers).not.toContain('useOther');
  1913. expect(otherCallers).toContain('useOther');
  1914. expect(otherCallers).not.toContain('use');
  1915. });
  1916. // The same typed-parameter gap existed in every language whose pattern set
  1917. // only matched keyword-anchored locals (let/var/:=/= new), not the bare
  1918. // parameter form — Rust, Go, Dart, PHP (#1125). Each case: two classes
  1919. // sharing a method name + two functions taking one as a typed param; a
  1920. // correct fix routes each call to its OWN type's method (the collision is
  1921. // load-bearing — a single class resolves via the same-name fallback either
  1922. // way). Method↔type association is by qualifiedName, robust where the method
  1923. // lives outside the type's line range (Rust `impl`, Go method decl).
  1924. const typedParamCases: Array<{
  1925. lang: string; file: string; method: string; callerA: string; callerB: string; src: string;
  1926. }> = [
  1927. { lang: 'Rust (fn f(x: &T))', file: 'svc.rs', method: 'log', callerA: 'use_it', callerB: 'use_other',
  1928. 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` },
  1929. { lang: 'Go (func f(x T))', file: 'svc.go', method: 'Log', callerA: 'UseIt', callerB: 'UseOther',
  1930. 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` },
  1931. { lang: 'Dart (T f(U x))', file: 'svc.dart', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1932. 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` },
  1933. { lang: 'PHP (f(T $x))', file: 'svc.php', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1934. 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` },
  1935. ];
  1936. for (const c of typedParamCases) {
  1937. it(`infers a typed-parameter receiver, disambiguating same-named methods — ${c.lang} (#1125)`, async () => {
  1938. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1939. cg = await CodeGraph.init(tempDir, { index: true });
  1940. cg.resolveReferences();
  1941. const methods = cg.getNodesByKind('method').filter((n) => n.name === c.method);
  1942. expect(methods.length, `${c.lang}: both ${c.method} methods indexed`).toBe(2);
  1943. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1944. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1945. expect(loggerLog, `${c.lang}: Logger's ${c.method}`).toBeDefined();
  1946. expect(otherLog, `${c.lang}: Other's ${c.method}`).toBeDefined();
  1947. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1948. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1949. expect(loggerCallers, `${c.lang}: Logger callers`).toContain(c.callerA);
  1950. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain(c.callerB);
  1951. expect(otherCallers, `${c.lang}: Other callers`).toContain(c.callerB);
  1952. expect(otherCallers, `${c.lang}: Other callers`).not.toContain(c.callerA);
  1953. });
  1954. }
  1955. // Lua/Luau: a PascalCase method call (`lg:Log()`, the Roblox convention)
  1956. // is the identical `receiver:Name` shape as a Luau type annotation, so it
  1957. // self-matched the annotation pattern on the call's own line and inferred
  1958. // "type = Log" (#1124). Two things are load-bearing in these fixtures:
  1959. // the declaration sits on an EARLIER line than the call (on one line,
  1960. // pattern order resolves it — the `.new` pattern wins first), and TWO
  1961. // classes share the method name (a single class resolves via the
  1962. // same-name fallback even when inference misfires). Luau's `useLogger`
  1963. // takes a typed param instead of calling `.new()`, pinning that the
  1964. // gated pattern still matches a genuine annotation.
  1965. const pascalMethodCases: Array<{ lang: string; file: string; src: string }> = [
  1966. { lang: 'Lua', file: 'svc.lua',
  1967. 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` },
  1968. { lang: 'Luau', file: 'svc.luau',
  1969. 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` },
  1970. ];
  1971. for (const c of pascalMethodCases) {
  1972. it(`resolves a PascalCase method call without self-matching the annotation pattern — ${c.lang} (#1124)`, async () => {
  1973. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1974. cg = await CodeGraph.init(tempDir, { index: true });
  1975. cg.resolveReferences();
  1976. const methods = cg.getNodesByKind('method').filter((n) => n.name === 'Log');
  1977. expect(methods.length, `${c.lang}: both Log methods indexed`).toBe(2);
  1978. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1979. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1980. expect(loggerLog, `${c.lang}: Logger's Log`).toBeDefined();
  1981. expect(otherLog, `${c.lang}: Other's Log`).toBeDefined();
  1982. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1983. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1984. expect(loggerCallers, `${c.lang}: Logger callers`).toContain('useLogger');
  1985. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain('useOther');
  1986. expect(otherCallers, `${c.lang}: Other callers`).toContain('useOther');
  1987. expect(otherCallers, `${c.lang}: Other callers`).not.toContain('useLogger');
  1988. });
  1989. }
  1990. });
  1991. describe('Name Matcher: kind bias for new ref kinds', () => {
  1992. const baseContext = (candidates: Node[]): ResolutionContext => ({
  1993. getNodesInFile: () => [],
  1994. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1995. getNodesByQualifiedName: () => [],
  1996. getNodesByKind: () => [],
  1997. fileExists: () => true,
  1998. readFile: () => null,
  1999. getProjectRoot: () => '/test',
  2000. getAllFiles: () => [],
  2001. getNodesByLowerName: () => [],
  2002. getImportMappings: () => [],
  2003. });
  2004. it('prefers a class candidate over a function for `instantiates` refs', () => {
  2005. // A class and a function share a name across the codebase.
  2006. // Without the kind bias, the function (which gets the +25 `calls`
  2007. // bonus historically applied to all candidates of that kind) would
  2008. // win. Now the instantiates branch reverses it.
  2009. const fn: Node = {
  2010. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  2011. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  2012. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2013. };
  2014. const cls: Node = {
  2015. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  2016. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  2017. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2018. };
  2019. const ref = {
  2020. fromNodeId: 'func:main.ts:bootstrap:1',
  2021. referenceName: 'Logger',
  2022. referenceKind: 'instantiates' as const,
  2023. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  2024. };
  2025. const result = matchReference(ref, baseContext([fn, cls]));
  2026. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  2027. });
  2028. it('prefers a union candidate over a function for `instantiates` refs', () => {
  2029. const fn: Node = {
  2030. id: 'func:packet.cpp:Packet:5', kind: 'function', name: 'Packet',
  2031. qualifiedName: 'packet.cpp::Packet', filePath: 'packet.cpp', language: 'cpp',
  2032. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2033. };
  2034. const union: Node = {
  2035. id: 'union:packet.hpp:Packet:10', kind: 'union', name: 'Packet',
  2036. qualifiedName: 'packet.hpp::Packet', filePath: 'packet.hpp', language: 'cpp',
  2037. startLine: 10, endLine: 14, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2038. };
  2039. const ref = {
  2040. fromNodeId: 'func:main.cpp:initialize:1',
  2041. referenceName: 'Packet',
  2042. referenceKind: 'instantiates' as const,
  2043. line: 5, column: 0, filePath: 'main.cpp', language: 'cpp' as const,
  2044. };
  2045. const result = matchReference(ref, baseContext([fn, union]));
  2046. expect(result?.targetNodeId).toBe('union:packet.hpp:Packet:10');
  2047. });
  2048. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  2049. const variable: Node = {
  2050. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  2051. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  2052. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2053. };
  2054. const decorator: Node = {
  2055. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  2056. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  2057. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2058. };
  2059. const ref = {
  2060. fromNodeId: 'class:svc.ts:UserService:1',
  2061. referenceName: 'Inject',
  2062. referenceKind: 'decorates' as const,
  2063. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  2064. };
  2065. const result = matchReference(ref, baseContext([variable, decorator]));
  2066. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  2067. });
  2068. });
  2069. describe('tsconfig path aliases', () => {
  2070. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  2071. // Two same-named exports in different directories. Without alias
  2072. // resolution, name-matcher would pick whichever it finds first;
  2073. // with alias resolution, the import path uniquely picks one.
  2074. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  2075. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  2076. fs.writeFileSync(
  2077. path.join(tempDir, 'src/utils/format.ts'),
  2078. `export function pickMe(): number { return 1; }\n`
  2079. );
  2080. fs.writeFileSync(
  2081. path.join(tempDir, 'src/legacy/format.ts'),
  2082. `export function pickMe(): number { return 99; }\n`
  2083. );
  2084. fs.writeFileSync(
  2085. path.join(tempDir, 'src/main.ts'),
  2086. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  2087. );
  2088. fs.writeFileSync(
  2089. path.join(tempDir, 'tsconfig.json'),
  2090. JSON.stringify({
  2091. compilerOptions: {
  2092. baseUrl: './src',
  2093. paths: { '@utils/*': ['utils/*'] },
  2094. },
  2095. })
  2096. );
  2097. cg = await CodeGraph.init(tempDir, { index: true });
  2098. cg.resolveReferences();
  2099. // The two pickMe nodes live in different files. The aliased
  2100. // import should attach the call edge to the @utils-mapped one,
  2101. // not the legacy duplicate.
  2102. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  2103. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  2104. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  2105. expect(utilsNode).toBeDefined();
  2106. expect(legacyNode).toBeDefined();
  2107. const utilsCallers = cg.getCallers(utilsNode!.id);
  2108. const legacyCallers = cg.getCallers(legacyNode!.id);
  2109. expect(utilsCallers.length).toBeGreaterThan(0);
  2110. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2111. // The legacy node should NOT have a caller from src/main.ts —
  2112. // the alias correctly picked the utils version.
  2113. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  2114. });
  2115. it('falls back gracefully when tsconfig is absent', async () => {
  2116. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2117. fs.writeFileSync(
  2118. path.join(tempDir, 'src/a.ts'),
  2119. `export function aFn(): void {}\n`
  2120. );
  2121. fs.writeFileSync(
  2122. path.join(tempDir, 'src/b.ts'),
  2123. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  2124. );
  2125. cg = await CodeGraph.init(tempDir, { index: true });
  2126. // No tsconfig present — index should still complete and the
  2127. // relative-import-based call edge should be created.
  2128. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  2129. expect(aFn).toBeDefined();
  2130. const callers = cg.getCallers(aFn!.id);
  2131. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  2132. });
  2133. });
  2134. describe('re-export chain following', () => {
  2135. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  2136. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  2137. // Without chain following, `signIn` resolves to nothing because
  2138. // none of the barrel files declare it directly.
  2139. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  2140. fs.writeFileSync(
  2141. path.join(tempDir, 'src/services/auth.ts'),
  2142. `export function signIn(): void {}\n`
  2143. );
  2144. fs.writeFileSync(
  2145. path.join(tempDir, 'src/services/index.ts'),
  2146. `export { signIn } from './auth';\n`
  2147. );
  2148. fs.writeFileSync(
  2149. path.join(tempDir, 'src/all.ts'),
  2150. `export * from './services/index';\n`
  2151. );
  2152. fs.writeFileSync(
  2153. path.join(tempDir, 'src/main.ts'),
  2154. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  2155. );
  2156. cg = await CodeGraph.init(tempDir, { index: true });
  2157. cg.resolveReferences();
  2158. const signInNode = cg
  2159. .getNodesByKind('function')
  2160. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  2161. expect(signInNode).toBeDefined();
  2162. const callers = cg.getCallers(signInNode!.id);
  2163. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2164. });
  2165. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  2166. // The chase has to look up `foo` in the upstream module even
  2167. // though the importer asked for `bar` — exercises the rename
  2168. // branch of findExportedSymbol.
  2169. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2170. fs.writeFileSync(
  2171. path.join(tempDir, 'src/auth.ts'),
  2172. `export function signIn(): void {}\n`
  2173. );
  2174. fs.writeFileSync(
  2175. path.join(tempDir, 'src/index.ts'),
  2176. `export { signIn as login } from './auth';\n`
  2177. );
  2178. fs.writeFileSync(
  2179. path.join(tempDir, 'src/main.ts'),
  2180. `import { login } from './index';\nexport function go(): void { login(); }\n`
  2181. );
  2182. cg = await CodeGraph.init(tempDir, { index: true });
  2183. cg.resolveReferences();
  2184. const signInNode = cg
  2185. .getNodesByKind('function')
  2186. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  2187. expect(signInNode).toBeDefined();
  2188. const callers = cg.getCallers(signInNode!.id);
  2189. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2190. });
  2191. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  2192. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  2193. // .svelte component (extracted as kind 'component', the default
  2194. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  2195. // component's real name (`RealButton`) so the name-matcher fallback
  2196. // can't coincidentally connect them — the only path to the edge is
  2197. // the import-chase, which must match a `component` (not just
  2198. // function/class) for the default export. Otherwise the
  2199. // consumer↔component edge is never created and `callers` returns a
  2200. // false 0.
  2201. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2202. fs.writeFileSync(
  2203. path.join(tempDir, 'src/lib/RealButton.svelte'),
  2204. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2205. );
  2206. fs.writeFileSync(
  2207. path.join(tempDir, 'src/lib/index.ts'),
  2208. `export { default as Foo } from './RealButton.svelte';\n`
  2209. );
  2210. fs.writeFileSync(
  2211. path.join(tempDir, 'src/Bar.svelte'),
  2212. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  2213. );
  2214. cg = await CodeGraph.init(tempDir, { index: true });
  2215. cg.resolveReferences();
  2216. const fooNode = cg
  2217. .getNodesByKind('component')
  2218. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  2219. expect(fooNode).toBeDefined();
  2220. const callers = cg.getCallers(fooNode!.id);
  2221. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  2222. });
  2223. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  2224. // The canonical Astro shape: a page imports a layout/component in
  2225. // frontmatter and uses it as a template tag; the component's template
  2226. // calls an imported .ts util. Both hops must produce graph edges or
  2227. // an Astro project is invisible to callers/impact.
  2228. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  2229. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  2230. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  2231. fs.writeFileSync(
  2232. path.join(tempDir, 'src/utils/format.ts'),
  2233. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  2234. );
  2235. fs.writeFileSync(
  2236. path.join(tempDir, 'src/components/PostCard.astro'),
  2237. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  2238. );
  2239. fs.writeFileSync(
  2240. path.join(tempDir, 'src/pages/index.astro'),
  2241. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  2242. );
  2243. cg = await CodeGraph.init(tempDir, { index: true });
  2244. cg.resolveReferences();
  2245. // Hop 1: page → component (template tag through the frontmatter import)
  2246. const cardNode = cg
  2247. .getNodesByKind('component')
  2248. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  2249. expect(cardNode).toBeDefined();
  2250. const cardCallers = cg.getCallers(cardNode!.id);
  2251. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  2252. // Hop 2: component template call → .ts util
  2253. const fmtNode = cg
  2254. .getNodesByKind('function')
  2255. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  2256. expect(fmtNode).toBeDefined();
  2257. const fmtCallers = cg.getCallers(fmtNode!.id);
  2258. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  2259. });
  2260. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  2261. // `import { helper } from '.'` (or './') must map to the
  2262. // directory's index.ts before the re-export chase can run. The
  2263. // barrel renames `realHelper` → `helper` so the name-matcher can't
  2264. // mask a path-resolution failure: only the bare-dir resolution +
  2265. // rename chase can connect the edge.
  2266. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2267. fs.writeFileSync(
  2268. path.join(tempDir, 'src/util.ts'),
  2269. `export function realHelper(): void {}\n`
  2270. );
  2271. fs.writeFileSync(
  2272. path.join(tempDir, 'src/index.ts'),
  2273. `export { realHelper as helper } from './util';\n`
  2274. );
  2275. fs.writeFileSync(
  2276. path.join(tempDir, 'src/main.ts'),
  2277. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  2278. );
  2279. fs.writeFileSync(
  2280. path.join(tempDir, 'src/main2.ts'),
  2281. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  2282. );
  2283. cg = await CodeGraph.init(tempDir, { index: true });
  2284. cg.resolveReferences();
  2285. const helperNode = cg
  2286. .getNodesByKind('function')
  2287. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  2288. expect(helperNode).toBeDefined();
  2289. const callers = cg.getCallers(helperNode!.id);
  2290. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2291. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  2292. });
  2293. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  2294. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  2295. // `widgets/` subdir index, which re-exports a .svelte component.
  2296. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  2297. // only workspace-package resolution can connect the edge.
  2298. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  2299. fs.writeFileSync(
  2300. path.join(tempDir, 'package.json'),
  2301. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  2302. );
  2303. fs.writeFileSync(
  2304. path.join(tempDir, 'packages/ui/package.json'),
  2305. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  2306. );
  2307. fs.writeFileSync(
  2308. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  2309. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2310. );
  2311. fs.writeFileSync(
  2312. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  2313. `export { default as Thing } from './Widget.svelte';\n`
  2314. );
  2315. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  2316. fs.writeFileSync(
  2317. path.join(tempDir, 'app/App.svelte'),
  2318. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  2319. );
  2320. cg = await CodeGraph.init(tempDir, { index: true });
  2321. cg.resolveReferences();
  2322. const buttonNode = cg
  2323. .getNodesByKind('component')
  2324. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  2325. expect(buttonNode).toBeDefined();
  2326. const callers = cg.getCallers(buttonNode!.id);
  2327. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  2328. });
  2329. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  2330. // The same import-resolution gaps (no SFC import mappings, no SFC
  2331. // extension list, barrel parsed in the consumer's language) broke
  2332. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  2333. // The barrel renames `realRun` → `run` so only the import-chase (not
  2334. // the name-matcher) can connect the call.
  2335. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2336. fs.writeFileSync(
  2337. path.join(tempDir, 'src/util.ts'),
  2338. `export function realRun(): void {}\n`
  2339. );
  2340. fs.writeFileSync(
  2341. path.join(tempDir, 'src/index.ts'),
  2342. `export { realRun as run } from './util';\n`
  2343. );
  2344. fs.writeFileSync(
  2345. path.join(tempDir, 'src/App.vue'),
  2346. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  2347. );
  2348. cg = await CodeGraph.init(tempDir, { index: true });
  2349. cg.resolveReferences();
  2350. const runNode = cg
  2351. .getNodesByKind('function')
  2352. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  2353. expect(runNode).toBeDefined();
  2354. const callers = cg.getCallers(runNode!.id);
  2355. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2356. });
  2357. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  2358. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  2359. // component re-exported under an alias (`Thing`) that differs from its
  2360. // real name (`Widget`), and the consumer uses it ONLY in markup
  2361. // (`<Thing />`). Requires both the new template-tag extraction AND the
  2362. // barrel default-export chase to connect the edge.
  2363. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2364. fs.writeFileSync(
  2365. path.join(tempDir, 'src/lib/Widget.vue'),
  2366. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  2367. );
  2368. fs.writeFileSync(
  2369. path.join(tempDir, 'src/lib/index.ts'),
  2370. `export { default as Thing } from './Widget.vue';\n`
  2371. );
  2372. fs.writeFileSync(
  2373. path.join(tempDir, 'src/App.vue'),
  2374. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  2375. );
  2376. cg = await CodeGraph.init(tempDir, { index: true });
  2377. cg.resolveReferences();
  2378. const widgetNode = cg
  2379. .getNodesByKind('component')
  2380. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  2381. expect(widgetNode).toBeDefined();
  2382. const callers = cg.getCallers(widgetNode!.id);
  2383. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2384. });
  2385. });
  2386. describe('Literal receivers and nested-local scope (#1230)', () => {
  2387. // Two stacked fabrications: `", ".join(...)` (a builtin on a string
  2388. // literal) exact-matched a project function named `join` — one that was
  2389. // moreover nested inside a DIFFERENT function and thus lexically
  2390. // unreachable. Literal receivers now emit no call ref at all, and
  2391. // exact-match refuses candidates nested in a function the ref isn't in.
  2392. it("str-literal builtin calls don't bind to project symbols; nested locals only resolve from inside their container", async () => {
  2393. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1230-'));
  2394. try {
  2395. fs.writeFileSync(
  2396. path.join(tmpDir, 'repro.py'),
  2397. `def format_fields(values):
  2398. def join(vals):
  2399. return "-".join(sorted(vals))
  2400. return join(values)
  2401. def report_missing(unresolved):
  2402. missing_list = ", ".join(sorted(unresolved))
  2403. return f"Could not resolve: {missing_list}"
  2404. `
  2405. );
  2406. const cg = CodeGraph.initSync(tmpDir);
  2407. await cg.indexAll();
  2408. const join = (await cg.searchNodes('join', { limit: 5 })).find(
  2409. (r) => r.node.kind === 'function' && r.node.name === 'join'
  2410. );
  2411. expect(join).toBeDefined();
  2412. // Exactly one caller: the enclosing format_fields. Neither
  2413. // report_missing (literal receiver) nor join itself (its own literal
  2414. // "-".join) may appear.
  2415. const callers = await cg.getCallers(join!.node.id);
  2416. expect(callers.map((c) => c.node.name)).toEqual(['format_fields']);
  2417. // report_missing has zero project callees.
  2418. const reportMissing = (await cg.searchNodes('report_missing', { limit: 5 })).find(
  2419. (r) => r.node.kind === 'function'
  2420. );
  2421. const callees = await cg.getCallees(reportMissing!.node.id);
  2422. expect(callees.filter((c) => c.node.name === 'join')).toHaveLength(0);
  2423. cg.close();
  2424. } finally {
  2425. fs.rmSync(tmpDir, { recursive: true, force: true });
  2426. }
  2427. }, 30000);
  2428. });
  2429. describe('Go field-chain receiver calls (#1276)', () => {
  2430. // `target.conn.Exec(...)` where `conn *sql.DB` used to emit a BARE `Exec`
  2431. // ref, which exact-matched the only local `Exec` — an unrelated
  2432. // interface's method — fabricating an internal dependency. Chained Go
  2433. // receivers now resolve exclusively via validated field-hop inference:
  2434. // external field types produce NO edge; in-project ones produce the
  2435. // correct edge (new recall).
  2436. it('external receiver types produce no edge; in-project field chains resolve correctly', async () => {
  2437. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1276-'));
  2438. try {
  2439. fs.writeFileSync(path.join(tmpDir, 'go.mod'), 'module example.com/app\n\ngo 1.22\n');
  2440. fs.mkdirSync(path.join(tmpDir, 'flow'));
  2441. fs.writeFileSync(
  2442. path.join(tmpDir, 'flow', 'flow.go'),
  2443. `package flow
  2444. import "database/sql"
  2445. type InternalStore interface {
  2446. Exec(string, ...any) (sql.Result, error)
  2447. QueryRow(string, ...any) *sql.Row
  2448. }
  2449. type Target struct{ conn *sql.DB }
  2450. func (target *Target) Write() error {
  2451. _, err := target.conn.Exec("insert")
  2452. return err
  2453. }
  2454. func (target *Target) Read() *sql.Row {
  2455. return target.conn.QueryRow("select")
  2456. }
  2457. type Store struct{}
  2458. func (s *Store) Put(key string) {}
  2459. type Repo struct{ db *Store }
  2460. func (r *Repo) Save() {
  2461. r.db.Put("k")
  2462. }
  2463. `
  2464. );
  2465. const cg = CodeGraph.initSync(tmpDir);
  2466. await cg.indexAll();
  2467. // The unrelated local interface's methods have NO callers — the
  2468. // external sql.DB calls must not bind to them.
  2469. const execDecl = (await cg.searchNodes('Exec', { limit: 10 })).find(
  2470. (r) => r.node.kind === 'method'
  2471. );
  2472. if (execDecl) {
  2473. const execCallers = await cg.getCallers(execDecl.node.id);
  2474. expect(execCallers.map((c) => c.node.name)).not.toContain('Write');
  2475. }
  2476. const qrDecl = (await cg.searchNodes('QueryRow', { limit: 10 })).find(
  2477. (r) => r.node.kind === 'method'
  2478. );
  2479. if (qrDecl) {
  2480. const qrCallers = await cg.getCallers(qrDecl.node.id);
  2481. expect(qrCallers.map((c) => c.node.name)).not.toContain('Read');
  2482. }
  2483. // The in-project field chain resolves (validated), gaining an edge the
  2484. // bare-name era never produced.
  2485. const put = (await cg.searchNodes('Put', { limit: 10 })).find(
  2486. (r) => r.node.kind === 'method' && r.node.qualifiedName?.includes('Store')
  2487. );
  2488. expect(put).toBeDefined();
  2489. const putCallers = await cg.getCallers(put!.node.id);
  2490. expect(putCallers.map((c) => c.node.name)).toContain('Save');
  2491. cg.close();
  2492. } finally {
  2493. fs.rmSync(tmpDir, { recursive: true, force: true });
  2494. }
  2495. }, 30000);
  2496. it('unexported field types resolve; stdlib-qualified types never bind a same-named local decoy', async () => {
  2497. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1276b-'));
  2498. try {
  2499. fs.writeFileSync(path.join(tmpDir, 'go.mod'), 'module example.com/b\n\ngo 1.22\n');
  2500. fs.writeFileSync(
  2501. path.join(tmpDir, 'm.go'),
  2502. `package m
  2503. import "net/http"
  2504. type node struct{}
  2505. func (n *node) InsertRoute(path string) {}
  2506. // A local type sharing the stdlib interface's name — the decoy the
  2507. // package-qualifier gate exists for.
  2508. type Handler func()
  2509. func (h Handler) ServeHTTP() {}
  2510. type Mux struct {
  2511. // the tree router lives below this comment (the comment must not
  2512. // donate a field type)
  2513. handler http.Handler
  2514. tree *node
  2515. }
  2516. func (mx *Mux) handle(path string) {
  2517. mx.tree.InsertRoute(path)
  2518. }
  2519. func (mx *Mux) dispatch() {
  2520. mx.handler.ServeHTTP(nil, nil)
  2521. }
  2522. `
  2523. );
  2524. const cg = CodeGraph.initSync(tmpDir);
  2525. await cg.indexAll();
  2526. // Unexported in-package field type: chain resolves (chi's mx.tree shape),
  2527. // and the doc comment above the field donates nothing.
  2528. const insert = (await cg.searchNodes('InsertRoute', { limit: 5 })).find(
  2529. (r) => r.node.kind === 'method'
  2530. );
  2531. expect(insert).toBeDefined();
  2532. const insertCallers = await cg.getCallers(insert!.node.id);
  2533. expect(insertCallers.map((c) => c.node.name)).toContain('handle');
  2534. // `handler http.Handler` is stdlib — the call must NOT bind to the
  2535. // local decoy `Handler.ServeHTTP`.
  2536. const serve = (await cg.searchNodes('ServeHTTP', { limit: 5 })).find(
  2537. (r) => r.node.kind === 'method'
  2538. );
  2539. if (serve) {
  2540. const serveCallers = await cg.getCallers(serve.node.id);
  2541. expect(serveCallers.map((c) => c.node.name)).not.toContain('dispatch');
  2542. }
  2543. cg.close();
  2544. } finally {
  2545. fs.rmSync(tmpDir, { recursive: true, force: true });
  2546. }
  2547. }, 30000);
  2548. });
  2549. describe('Imported singleton instance-method calls (#1292)', () => {
  2550. // `reproStore.notifyJoinGuildStatus()` after `import { reproStore }` used
  2551. // to emit its calls edge to the CONSTANT (resolvedBy:'import'), while the
  2552. // identical call in the defining file resolved to the method — so callers
  2553. // of the method missed every cross-file use. The import path now infers
  2554. // the value's type from its own declaration and resolves the member on it.
  2555. it('cross-file call through an imported singleton resolves to the class method', async () => {
  2556. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1292-'));
  2557. try {
  2558. fs.mkdirSync(path.join(tmpDir, 'src'));
  2559. fs.writeFileSync(
  2560. path.join(tmpDir, 'src', 'store.ts'),
  2561. `export class ReproStore {
  2562. notifyJoinGuildStatus(): void {
  2563. console.log('notified');
  2564. }
  2565. }
  2566. export const reproStore = new ReproStore();
  2567. export function callInDefinitionFile(): void {
  2568. reproStore.notifyJoinGuildStatus();
  2569. }
  2570. `
  2571. );
  2572. fs.writeFileSync(
  2573. path.join(tmpDir, 'src', 'caller.ts'),
  2574. `import { reproStore } from './store';
  2575. export function callFromImportedFile(): void {
  2576. reproStore.notifyJoinGuildStatus();
  2577. }
  2578. `
  2579. );
  2580. const cg = CodeGraph.initSync(tmpDir);
  2581. await cg.indexAll();
  2582. const method = (await cg.searchNodes('notifyJoinGuildStatus', { limit: 5 })).find(
  2583. (r) => r.node.kind === 'method'
  2584. );
  2585. expect(method).toBeDefined();
  2586. // BOTH functions call the method — the cross-file one included.
  2587. const callers = await cg.getCallers(method!.node.id);
  2588. const callerNames = callers.map((c) => c.node.name).sort();
  2589. expect(callerNames).toContain('callInDefinitionFile');
  2590. expect(callerNames).toContain('callFromImportedFile');
  2591. cg.close();
  2592. } finally {
  2593. fs.rmSync(tmpDir, { recursive: true, force: true });
  2594. }
  2595. }, 30000);
  2596. });
  2597. describe('C++ namespace-qualified static method calls to out-of-line definitions (#1291)', () => {
  2598. // The issue's exact shape: nested types + out-of-line static method
  2599. // definition inside `namespace simulator { }` in the .cpp, called via the
  2600. // fully-qualified path from a different file. The definition's
  2601. // qualifiedName previously dropped the namespace (`ManifestStartup::Apply`
  2602. // vs the class's `simulator::ManifestStartup`), so `callers` came up empty.
  2603. it('resolves simulator::ManifestStartup::Apply(...) from another file', async () => {
  2604. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1291-'));
  2605. try {
  2606. fs.writeFileSync(
  2607. path.join(tmpDir, 'manifest_startup.h'),
  2608. `#pragma once
  2609. namespace simulator {
  2610. class ManifestStartup {
  2611. public:
  2612. struct Input { int a; };
  2613. struct Output { int b; };
  2614. static Output Apply(const Input& input);
  2615. };
  2616. }
  2617. `
  2618. );
  2619. fs.writeFileSync(
  2620. path.join(tmpDir, 'manifest_startup.cpp'),
  2621. `#include "manifest_startup.h"
  2622. namespace simulator {
  2623. ManifestStartup::Output ManifestStartup::Apply(const Input& input) {
  2624. return Output{input.a};
  2625. }
  2626. }
  2627. `
  2628. );
  2629. fs.writeFileSync(
  2630. path.join(tmpDir, 'main.cpp'),
  2631. `#include "manifest_startup.h"
  2632. int run() {
  2633. const auto manifest_result = simulator::ManifestStartup::Apply({1});
  2634. return manifest_result.b;
  2635. }
  2636. `
  2637. );
  2638. const cg = CodeGraph.initSync(tmpDir);
  2639. await cg.indexAll();
  2640. const applyDefs = (await cg.searchNodes('Apply', { limit: 20 })).filter(
  2641. (r) => r.node.name === 'Apply' && r.node.kind === 'method'
  2642. );
  2643. expect(applyDefs.length).toBeGreaterThan(0);
  2644. const def = applyDefs.find((r) => r.node.filePath.endsWith('manifest_startup.cpp'));
  2645. expect(def).toBeDefined();
  2646. expect(def!.node.qualifiedName).toBe('simulator::ManifestStartup::Apply');
  2647. // The qualified cross-file call resolves: run() is a caller of Apply.
  2648. const callers = await cg.getCallers(def!.node.id);
  2649. expect(callers.map((c) => c.node.name)).toContain('run');
  2650. cg.close();
  2651. } finally {
  2652. fs.rmSync(tmpDir, { recursive: true, force: true });
  2653. }
  2654. }, 30000);
  2655. });
  2656. describe('C/C++ Import Resolution', () => {
  2657. afterEach(() => {
  2658. clearCppIncludeDirCache();
  2659. });
  2660. it('should resolve C include to header in same directory', () => {
  2661. const context: ResolutionContext = {
  2662. getNodesInFile: () => [],
  2663. getNodesByName: () => [],
  2664. getNodesByQualifiedName: () => [],
  2665. getNodesByKind: () => [],
  2666. fileExists: (p) => p === 'utils.h',
  2667. readFile: () => null,
  2668. getProjectRoot: () => '',
  2669. getAllFiles: () => ['utils.h', 'main.c'],
  2670. };
  2671. const result = resolveImportPath(
  2672. 'utils.h',
  2673. 'main.c',
  2674. 'c',
  2675. context
  2676. );
  2677. expect(result).toBe('utils.h');
  2678. });
  2679. it('should resolve C++ include with .hpp extension', () => {
  2680. const context: ResolutionContext = {
  2681. getNodesInFile: () => [],
  2682. getNodesByName: () => [],
  2683. getNodesByQualifiedName: () => [],
  2684. getNodesByKind: () => [],
  2685. fileExists: (p) => p === 'include/myclass.hpp',
  2686. readFile: () => null,
  2687. getProjectRoot: () => '',
  2688. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2689. getCppIncludeDirs: () => ['include'],
  2690. };
  2691. const result = resolveImportPath(
  2692. 'myclass.hpp',
  2693. 'src/main.cpp',
  2694. 'cpp',
  2695. context
  2696. );
  2697. expect(result).toBe('include/myclass.hpp');
  2698. });
  2699. it('should resolve include with subdirectory path', () => {
  2700. const context: ResolutionContext = {
  2701. getNodesInFile: () => [],
  2702. getNodesByName: () => [],
  2703. getNodesByQualifiedName: () => [],
  2704. getNodesByKind: () => [],
  2705. fileExists: (p) => p === 'utils/helpers.h',
  2706. readFile: () => null,
  2707. getProjectRoot: () => '',
  2708. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  2709. };
  2710. const result = resolveImportPath(
  2711. 'utils/helpers.h',
  2712. 'main.c',
  2713. 'c',
  2714. context
  2715. );
  2716. expect(result).toBe('utils/helpers.h');
  2717. });
  2718. it('should resolve include via include directories', () => {
  2719. const context: ResolutionContext = {
  2720. getNodesInFile: () => [],
  2721. getNodesByName: () => [],
  2722. getNodesByQualifiedName: () => [],
  2723. getNodesByKind: () => [],
  2724. fileExists: (p) => p === 'include/myheader.h',
  2725. readFile: () => null,
  2726. getProjectRoot: () => '',
  2727. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  2728. getCppIncludeDirs: () => ['include'],
  2729. };
  2730. const result = resolveImportPath(
  2731. 'myheader.h',
  2732. 'src/main.cpp',
  2733. 'cpp',
  2734. context
  2735. );
  2736. expect(result).toBe('include/myheader.h');
  2737. });
  2738. it('should resolve include trying multiple extensions', () => {
  2739. const context: ResolutionContext = {
  2740. getNodesInFile: () => [],
  2741. getNodesByName: () => [],
  2742. getNodesByQualifiedName: () => [],
  2743. getNodesByKind: () => [],
  2744. // myclass.h does not exist, but myclass.hpp does
  2745. fileExists: (p) => p === 'include/myclass.hpp',
  2746. readFile: () => null,
  2747. getProjectRoot: () => '',
  2748. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2749. getCppIncludeDirs: () => ['include'],
  2750. };
  2751. const result = resolveImportPath(
  2752. 'myclass',
  2753. 'src/main.cpp',
  2754. 'cpp',
  2755. context
  2756. );
  2757. expect(result).toBe('include/myclass.hpp');
  2758. });
  2759. it('should return null for system headers', () => {
  2760. const context: ResolutionContext = {
  2761. getNodesInFile: () => [],
  2762. getNodesByName: () => [],
  2763. getNodesByQualifiedName: () => [],
  2764. getNodesByKind: () => [],
  2765. fileExists: () => true,
  2766. readFile: () => null,
  2767. getProjectRoot: () => '',
  2768. getAllFiles: () => [],
  2769. };
  2770. // C standard library header
  2771. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  2772. // C++ standard library header
  2773. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  2774. // C++ C-wrapper header
  2775. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  2776. });
  2777. it('should return null for single-component third-party paths that cannot be resolved', () => {
  2778. const context: ResolutionContext = {
  2779. getNodesInFile: () => [],
  2780. getNodesByName: () => [],
  2781. getNodesByQualifiedName: () => [],
  2782. getNodesByKind: () => [],
  2783. fileExists: () => false,
  2784. readFile: () => null,
  2785. getProjectRoot: () => '',
  2786. getAllFiles: () => [],
  2787. getCppIncludeDirs: () => [],
  2788. };
  2789. // Third-party bare header without path — not resolvable, returns null
  2790. const result = resolveImportPath(
  2791. 'openssl/ssl.h',
  2792. 'main.cpp',
  2793. 'cpp',
  2794. context
  2795. );
  2796. expect(result).toBeNull();
  2797. });
  2798. it('should not filter project headers with path separators', () => {
  2799. const context: ResolutionContext = {
  2800. getNodesInFile: () => [],
  2801. getNodesByName: () => [],
  2802. getNodesByQualifiedName: () => [],
  2803. getNodesByKind: () => [],
  2804. fileExists: (p) => p === 'mylib/utils.h',
  2805. readFile: () => null,
  2806. getProjectRoot: () => '',
  2807. getAllFiles: () => ['mylib/utils.h'],
  2808. };
  2809. // Path with separator should NOT be filtered as external
  2810. const result = resolveImportPath(
  2811. 'mylib/utils.h',
  2812. 'main.c',
  2813. 'c',
  2814. context
  2815. );
  2816. expect(result).toBe('mylib/utils.h');
  2817. });
  2818. it('should extract C/C++ import mappings from #include directives', () => {
  2819. const code = `#include <iostream>
  2820. #include "myheader.h"
  2821. #include "utils/helpers.hpp"`;
  2822. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  2823. expect(mappings.length).toBe(3);
  2824. expect(mappings[0]).toEqual({
  2825. localName: 'iostream',
  2826. exportedName: '*',
  2827. source: 'iostream',
  2828. isDefault: false,
  2829. isNamespace: true,
  2830. });
  2831. expect(mappings[1]).toEqual({
  2832. localName: 'myheader',
  2833. exportedName: '*',
  2834. source: 'myheader.h',
  2835. isDefault: false,
  2836. isNamespace: true,
  2837. });
  2838. expect(mappings[2]).toEqual({
  2839. localName: 'helpers',
  2840. exportedName: '*',
  2841. source: 'utils/helpers.hpp',
  2842. isDefault: false,
  2843. isNamespace: true,
  2844. });
  2845. });
  2846. it('should discover include directories from compile_commands.json', () => {
  2847. // Create a temp project with compile_commands.json
  2848. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2849. try {
  2850. const compileDb = [
  2851. {
  2852. directory: tempProject,
  2853. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  2854. file: 'src/main.cpp',
  2855. },
  2856. ];
  2857. fs.writeFileSync(
  2858. path.join(tempProject, 'compile_commands.json'),
  2859. JSON.stringify(compileDb)
  2860. );
  2861. // Create the include dirs so they exist
  2862. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2863. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  2864. clearCppIncludeDirCache();
  2865. const dirs = loadCppIncludeDirs(tempProject);
  2866. // Should find include and src/lib (relative to project root)
  2867. // /usr/include is absolute and outside project, should be excluded
  2868. expect(dirs).toContain('include');
  2869. expect(dirs).toContain('src/lib');
  2870. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  2871. } finally {
  2872. fs.rmSync(tempProject, { recursive: true });
  2873. }
  2874. });
  2875. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  2876. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2877. try {
  2878. // Create include/ and src/ directories with headers
  2879. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2880. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  2881. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2882. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  2883. // Create a directory without headers — should not be included
  2884. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  2885. clearCppIncludeDirCache();
  2886. const dirs = loadCppIncludeDirs(tempProject);
  2887. expect(dirs).toContain('include');
  2888. expect(dirs).toContain('src');
  2889. expect(dirs).not.toContain('docs');
  2890. } finally {
  2891. fs.rmSync(tempProject, { recursive: true });
  2892. }
  2893. });
  2894. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  2895. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  2896. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  2897. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  2898. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  2899. // than missing real resolutions. The test pins this so a later
  2900. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  2901. // trade-off explicitly.
  2902. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  2903. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2904. try {
  2905. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  2906. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  2907. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  2908. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  2909. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  2910. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  2911. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  2912. clearCppIncludeDirCache();
  2913. const dirs = loadCppIncludeDirs(tempProject);
  2914. // Both included — Obj-C dirs are intentionally allowed.
  2915. expect(dirs).toContain('cppmod');
  2916. expect(dirs).toContain('iosmod');
  2917. } finally {
  2918. fs.rmSync(tempProject, { recursive: true });
  2919. }
  2920. });
  2921. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  2922. // in the actual indexing pipeline (not just a phantom file→import-node
  2923. // edge). This pins the include-dir resolution path so the headline PR
  2924. // feature can't silently regress to a no-op in the indexing flow.
  2925. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  2926. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  2927. try {
  2928. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2929. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2930. fs.writeFileSync(
  2931. path.join(tempProject, 'include', 'utils.h'),
  2932. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  2933. );
  2934. fs.writeFileSync(
  2935. path.join(tempProject, 'src', 'main.cpp'),
  2936. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  2937. );
  2938. clearCppIncludeDirCache();
  2939. cg = await CodeGraph.init(tempProject, { index: true });
  2940. // Sanity: file nodes exist for the header and the cpp.
  2941. const allFiles = cg.getStats();
  2942. expect(allFiles.fileCount).toBe(2);
  2943. // The `#include "utils.h"` edge should target the real
  2944. // `include/utils.h` file node — not a floating `import` node
  2945. // living inside main.cpp.
  2946. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2947. const rows = db.getDb().prepare(`
  2948. select dst.kind as dstKind, dst.file_path as dstPath
  2949. from edges e
  2950. join nodes src on e.source = src.id
  2951. join nodes dst on e.target = dst.id
  2952. where e.kind = 'imports'
  2953. and src.kind = 'file'
  2954. and src.file_path = 'src/main.cpp'
  2955. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2956. const resolvedToHeader = rows.find(
  2957. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  2958. );
  2959. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  2960. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  2961. const stdlibFile = rows.find(
  2962. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  2963. );
  2964. expect(stdlibFile).toBeUndefined();
  2965. } finally {
  2966. fs.rmSync(tempProject, { recursive: true, force: true });
  2967. }
  2968. });
  2969. });
  2970. describe('C++ templated base-class inheritance (#1043)', () => {
  2971. // A class deriving from a TEMPLATE — `class D : public Base<int>` (or a CRTP
  2972. // `class W : public CRTPBase<W>`, or a qualified `class Q : public ns::Tpl<int>`)
  2973. // recorded its base as the full instantiation text (`Base<int>`), which never
  2974. // name-matched the template, indexed as the bare node `Base`. The `<…>` args
  2975. // are now stripped so the `extends` edge resolves end-to-end.
  2976. it('resolves an extends edge to a templated base (plain, CRTP, struct, multi-base)', async () => {
  2977. fs.writeFileSync(
  2978. path.join(tempDir, 'lib.hpp'),
  2979. `#pragma once
  2980. template<typename T> class Base { public: void foo(); };
  2981. template<typename Derived> class CRTPBase {};
  2982. class Plain {};
  2983. class Widget : public Base<int> {}; // plain template base
  2984. class App : public CRTPBase<App> {}; // CRTP (curiously-recurring)
  2985. struct Node : public Base<double> {}; // struct inheriting a template
  2986. class Both : public Base<char>, public Plain {}; // templated + plain in one clause
  2987. `
  2988. );
  2989. cg = await CodeGraph.init(tempDir, { index: true });
  2990. const db = DatabaseConnection.open(path.join(tempDir, '.codegraph', 'codegraph.db'));
  2991. const edges = db
  2992. .getDb()
  2993. .prepare(
  2994. `select src.name as fromName, dst.name as toName
  2995. from edges e
  2996. join nodes src on e.source = src.id
  2997. join nodes dst on e.target = dst.id
  2998. where e.kind = 'extends'`
  2999. )
  3000. .all() as Array<{ fromName: string; toName: string }>;
  3001. const has = (from: string, to: string) =>
  3002. edges.some((r) => r.fromName === from && r.toName === to);
  3003. // Every templated base now resolves to the bare template node.
  3004. expect(has('Widget', 'Base'), 'Widget : Base<int>').toBe(true);
  3005. expect(has('App', 'CRTPBase'), 'App : CRTPBase<App> (CRTP)').toBe(true);
  3006. expect(has('Node', 'Base'), 'struct Node : Base<double>').toBe(true);
  3007. // A mixed clause resolves BOTH the templated and the plain base.
  3008. expect(has('Both', 'Base'), 'Both : Base<char>').toBe(true);
  3009. expect(has('Both', 'Plain'), 'Both : Plain (non-templated, regression guard)').toBe(true);
  3010. });
  3011. });
  3012. describe('PHP Include Resolution', () => {
  3013. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  3014. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  3015. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  3016. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  3017. });
  3018. // include paths: contain a slash or a file extension
  3019. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  3020. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  3021. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  3022. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  3023. // so they must NOT be treated as includes (would mis-connect to a
  3024. // same-named Closure.php / Bar.php file).
  3025. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  3026. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  3027. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  3028. // scoped to PHP imports only
  3029. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  3030. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  3031. });
  3032. it('resolves require_once to a file→file imports edge (#660)', async () => {
  3033. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  3034. try {
  3035. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  3036. fs.writeFileSync(
  3037. path.join(tempProject, 'src', 'lib.php'),
  3038. `<?php\nfunction greet() { return "hi"; }\n`
  3039. );
  3040. fs.writeFileSync(
  3041. path.join(tempProject, 'src', 'page.php'),
  3042. `<?php\nrequire_once("lib.php");\necho greet();\n`
  3043. );
  3044. cg = await CodeGraph.init(tempProject, { index: true });
  3045. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  3046. // to the real src/lib.php file node — a file→file `imports` edge, so
  3047. // callers(lib.php) now includes page.php.
  3048. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3049. const rows = db.getDb().prepare(`
  3050. select dst.kind as dstKind, dst.file_path as dstPath
  3051. from edges e
  3052. join nodes src on e.source = src.id
  3053. join nodes dst on e.target = dst.id
  3054. where e.kind = 'imports'
  3055. and src.kind = 'file'
  3056. and src.file_path = 'src/page.php'
  3057. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3058. const resolved = rows.find(
  3059. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  3060. );
  3061. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  3062. } finally {
  3063. fs.rmSync(tempProject, { recursive: true, force: true });
  3064. }
  3065. });
  3066. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  3067. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  3068. try {
  3069. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  3070. fs.writeFileSync(
  3071. path.join(tempProject, 'inc', 'db.php'),
  3072. `<?php\nfunction query() { return 1; }\n`
  3073. );
  3074. fs.writeFileSync(
  3075. path.join(tempProject, 'index.php'),
  3076. `<?php\nrequire "inc/db.php";\nquery();\n`
  3077. );
  3078. cg = await CodeGraph.init(tempProject, { index: true });
  3079. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3080. const rows = db.getDb().prepare(`
  3081. select dst.kind as dstKind, dst.file_path as dstPath
  3082. from edges e
  3083. join nodes src on e.source = src.id
  3084. join nodes dst on e.target = dst.id
  3085. where e.kind = 'imports'
  3086. and src.kind = 'file'
  3087. and src.file_path = 'index.php'
  3088. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3089. expect(
  3090. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  3091. 'index.php → inc/db.php imports edge missing'
  3092. ).toBeDefined();
  3093. } finally {
  3094. fs.rmSync(tempProject, { recursive: true, force: true });
  3095. }
  3096. });
  3097. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  3098. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  3099. try {
  3100. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  3101. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  3102. // but is unrelated — no edge should be created (a wrong edge is worse
  3103. // than a missing one).
  3104. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  3105. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  3106. fs.writeFileSync(
  3107. path.join(tempProject, 'lib', 'inc', 'db.php'),
  3108. `<?php\nfunction unrelated() {}\n`
  3109. );
  3110. fs.writeFileSync(
  3111. path.join(tempProject, 'app', 'page.php'),
  3112. `<?php\nrequire "inc/db.php";\n`
  3113. );
  3114. cg = await CodeGraph.init(tempProject, { index: true });
  3115. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3116. const rows = db.getDb().prepare(`
  3117. select dst.kind as dstKind, dst.file_path as dstPath
  3118. from edges e
  3119. join nodes src on e.source = src.id
  3120. join nodes dst on e.target = dst.id
  3121. where e.kind = 'imports'
  3122. and src.kind = 'file'
  3123. and src.file_path = 'app/page.php'
  3124. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3125. expect(
  3126. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  3127. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  3128. ).toBeUndefined();
  3129. } finally {
  3130. fs.rmSync(tempProject, { recursive: true, force: true });
  3131. }
  3132. });
  3133. });
  3134. describe('C++ chained-call receiver resolution (#645)', () => {
  3135. async function indexCpp(files: Record<string, string>): Promise<void> {
  3136. for (const [name, content] of Object.entries(files)) {
  3137. fs.writeFileSync(path.join(tempDir, name), content);
  3138. }
  3139. cg = await CodeGraph.init(tempDir, { index: true });
  3140. }
  3141. function callerNamesOf(qualifiedName: string): string[] {
  3142. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3143. if (!target) return [];
  3144. const names = cg
  3145. .getIncomingEdges(target.id)
  3146. .filter((e) => e.kind === 'calls')
  3147. .map((e) => cg.getNode(e.source)?.name)
  3148. .filter((n): n is string => !!n);
  3149. return [...new Set(names)].sort();
  3150. }
  3151. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  3152. // Two classes share writeLog; Logger sorts first so it wins any name-only
  3153. // tie. All three call forms target Metrics.
  3154. await indexCpp({
  3155. 'logger.hpp': `#pragma once
  3156. #include <string>
  3157. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  3158. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  3159. `,
  3160. 'impl.cpp': `#include "logger.hpp"
  3161. Logger& Logger::instance() { static Logger l; return l; }
  3162. Metrics& Metrics::instance() { static Metrics m; return m; }
  3163. void Logger::writeLog(const std::string&) {}
  3164. void Metrics::writeLog(const std::string&) {}
  3165. `,
  3166. 'app.cpp': `#include "logger.hpp"
  3167. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  3168. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  3169. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  3170. `,
  3171. });
  3172. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  3173. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  3174. });
  3175. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  3176. await indexCpp({
  3177. 'types.hpp': `#pragma once
  3178. #include <memory>
  3179. struct Widget { void draw(); };
  3180. struct Session { void run(); };
  3181. struct View { void render(); };
  3182. class WidgetFactory { public: static Widget create(); };
  3183. class Manager { public: View view(); };
  3184. Session* openSession();
  3185. // Decoy that sorts first and has all three methods — must never win.
  3186. struct Aaa { void draw(); void run(); void render(); };
  3187. `,
  3188. 'impl.cpp': `#include "types.hpp"
  3189. void Widget::draw() {}
  3190. void Session::run() {}
  3191. void View::render() {}
  3192. void Aaa::draw() {}
  3193. void Aaa::run() {}
  3194. void Aaa::render() {}
  3195. Widget WidgetFactory::create() { return Widget(); }
  3196. View Manager::view() { return View(); }
  3197. Session* openSession() { return nullptr; }
  3198. `,
  3199. 'app.cpp': `#include "types.hpp"
  3200. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  3201. void freefunc() { openSession()->run(); } // -> Session::run
  3202. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  3203. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  3204. `,
  3205. });
  3206. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  3207. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  3208. expect(callerNamesOf('View::render')).toEqual(['member']);
  3209. // The first-sorted decoy never captures any of them.
  3210. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  3211. expect(callerNamesOf('Aaa::run')).toEqual([]);
  3212. expect(callerNamesOf('Aaa::render')).toEqual([]);
  3213. });
  3214. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  3215. await indexCpp({
  3216. 'types.hpp': `#pragma once
  3217. struct Widget { void draw(); };
  3218. struct Other { void onlyOther(); };
  3219. class WidgetFactory { public: static Widget create(); };
  3220. `,
  3221. 'impl.cpp': `#include "types.hpp"
  3222. void Widget::draw() {}
  3223. void Other::onlyOther() {}
  3224. Widget WidgetFactory::create() { return Widget(); }
  3225. `,
  3226. 'app.cpp': `#include "types.hpp"
  3227. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  3228. void wrong() { WidgetFactory::create().onlyOther(); }
  3229. `,
  3230. });
  3231. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3232. });
  3233. });
  3234. describe('C++ explicit operator-call resolution (#1247)', () => {
  3235. // `a.operator+(b)` produced no calls edge: the operator_name lands in an
  3236. // ERROR node (never a field_expression callee), so the extractor emitted a
  3237. // ref named just `a`. With the ERROR-node recovery it emits `a.operator+`,
  3238. // and matchMethodCall (dot pattern extended to admit operator method parts)
  3239. // resolves it through receiver-type inference. Infix `a + b` / `a[i]` need
  3240. // real type inference and are out of scope here (#1258).
  3241. async function indexCpp(files: Record<string, string>): Promise<void> {
  3242. for (const [name, content] of Object.entries(files)) {
  3243. fs.writeFileSync(path.join(tempDir, name), content);
  3244. }
  3245. cg = await CodeGraph.init(tempDir, { index: true });
  3246. }
  3247. function callerNamesOf(qualifiedName: string): string[] {
  3248. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3249. if (!target) return [];
  3250. const names = cg
  3251. .getIncomingEdges(target.id)
  3252. .filter((e) => e.kind === 'calls')
  3253. .map((e) => cg.getNode(e.source)?.name)
  3254. .filter((n): n is string => !!n);
  3255. return [...new Set(names)].sort();
  3256. }
  3257. it('resolves explicit operator calls to the receiver type, never a same-named decoy', async () => {
  3258. // Aaa sorts first and declares the same operators — only receiver-type
  3259. // inference (const V& a → V) can pick V, so a name-only tie can't win.
  3260. await indexCpp({
  3261. 'optest.cpp': `struct Aaa {
  3262. Aaa operator+(const Aaa& o) const { return o; }
  3263. Aaa operator[](int i) const { return *this; }
  3264. };
  3265. struct V {
  3266. int x;
  3267. V operator+(const V& o) const { return V{x + o.x}; }
  3268. V operator[](int i) const { return V{x + i}; }
  3269. int get() const { return x; }
  3270. };
  3271. int plainCaller(const V& a) { return a.get(); }
  3272. V explicitCaller(const V& a, const V& b) { return a.operator+(b); }
  3273. V subscriptCaller(const V& a) { return a.operator[](3); }
  3274. V pointerCaller(const V* p, const V& b) { return p->operator+(b); }
  3275. `,
  3276. });
  3277. expect(callerNamesOf('V::operator+')).toEqual(['explicitCaller', 'pointerCaller']);
  3278. expect(callerNamesOf('V::operator[]')).toEqual(['subscriptCaller']);
  3279. expect(callerNamesOf('V::get')).toEqual(['plainCaller']); // control: plain calls unaffected
  3280. expect(callerNamesOf('Aaa::operator+')).toEqual([]);
  3281. expect(callerNamesOf('Aaa::operator[]')).toEqual([]);
  3282. });
  3283. it('resolves an out-of-line operator definition (declaration in header)', async () => {
  3284. await indexCpp({
  3285. 'v.hpp': `#pragma once
  3286. struct V { int x; V operator+(const V& o) const; };
  3287. `,
  3288. 'v.cpp': `#include "v.hpp"
  3289. V V::operator+(const V& o) const { return V{x + o.x}; }
  3290. `,
  3291. 'app.cpp': `#include "v.hpp"
  3292. V add(const V& a, const V& b) { return a.operator+(b); }
  3293. `,
  3294. });
  3295. expect(callerNamesOf('V::operator+')).toEqual(['add']);
  3296. });
  3297. });
  3298. describe('PHP chained static-factory call resolution (#608)', () => {
  3299. function callerNamesOf(qualifiedName: string): string[] {
  3300. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3301. if (!target) return [];
  3302. const names = cg
  3303. .getIncomingEdges(target.id)
  3304. .filter((e) => e.kind === 'calls')
  3305. .map((e) => cg.getNode(e.source)?.name)
  3306. .filter((n): n is string => !!n);
  3307. return [...new Set(names)].sort();
  3308. }
  3309. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  3310. fs.writeFileSync(
  3311. path.join(tempDir, 'ApiClient.php'),
  3312. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  3313. );
  3314. fs.writeFileSync(
  3315. path.join(tempDir, 'DispatchOrder.php'),
  3316. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  3317. );
  3318. cg = await CodeGraph.init(tempDir, { index: true });
  3319. // The chained call's edge attaches to the factory result's method.
  3320. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  3321. });
  3322. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  3323. fs.writeFileSync(
  3324. path.join(tempDir, 'lib.php'),
  3325. `<?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`
  3326. );
  3327. cg = await CodeGraph.init(tempDir, { index: true });
  3328. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3329. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3330. });
  3331. });
  3332. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  3333. function callerNamesOf(qualifiedName: string): string[] {
  3334. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3335. if (!target) return [];
  3336. const names = cg
  3337. .getIncomingEdges(target.id)
  3338. .filter((e) => e.kind === 'calls')
  3339. .map((e) => cg.getNode(e.source)?.name)
  3340. .filter((n): n is string => !!n);
  3341. return [...new Set(names)].sort();
  3342. }
  3343. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  3344. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  3345. fs.writeFileSync(
  3346. path.join(tempDir, 'Main.java'),
  3347. `class Aaa { void bar() {} }
  3348. class Foo {
  3349. static Foo getInstance() { return new Foo(); }
  3350. void bar() {}
  3351. }
  3352. class Caller {
  3353. void run() { Foo.getInstance().bar(); }
  3354. }
  3355. `
  3356. );
  3357. cg = await CodeGraph.init(tempDir, { index: true });
  3358. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  3359. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  3360. });
  3361. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  3362. // The factory call carries an argument; the extractor must normalize the
  3363. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  3364. fs.writeFileSync(
  3365. path.join(tempDir, 'Main.java'),
  3366. `class Config {}
  3367. class Foo {
  3368. static Foo create(Config c) { return new Foo(); }
  3369. void build() {}
  3370. }
  3371. class Caller {
  3372. void run() { Foo.create(new Config()).build(); }
  3373. }
  3374. `
  3375. );
  3376. cg = await CodeGraph.init(tempDir, { index: true });
  3377. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  3378. });
  3379. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3380. fs.writeFileSync(
  3381. path.join(tempDir, 'Main.java'),
  3382. `class Foo {
  3383. static Foo getInstance() { return new Foo(); }
  3384. }
  3385. class Other { void onlyOther() {} }
  3386. class Caller {
  3387. void run() { Foo.getInstance().onlyOther(); }
  3388. }
  3389. `
  3390. );
  3391. cg = await CodeGraph.init(tempDir, { index: true });
  3392. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3393. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3394. });
  3395. });
  3396. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  3397. function callerNamesOf(qualifiedName: string): string[] {
  3398. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3399. if (!target) return [];
  3400. const names = cg
  3401. .getIncomingEdges(target.id)
  3402. .filter((e) => e.kind === 'calls')
  3403. .map((e) => cg.getNode(e.source)?.name)
  3404. .filter((n): n is string => !!n);
  3405. return [...new Set(names)].sort();
  3406. }
  3407. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  3408. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  3409. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  3410. fs.writeFileSync(
  3411. path.join(tempDir, 'Main.kt'),
  3412. `class Aaa { fun bar() {} }
  3413. class Foo {
  3414. companion object {
  3415. fun getInstance(): Foo = Foo()
  3416. }
  3417. fun bar() {}
  3418. }
  3419. class Caller {
  3420. fun run() { Foo.getInstance().bar() }
  3421. }
  3422. `
  3423. );
  3424. cg = await CodeGraph.init(tempDir, { index: true });
  3425. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  3426. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  3427. });
  3428. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  3429. fs.writeFileSync(
  3430. path.join(tempDir, 'Main.kt'),
  3431. `class Config
  3432. class Foo {
  3433. companion object {
  3434. fun create(c: Config): Foo = Foo()
  3435. }
  3436. fun build() {}
  3437. }
  3438. class Caller {
  3439. fun run() { Foo.create(Config()).build() }
  3440. }
  3441. `
  3442. );
  3443. cg = await CodeGraph.init(tempDir, { index: true });
  3444. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  3445. });
  3446. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  3447. fs.writeFileSync(
  3448. path.join(tempDir, 'Main.kt'),
  3449. `class Foo {
  3450. companion object {
  3451. fun getInstance(): Foo = Foo()
  3452. }
  3453. }
  3454. class Other { fun onlyOther() {} }
  3455. class Caller {
  3456. fun run() { Foo.getInstance().onlyOther() }
  3457. }
  3458. `
  3459. );
  3460. cg = await CodeGraph.init(tempDir, { index: true });
  3461. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3462. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3463. });
  3464. });
  3465. describe('C# chained static-factory 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 Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  3477. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  3478. fs.writeFileSync(
  3479. path.join(tempDir, 'Main.cs'),
  3480. `class Aaa { void Bar() {} }
  3481. class Foo {
  3482. static Foo Create() { return new Foo(); }
  3483. void Bar() {}
  3484. }
  3485. class Caller {
  3486. void Run() { Foo.Create().Bar(); }
  3487. }
  3488. `
  3489. );
  3490. cg = await CodeGraph.init(tempDir, { index: true });
  3491. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  3492. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  3493. });
  3494. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  3495. fs.writeFileSync(
  3496. path.join(tempDir, 'Main.cs'),
  3497. `class Config {}
  3498. class Foo {
  3499. static Foo Make(Config c) { return new Foo(); }
  3500. void Build() {}
  3501. }
  3502. class Caller {
  3503. void Run() { Foo.Make(new Config()).Build(); }
  3504. }
  3505. `
  3506. );
  3507. cg = await CodeGraph.init(tempDir, { index: true });
  3508. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  3509. });
  3510. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3511. fs.writeFileSync(
  3512. path.join(tempDir, 'Main.cs'),
  3513. `class Foo {
  3514. static Foo Create() { return new Foo(); }
  3515. }
  3516. class Other { void OnlyOther() {} }
  3517. class Caller {
  3518. void Run() { Foo.Create().OnlyOther(); }
  3519. }
  3520. `
  3521. );
  3522. cg = await CodeGraph.init(tempDir, { index: true });
  3523. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3524. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3525. });
  3526. });
  3527. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  3528. function callerNamesOf(qualifiedName: string): string[] {
  3529. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3530. if (!target) return [];
  3531. const names = cg
  3532. .getIncomingEdges(target.id)
  3533. .filter((e) => e.kind === 'calls')
  3534. .map((e) => cg.getNode(e.source)?.name)
  3535. .filter((n): n is string => !!n);
  3536. return [...new Set(names)].sort();
  3537. }
  3538. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  3539. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  3540. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  3541. fs.writeFileSync(
  3542. path.join(tempDir, 'Main.swift'),
  3543. `class Aaa { func draw() {} }
  3544. class Foo {
  3545. static func make() -> Foo { return Foo() }
  3546. func draw() {}
  3547. }
  3548. func runCaller() { Foo.make().draw() }
  3549. `
  3550. );
  3551. cg = await CodeGraph.init(tempDir, { index: true });
  3552. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  3553. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  3554. });
  3555. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  3556. fs.writeFileSync(
  3557. path.join(tempDir, 'Main.swift'),
  3558. `class Config {}
  3559. class Foo {
  3560. static func build(_ c: Config) -> Foo { return Foo() }
  3561. func draw() {}
  3562. func render() {}
  3563. }
  3564. func runCaller() {
  3565. Foo().draw()
  3566. Foo.build(Config()).render()
  3567. }
  3568. `
  3569. );
  3570. cg = await CodeGraph.init(tempDir, { index: true });
  3571. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  3572. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  3573. });
  3574. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3575. fs.writeFileSync(
  3576. path.join(tempDir, 'Main.swift'),
  3577. `class Foo {
  3578. static func make() -> Foo { return Foo() }
  3579. }
  3580. class Other { func onlyOther() {} }
  3581. func runCaller() { Foo.make().onlyOther() }
  3582. `
  3583. );
  3584. cg = await CodeGraph.init(tempDir, { index: true });
  3585. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3586. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3587. });
  3588. });
  3589. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  3590. function callerNamesOf(qualifiedName: string): string[] {
  3591. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3592. if (!target) return [];
  3593. const names = cg
  3594. .getIncomingEdges(target.id)
  3595. .filter((e) => e.kind === 'calls')
  3596. .map((e) => cg.getNode(e.source)?.name)
  3597. .filter((n): n is string => !!n);
  3598. return [...new Set(names)].sort();
  3599. }
  3600. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  3601. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  3602. // its own. Decoy.draw must never win. Needs the conformance second pass.
  3603. fs.writeFileSync(
  3604. path.join(tempDir, 'Main.java'),
  3605. `class Base { void draw() {} }
  3606. class Widget extends Base {}
  3607. class Decoy { void draw() {} }
  3608. class Factory { static Widget create() { return new Widget(); } }
  3609. class Caller {
  3610. void run() { Factory.create().draw(); }
  3611. }
  3612. `
  3613. );
  3614. cg = await CodeGraph.init(tempDir, { index: true });
  3615. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  3616. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3617. });
  3618. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  3619. fs.writeFileSync(
  3620. path.join(tempDir, 'Main.java'),
  3621. `interface Drawable { default void draw() {} }
  3622. class Widget implements Drawable {}
  3623. class Decoy { void draw() {} }
  3624. class Factory { static Widget create() { return new Widget(); } }
  3625. class Caller {
  3626. void run() { Factory.create().draw(); }
  3627. }
  3628. `
  3629. );
  3630. cg = await CodeGraph.init(tempDir, { index: true });
  3631. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  3632. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3633. });
  3634. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  3635. fs.writeFileSync(
  3636. path.join(tempDir, 'Main.java'),
  3637. `class Base {}
  3638. class Widget extends Base {}
  3639. class Other { void onlyOther() {} }
  3640. class Factory { static Widget create() { return new Widget(); } }
  3641. class Caller {
  3642. void run() { Factory.create().onlyOther(); }
  3643. }
  3644. `
  3645. );
  3646. cg = await CodeGraph.init(tempDir, { index: true });
  3647. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  3648. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3649. });
  3650. });
  3651. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  3652. function callerNamesOf(qualifiedName: string): string[] {
  3653. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3654. if (!target) return [];
  3655. const names = cg
  3656. .getIncomingEdges(target.id)
  3657. .filter((e) => e.kind === 'calls')
  3658. .map((e) => cg.getNode(e.source)?.name)
  3659. .filter((n): n is string => !!n);
  3660. return [...new Set(names)].sort();
  3661. }
  3662. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  3663. fs.writeFileSync(
  3664. path.join(tempDir, 'main.rs'),
  3665. `struct Aaa { _x: i32 }
  3666. impl Aaa { fn bar(&self) {} }
  3667. struct Foo { _x: i32 }
  3668. impl Foo {
  3669. fn new() -> Foo { Foo { _x: 0 } }
  3670. fn make() -> Self { Foo { _x: 0 } }
  3671. fn bar(&self) {}
  3672. }
  3673. fn caller() {
  3674. Foo::new().bar();
  3675. Foo::make().bar();
  3676. }
  3677. `
  3678. );
  3679. cg = await CodeGraph.init(tempDir, { index: true });
  3680. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  3681. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  3682. });
  3683. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  3684. fs.writeFileSync(
  3685. path.join(tempDir, 'main.rs'),
  3686. `struct Config;
  3687. struct Foo { _x: i32 }
  3688. impl Foo {
  3689. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  3690. fn build(&self) {}
  3691. }
  3692. fn caller() { Foo::with(Config).build(); }
  3693. `
  3694. );
  3695. cg = await CodeGraph.init(tempDir, { index: true });
  3696. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  3697. });
  3698. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  3699. fs.writeFileSync(
  3700. path.join(tempDir, 'main.rs'),
  3701. `struct Foo { _x: i32 }
  3702. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3703. struct Decoy { _x: i32 }
  3704. impl Decoy { fn draw(&self) {} }
  3705. trait Drawable { fn draw(&self) {} }
  3706. impl Drawable for Foo {}
  3707. fn caller() { Foo::new().draw(); }
  3708. `
  3709. );
  3710. cg = await CodeGraph.init(tempDir, { index: true });
  3711. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  3712. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3713. });
  3714. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  3715. fs.writeFileSync(
  3716. path.join(tempDir, 'main.rs'),
  3717. `struct Foo { _x: i32 }
  3718. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3719. struct Other { _x: i32 }
  3720. impl Other { fn only_other(&self) {} }
  3721. fn caller() { Foo::new().only_other(); }
  3722. `
  3723. );
  3724. cg = await CodeGraph.init(tempDir, { index: true });
  3725. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  3726. expect(callerNamesOf('Other::only_other')).toEqual([]);
  3727. });
  3728. });
  3729. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  3730. function callerNamesOf(qualifiedName: string): string[] {
  3731. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3732. if (!target) return [];
  3733. const names = cg
  3734. .getIncomingEdges(target.id)
  3735. .filter((e) => e.kind === 'calls')
  3736. .map((e) => cg.getNode(e.source)?.name)
  3737. .filter((n): n is string => !!n);
  3738. return [...new Set(names)].sort();
  3739. }
  3740. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  3741. fs.writeFileSync(
  3742. path.join(tempDir, 'main.go'),
  3743. `package main
  3744. type Aaa struct{}
  3745. func (a *Aaa) Bar() {}
  3746. type Foo struct{}
  3747. func New() *Foo { return &Foo{} }
  3748. func (f *Foo) Bar() {}
  3749. func caller() { New().Bar() }
  3750. `
  3751. );
  3752. cg = await CodeGraph.init(tempDir, { index: true });
  3753. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  3754. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  3755. });
  3756. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  3757. fs.writeFileSync(
  3758. path.join(tempDir, 'main.go'),
  3759. `package main
  3760. type Config struct{}
  3761. type Foo struct{}
  3762. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  3763. func (f *Foo) Build() {}
  3764. func caller() { With(Config{}).Build() }
  3765. `
  3766. );
  3767. cg = await CodeGraph.init(tempDir, { index: true });
  3768. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  3769. });
  3770. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  3771. fs.writeFileSync(
  3772. path.join(tempDir, 'main.go'),
  3773. `package main
  3774. type Base struct{}
  3775. func (b *Base) Embedded() {}
  3776. type Decoy struct{}
  3777. func (d *Decoy) Embedded() {}
  3778. type Widget struct{ Base }
  3779. func NewWidget() *Widget { return &Widget{} }
  3780. func caller() { NewWidget().Embedded() }
  3781. `
  3782. );
  3783. cg = await CodeGraph.init(tempDir, { index: true });
  3784. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  3785. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  3786. });
  3787. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  3788. fs.writeFileSync(
  3789. path.join(tempDir, 'main.go'),
  3790. `package main
  3791. type Foo struct{}
  3792. func New() *Foo { return &Foo{} }
  3793. type Other struct{}
  3794. func (o *Other) OnlyOther() {}
  3795. func caller() { New().OnlyOther() }
  3796. `
  3797. );
  3798. cg = await CodeGraph.init(tempDir, { index: true });
  3799. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3800. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3801. });
  3802. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  3803. // `engine` is a package-level VARIABLE holding a func value, not a factory
  3804. // FUNCTION — so its return type can't be recovered and the chain falls back
  3805. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  3806. // Regression for the runaway this fallback originally caused: it resolved
  3807. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  3808. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  3809. // no-oped, the offset-0 batch never drained, and edges inserted forever
  3810. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  3811. // the original ref, and a non-progress guard backstops the loop.
  3812. fs.writeFileSync(
  3813. path.join(tempDir, 'main.go'),
  3814. `package main
  3815. type Server struct{}
  3816. func (s *Server) ServeHTTP() {}
  3817. var engine = func() *Server { return &Server{} }
  3818. func caller() { engine().ServeHTTP() }
  3819. `
  3820. );
  3821. cg = await CodeGraph.init(tempDir, { index: true });
  3822. // Recall: the variable-inner chain still finds the method by bare name.
  3823. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  3824. // No runaway: a single call site yields a single edge, not millions.
  3825. const target = cg
  3826. .getNodesByKind('method')
  3827. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  3828. const rawCalls = cg
  3829. .getIncomingEdges(target.id)
  3830. .filter((e) => e.kind === 'calls');
  3831. expect(rawCalls.length).toBeLessThan(5);
  3832. });
  3833. });
  3834. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  3835. function callerNamesOf(qualifiedName: string): string[] {
  3836. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3837. if (!target) return [];
  3838. const names = cg
  3839. .getIncomingEdges(target.id)
  3840. .filter((e) => e.kind === 'calls')
  3841. .map((e) => cg.getNode(e.source)?.name)
  3842. .filter((n): n is string => !!n);
  3843. return [...new Set(names)].sort();
  3844. }
  3845. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  3846. fs.writeFileSync(
  3847. path.join(tempDir, 'Main.scala'),
  3848. `object Foo {
  3849. def create(): Bar = new Bar()
  3850. }
  3851. class Bar {
  3852. def doIt(): Unit = {}
  3853. }
  3854. class Decoy {
  3855. def doIt(): Unit = {}
  3856. }
  3857. object Main {
  3858. def run(): Unit = { Foo.create().doIt() }
  3859. }
  3860. `
  3861. );
  3862. cg = await CodeGraph.init(tempDir, { index: true });
  3863. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3864. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3865. });
  3866. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  3867. fs.writeFileSync(
  3868. path.join(tempDir, 'Main.scala'),
  3869. `class Point(x: Int) {
  3870. def dist(): Int = x
  3871. }
  3872. class Other {
  3873. def dist(): Int = 0
  3874. }
  3875. object Main {
  3876. def run(): Unit = { Point(3).dist() }
  3877. }
  3878. `
  3879. );
  3880. cg = await CodeGraph.init(tempDir, { index: true });
  3881. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  3882. expect(callerNamesOf('Other::dist')).toEqual([]);
  3883. });
  3884. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  3885. fs.writeFileSync(
  3886. path.join(tempDir, 'Main.scala'),
  3887. `trait Base {
  3888. def shared(): Unit = {}
  3889. }
  3890. class Widget extends Base
  3891. class Decoy {
  3892. def shared(): Unit = {}
  3893. }
  3894. object Factory {
  3895. def make(): Widget = new Widget()
  3896. }
  3897. object Main {
  3898. def run(): Unit = { Factory.make().shared() }
  3899. }
  3900. `
  3901. );
  3902. cg = await CodeGraph.init(tempDir, { index: true });
  3903. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  3904. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  3905. });
  3906. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3907. fs.writeFileSync(
  3908. path.join(tempDir, 'Main.scala'),
  3909. `object Foo {
  3910. def create(): Bar = new Bar()
  3911. }
  3912. class Bar {
  3913. }
  3914. class Other {
  3915. def onlyOther(): Unit = {}
  3916. }
  3917. object Main {
  3918. def run(): Unit = { Foo.create().onlyOther() }
  3919. }
  3920. `
  3921. );
  3922. cg = await CodeGraph.init(tempDir, { index: true });
  3923. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3924. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3925. });
  3926. });
  3927. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  3928. function callerNamesOf(qualifiedName: string): string[] {
  3929. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3930. if (!target) return [];
  3931. const names = cg
  3932. .getIncomingEdges(target.id)
  3933. .filter((e) => e.kind === 'calls')
  3934. .map((e) => cg.getNode(e.source)?.name)
  3935. .filter((n): n is string => !!n);
  3936. return [...new Set(names)].sort();
  3937. }
  3938. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  3939. fs.writeFileSync(
  3940. path.join(tempDir, 'main.dart'),
  3941. `class Foo {
  3942. static Bar makeBar() => Bar();
  3943. }
  3944. class Bar {
  3945. void doIt() {}
  3946. }
  3947. class Decoy {
  3948. void doIt() {}
  3949. }
  3950. void run() {
  3951. Foo.makeBar().doIt();
  3952. }
  3953. `
  3954. );
  3955. cg = await CodeGraph.init(tempDir, { index: true });
  3956. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3957. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3958. });
  3959. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  3960. fs.writeFileSync(
  3961. path.join(tempDir, 'main.dart'),
  3962. `class Foo {
  3963. Foo._();
  3964. factory Foo.create() => Foo._();
  3965. void ship() {}
  3966. }
  3967. class Decoy {
  3968. void ship() {}
  3969. }
  3970. void run() {
  3971. Foo.create().ship();
  3972. }
  3973. `
  3974. );
  3975. cg = await CodeGraph.init(tempDir, { index: true });
  3976. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  3977. // so `ship` resolves on Foo, not the same-named Decoy.
  3978. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  3979. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  3980. });
  3981. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  3982. fs.writeFileSync(
  3983. path.join(tempDir, 'main.dart'),
  3984. `class Bar {
  3985. void doIt() {}
  3986. }
  3987. class Decoy {
  3988. void doIt() {}
  3989. }
  3990. void run() {
  3991. Bar().doIt();
  3992. }
  3993. `
  3994. );
  3995. cg = await CodeGraph.init(tempDir, { index: true });
  3996. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3997. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3998. });
  3999. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  4000. fs.writeFileSync(
  4001. path.join(tempDir, 'main.dart'),
  4002. `class Base {
  4003. void render() {}
  4004. }
  4005. class Widget extends Base {
  4006. static Widget make() => Widget();
  4007. }
  4008. class Decoy {
  4009. void render() {}
  4010. }
  4011. void run() {
  4012. Widget.make().render();
  4013. }
  4014. `
  4015. );
  4016. cg = await CodeGraph.init(tempDir, { index: true });
  4017. expect(callerNamesOf('Base::render')).toEqual(['run']);
  4018. expect(callerNamesOf('Decoy::render')).toEqual([]);
  4019. });
  4020. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  4021. fs.writeFileSync(
  4022. path.join(tempDir, 'main.dart'),
  4023. `class Foo {
  4024. static Bar makeBar() => Bar();
  4025. }
  4026. class Bar {
  4027. }
  4028. class Other {
  4029. void onlyOther() {}
  4030. }
  4031. void run() {
  4032. Foo.makeBar().onlyOther();
  4033. }
  4034. `
  4035. );
  4036. cg = await CodeGraph.init(tempDir, { index: true });
  4037. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  4038. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4039. });
  4040. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  4041. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  4042. // swallows the record return type, so `reduce()` looks like a single-
  4043. // identifier constructor_signature. It must NOT be skipped as an unnamed
  4044. // ctor (its name doesn't match the class); its body call must attribute to
  4045. // `reduce`, not the class.
  4046. fs.writeFileSync(
  4047. path.join(tempDir, 'main.dart'),
  4048. `class Base {}
  4049. class Action extends Base {
  4050. Action({required int x});
  4051. @override
  4052. (int, String) reduce() {
  4053. return (compute(), "y");
  4054. }
  4055. int compute() => 1;
  4056. }
  4057. `
  4058. );
  4059. cg = await CodeGraph.init(tempDir, { index: true });
  4060. // reduce must be a node and its body call must resolve to Action::compute.
  4061. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  4062. });
  4063. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  4064. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  4065. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  4066. // never hijacked into a call to a phantom constructor method.
  4067. fs.writeFileSync(
  4068. path.join(tempDir, 'main.dart'),
  4069. `class Widget {
  4070. final int x;
  4071. Widget(this.x);
  4072. }
  4073. void run() {
  4074. Widget(3);
  4075. }
  4076. `
  4077. );
  4078. cg = await CodeGraph.init(tempDir, { index: true });
  4079. // No Foo::Foo phantom method node.
  4080. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  4081. // The construction resolves to the class as an `instantiates` edge.
  4082. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  4083. const incoming = cg.getIncomingEdges(widget.id);
  4084. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  4085. });
  4086. });
  4087. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  4088. function callerNamesOf(qualifiedName: string): string[] {
  4089. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4090. if (!target) return [];
  4091. const names = cg
  4092. .getIncomingEdges(target.id)
  4093. .filter((e) => e.kind === 'calls')
  4094. .map((e) => cg.getNode(e.source)?.name)
  4095. .filter((n): n is string => !!n);
  4096. return [...new Set(names)].sort();
  4097. }
  4098. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  4099. fs.writeFileSync(
  4100. path.join(tempDir, 'main.m'),
  4101. `@interface Bar : NSObject
  4102. - (void)doIt;
  4103. @end
  4104. @implementation Bar
  4105. - (void)doIt {}
  4106. @end
  4107. @interface Decoy : NSObject
  4108. - (void)doIt;
  4109. @end
  4110. @implementation Decoy
  4111. - (void)doIt {}
  4112. @end
  4113. @interface Foo : NSObject
  4114. + (Bar *)create;
  4115. @end
  4116. @implementation Foo
  4117. + (Bar *)create { return nil; }
  4118. - (void)run { [[Foo create] doIt]; }
  4119. @end
  4120. `
  4121. );
  4122. cg = await CodeGraph.init(tempDir, { index: true });
  4123. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  4124. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  4125. });
  4126. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  4127. fs.writeFileSync(
  4128. path.join(tempDir, 'main.m'),
  4129. `@interface Base : NSObject
  4130. - (void)render;
  4131. @end
  4132. @implementation Base
  4133. - (void)render {}
  4134. @end
  4135. @interface Widget : Base
  4136. @end
  4137. @implementation Widget
  4138. @end
  4139. @interface Decoy : NSObject
  4140. - (void)render;
  4141. @end
  4142. @implementation Decoy
  4143. - (void)render {}
  4144. @end
  4145. @interface Factory : NSObject
  4146. + (Widget *)make;
  4147. @end
  4148. @implementation Factory
  4149. + (Widget *)make { return nil; }
  4150. - (void)run { [[Factory make] render]; }
  4151. @end
  4152. `
  4153. );
  4154. cg = await CodeGraph.init(tempDir, { index: true });
  4155. expect(callerNamesOf('Base::render')).toEqual(['run']);
  4156. expect(callerNamesOf('Decoy::render')).toEqual([]);
  4157. });
  4158. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  4159. fs.writeFileSync(
  4160. path.join(tempDir, 'main.m'),
  4161. `@interface Bar : NSObject
  4162. @end
  4163. @implementation Bar
  4164. @end
  4165. @interface Other : NSObject
  4166. - (void)onlyOther;
  4167. @end
  4168. @implementation Other
  4169. - (void)onlyOther {}
  4170. @end
  4171. @interface Foo : NSObject
  4172. + (Bar *)create;
  4173. @end
  4174. @implementation Foo
  4175. + (Bar *)create { return nil; }
  4176. - (void)run { [[Foo create] onlyOther]; }
  4177. @end
  4178. `
  4179. );
  4180. cg = await CodeGraph.init(tempDir, { index: true });
  4181. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  4182. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4183. });
  4184. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  4185. // The factory returns `nonnull instancetype` — the nullability qualifier must
  4186. // be skipped (not captured AS the type), and an instancetype class-message
  4187. // factory returns the receiver class, so clearAll resolves on Cache, never a
  4188. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  4189. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  4190. fs.writeFileSync(
  4191. path.join(tempDir, 'main.m'),
  4192. `@interface Cache : NSObject
  4193. + (nonnull instancetype)shared;
  4194. - (void)clearAll;
  4195. @end
  4196. @implementation Cache
  4197. + (nonnull instancetype)shared { return nil; }
  4198. - (void)clearAll {}
  4199. @end
  4200. @interface Decoy : NSObject
  4201. - (void)clearAll;
  4202. @end
  4203. @implementation Decoy
  4204. - (void)clearAll {}
  4205. @end
  4206. @interface Caller : NSObject
  4207. - (void)run;
  4208. @end
  4209. @implementation Caller
  4210. - (void)run { [[Cache shared] clearAll]; }
  4211. @end
  4212. `
  4213. );
  4214. cg = await CodeGraph.init(tempDir, { index: true });
  4215. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  4216. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  4217. });
  4218. });
  4219. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  4220. function callerNamesOf(qualifiedName: string): string[] {
  4221. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4222. if (!target) return [];
  4223. const names = cg
  4224. .getIncomingEdges(target.id)
  4225. .filter((e) => e.kind === 'calls')
  4226. .map((e) => cg.getNode(e.source)?.name)
  4227. .filter((n): n is string => !!n);
  4228. return [...new Set(names)].sort();
  4229. }
  4230. function isCalled(qn: string): boolean {
  4231. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  4232. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  4233. }
  4234. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  4235. fs.writeFileSync(
  4236. path.join(tempDir, 'main.pas'),
  4237. `unit Main;
  4238. interface
  4239. type
  4240. TBar = class
  4241. procedure DoIt;
  4242. end;
  4243. TDecoy = class
  4244. procedure DoIt;
  4245. end;
  4246. TFoo = class
  4247. class function GetInstance: TBar;
  4248. end;
  4249. implementation
  4250. procedure TBar.DoIt; begin end;
  4251. procedure TDecoy.DoIt; begin end;
  4252. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4253. procedure Run;
  4254. begin
  4255. TFoo.GetInstance().DoIt();
  4256. end;
  4257. end.
  4258. `
  4259. );
  4260. cg = await CodeGraph.init(tempDir, { index: true });
  4261. expect(isCalled('TBar::DoIt')).toBe(true);
  4262. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4263. });
  4264. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  4265. fs.writeFileSync(
  4266. path.join(tempDir, 'main.pas'),
  4267. `unit Main;
  4268. interface
  4269. type
  4270. TFoo = class
  4271. constructor Create;
  4272. procedure Configure;
  4273. end;
  4274. TDecoy = class
  4275. procedure Configure;
  4276. end;
  4277. implementation
  4278. constructor TFoo.Create; begin end;
  4279. procedure TFoo.Configure; begin end;
  4280. procedure TDecoy.Configure; begin end;
  4281. procedure Run;
  4282. begin
  4283. TFoo.Create().Configure();
  4284. end;
  4285. end.
  4286. `
  4287. );
  4288. cg = await CodeGraph.init(tempDir, { index: true });
  4289. // A constructor returns its own class (no `: TBar` annotation), so Configure
  4290. // resolves on TFoo, not the same-named decoy.
  4291. expect(isCalled('TFoo::Configure')).toBe(true);
  4292. expect(isCalled('TDecoy::Configure')).toBe(false);
  4293. });
  4294. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  4295. fs.writeFileSync(
  4296. path.join(tempDir, 'main.pas'),
  4297. `unit Main;
  4298. interface
  4299. type
  4300. TFoo = class
  4301. procedure DoIt;
  4302. end;
  4303. TDecoy = class
  4304. procedure DoIt;
  4305. end;
  4306. implementation
  4307. procedure TFoo.DoIt; begin end;
  4308. procedure TDecoy.DoIt; begin end;
  4309. procedure Run(obj: TObject);
  4310. begin
  4311. TFoo(obj).DoIt();
  4312. end;
  4313. end.
  4314. `
  4315. );
  4316. cg = await CodeGraph.init(tempDir, { index: true });
  4317. expect(isCalled('TFoo::DoIt')).toBe(true);
  4318. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4319. });
  4320. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  4321. fs.writeFileSync(
  4322. path.join(tempDir, 'main.pas'),
  4323. `unit Main;
  4324. interface
  4325. type
  4326. TBar = class
  4327. end;
  4328. TOther = class
  4329. procedure OnlyOther;
  4330. end;
  4331. TFoo = class
  4332. class function GetInstance: TBar;
  4333. end;
  4334. implementation
  4335. procedure TOther.OnlyOther; begin end;
  4336. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4337. procedure Run;
  4338. begin
  4339. TFoo.GetInstance().OnlyOther();
  4340. end;
  4341. end.
  4342. `
  4343. );
  4344. cg = await CodeGraph.init(tempDir, { index: true });
  4345. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  4346. expect(isCalled('TOther::OnlyOther')).toBe(false);
  4347. });
  4348. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  4349. fs.writeFileSync(
  4350. path.join(tempDir, 'main.pas'),
  4351. `unit Main;
  4352. interface
  4353. type
  4354. TFoo = class
  4355. procedure DoThing;
  4356. procedure Reset;
  4357. end;
  4358. implementation
  4359. procedure TFoo.DoThing; begin end;
  4360. procedure TFoo.Reset; begin end;
  4361. procedure Run(f: TFoo);
  4362. begin
  4363. f.DoThing;
  4364. f.Reset;
  4365. end;
  4366. end.
  4367. `
  4368. );
  4369. cg = await CodeGraph.init(tempDir, { index: true });
  4370. expect(isCalled('TFoo::DoThing')).toBe(true);
  4371. expect(isCalled('TFoo::Reset')).toBe(true);
  4372. });
  4373. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  4374. fs.writeFileSync(
  4375. path.join(tempDir, 'main.pas'),
  4376. `unit Main;
  4377. interface
  4378. type
  4379. TBar = class
  4380. procedure DoIt;
  4381. end;
  4382. TDecoy = class
  4383. procedure DoIt;
  4384. end;
  4385. TFoo = class
  4386. class function GetInstance: TBar;
  4387. end;
  4388. implementation
  4389. procedure TBar.DoIt; begin end;
  4390. procedure TDecoy.DoIt; begin end;
  4391. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4392. procedure Run;
  4393. begin
  4394. TFoo.GetInstance.DoIt;
  4395. end;
  4396. end.
  4397. `
  4398. );
  4399. cg = await CodeGraph.init(tempDir, { index: true });
  4400. expect(isCalled('TBar::DoIt')).toBe(true);
  4401. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4402. });
  4403. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  4404. fs.writeFileSync(
  4405. path.join(tempDir, 'main.pas'),
  4406. `unit Main;
  4407. interface
  4408. type
  4409. TFoo = class
  4410. function GetValue: Integer;
  4411. procedure SetValue(v: Integer);
  4412. property Value: Integer read GetValue write SetValue;
  4413. end;
  4414. implementation
  4415. function TFoo.GetValue: Integer; begin Result := 0; end;
  4416. procedure TFoo.SetValue(v: Integer); begin end;
  4417. procedure Run(f: TFoo);
  4418. var x: Integer;
  4419. begin
  4420. f.Value := 5;
  4421. x := f.Value;
  4422. end;
  4423. end.
  4424. `
  4425. );
  4426. cg = await CodeGraph.init(tempDir, { index: true });
  4427. // A property read/write is a bare dot in assignment position, not a statement,
  4428. // so it must not be mis-extracted as a call to the property's getter/setter.
  4429. expect(isCalled('TFoo::GetValue')).toBe(false);
  4430. expect(isCalled('TFoo::SetValue')).toBe(false);
  4431. });
  4432. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  4433. fs.writeFileSync(
  4434. path.join(tempDir, 'main.pas'),
  4435. `unit Main;
  4436. interface
  4437. type
  4438. TTgt = class
  4439. procedure Hit;
  4440. end;
  4441. TFoo = class
  4442. procedure DoStuff;
  4443. end;
  4444. implementation
  4445. procedure TTgt.Hit; begin end;
  4446. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  4447. procedure Helper; var t: TTgt; begin t.Hit; end;
  4448. `
  4449. );
  4450. cg = await CodeGraph.init(tempDir, { index: true });
  4451. // `Helper` is implementation-only (no interface decl, not a method), but its
  4452. // body's call must attribute to `Helper`, not the file/module — alongside the
  4453. // method `DoStuff`.
  4454. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  4455. });
  4456. });
  4457. describe('Nix path import resolution', () => {
  4458. function fileNode(filePath: string) {
  4459. return cg.getNodesByKind('file').find((n) => n.filePath === filePath);
  4460. }
  4461. function importedFilePaths(fromFile: string): string[] {
  4462. const source = fileNode(fromFile);
  4463. expect(source, `${fromFile} file node`).toBeDefined();
  4464. return cg
  4465. .getOutgoingEdges(source!.id)
  4466. .filter((edge) => edge.kind === 'imports')
  4467. .map((edge) => cg.getNodesByKind('file').find((n) => n.id === edge.target)?.filePath)
  4468. .filter((filePath): filePath is string => Boolean(filePath))
  4469. .sort();
  4470. }
  4471. it('resolves relative Nix imports to indexed file nodes', async () => {
  4472. fs.mkdirSync(path.join(tempDir, 'core'), { recursive: true });
  4473. fs.mkdirSync(path.join(tempDir, 'data'), { recursive: true });
  4474. fs.writeFileSync(path.join(tempDir, 'core', 'ports.nix'), '{ http = 80; https = 443; }');
  4475. fs.writeFileSync(
  4476. path.join(tempDir, 'data', 'postgresql.nix'),
  4477. `let
  4478. ports = import ../core/ports.nix;
  4479. in
  4480. {
  4481. port = ports.https;
  4482. }
  4483. `
  4484. );
  4485. cg = await CodeGraph.init(tempDir, { index: true });
  4486. cg.resolveReferences();
  4487. expect(importedFilePaths('data/postgresql.nix')).toEqual(['core/ports.nix']);
  4488. });
  4489. it('resolves Nix directory imports through default.nix and deduplicates called imports', async () => {
  4490. fs.mkdirSync(path.join(tempDir, 'dir'), { recursive: true });
  4491. fs.writeFileSync(path.join(tempDir, 'dir', 'default.nix'), '{ value = 1; }');
  4492. fs.writeFileSync(path.join(tempDir, 'x.nix'), '{ value = 2; }');
  4493. fs.writeFileSync(
  4494. path.join(tempDir, 'main.nix'),
  4495. `let
  4496. dir = import ./dir;
  4497. x = import ./x.nix {};
  4498. in
  4499. {
  4500. inherit dir x;
  4501. }
  4502. `
  4503. );
  4504. cg = await CodeGraph.init(tempDir, { index: true });
  4505. cg.resolveReferences();
  4506. expect(importedFilePaths('main.nix')).toEqual(['dir/default.nix', 'x.nix']);
  4507. });
  4508. it('resolves NixOS module imports lists and callPackage paths to file nodes', async () => {
  4509. fs.mkdirSync(path.join(tempDir, 'modules'), { recursive: true });
  4510. fs.mkdirSync(path.join(tempDir, 'common'), { recursive: true });
  4511. fs.mkdirSync(path.join(tempDir, 'pkgs', 'hello'), { recursive: true });
  4512. fs.writeFileSync(path.join(tempDir, 'modules', 'users.nix'), '{ users.users.demo.isNormalUser = true; }');
  4513. fs.writeFileSync(path.join(tempDir, 'common', 'default.nix'), '{ time.timeZone = "UTC"; }');
  4514. fs.writeFileSync(
  4515. path.join(tempDir, 'pkgs', 'hello', 'default.nix'),
  4516. '{ stdenv }: stdenv.mkDerivation { pname = "hello"; }'
  4517. );
  4518. fs.writeFileSync(
  4519. path.join(tempDir, 'configuration.nix'),
  4520. `{ config, pkgs, ... }:
  4521. {
  4522. imports = [ ./modules/users.nix ./common ];
  4523. environment.systemPackages = [ (pkgs.callPackage ./pkgs/hello { }) ];
  4524. }
  4525. `
  4526. );
  4527. cg = await CodeGraph.init(tempDir, { index: true });
  4528. cg.resolveReferences();
  4529. expect(importedFilePaths('configuration.nix')).toEqual([
  4530. 'common/default.nix',
  4531. 'modules/users.nix',
  4532. 'pkgs/hello/default.nix',
  4533. ]);
  4534. });
  4535. it('never resolves another language\'s calls into nix bindings', async () => {
  4536. // Nix bindings are not linkable symbols from any other language —
  4537. // interop is eval/CLI. Without the target-side gate, a Python script's
  4538. // bare `resolve(...)` exact-matches a module's `resolve = ...` binding.
  4539. fs.writeFileSync(
  4540. path.join(tempDir, 'helpers.nix'),
  4541. `let
  4542. resolve = x: x;
  4543. in
  4544. {
  4545. inherit resolve;
  4546. }
  4547. `
  4548. );
  4549. fs.writeFileSync(path.join(tempDir, 'tool.py'), 'def main():\n return resolve("target")\n');
  4550. cg = await CodeGraph.init(tempDir, { index: true });
  4551. cg.resolveReferences();
  4552. const nixNodeIds = new Set(
  4553. cg.getNodesByKind('variable').filter((n) => n.language === 'nix').map((n) => n.id)
  4554. );
  4555. const pyFns = cg.getNodesByKind('function').filter((n) => n.language === 'python');
  4556. expect(pyFns.length).toBeGreaterThan(0);
  4557. const crossEdges = pyFns.flatMap((f) => cg.getOutgoingEdges(f.id)).filter((e) => nixNodeIds.has(e.target));
  4558. expect(crossEdges).toEqual([]);
  4559. });
  4560. it('never cross-links Nix calls by bare name across files (lexical scope only)', async () => {
  4561. // Both modules `inherit (lib) mkOption` — the nixpkgs idiom. A call to
  4562. // mkOption in one file must NOT resolve to the other file's inherit
  4563. // binding: Nix has no ambient cross-file namespace, so any such edge is
  4564. // wrong by construction. Same-file bindings still resolve.
  4565. fs.writeFileSync(
  4566. path.join(tempDir, 'alpha.nix'),
  4567. `{ lib, ... }:
  4568. let
  4569. inherit (lib) mkOption;
  4570. mkPort = default: mkOption { inherit default; };
  4571. in
  4572. {
  4573. options.alpha.port = mkPort 8080;
  4574. }
  4575. `
  4576. );
  4577. fs.writeFileSync(
  4578. path.join(tempDir, 'beta.nix'),
  4579. `{ lib, ... }:
  4580. let
  4581. inherit (lib) mkOption;
  4582. in
  4583. {
  4584. options.beta.enable = mkOption { default = false; };
  4585. }
  4586. `
  4587. );
  4588. cg = await CodeGraph.init(tempDir, { index: true });
  4589. cg.resolveReferences();
  4590. const crossFileCalls = cg
  4591. .getNodesByKind('file')
  4592. .flatMap((f) => cg.getOutgoingEdges(f.id))
  4593. .concat(
  4594. cg.getNodesByKind('function').flatMap((f) => cg.getOutgoingEdges(f.id)),
  4595. cg.getNodesByKind('variable').flatMap((v) => cg.getOutgoingEdges(v.id))
  4596. )
  4597. .filter((e) => e.kind === 'calls')
  4598. .map((e) => {
  4599. const src = cg.getNode(e.source);
  4600. const tgt = cg.getNode(e.target);
  4601. return { from: src?.filePath, to: tgt?.filePath, name: tgt?.name };
  4602. });
  4603. // No calls edge may cross files by bare-name matching.
  4604. expect(crossFileCalls.filter((e) => e.from !== e.to)).toEqual([]);
  4605. // The same-file chain still resolves: mkPort's mkOption call hits
  4606. // alpha.nix's own inherit binding.
  4607. const sameFile = crossFileCalls.filter((e) => e.from === e.to && e.name === 'mkOption');
  4608. expect(sameFile.length).toBeGreaterThan(0);
  4609. expect(sameFile.every((e) => e.from === 'alpha.nix' || e.from === 'beta.nix')).toBe(true);
  4610. });
  4611. it('does not resolve Nix angle-bracket, attribute, or variable imports as project file edges', async () => {
  4612. fs.writeFileSync(path.join(tempDir, 'nixpkgs.nix'), '{ bogus = true; }');
  4613. fs.writeFileSync(path.join(tempDir, 'selectedPath.nix'), '{ bogus = true; }');
  4614. fs.writeFileSync(
  4615. path.join(tempDir, 'main.nix'),
  4616. `let
  4617. pkgs = import <nixpkgs> {};
  4618. fromSources = import sources.nixpkgs {};
  4619. dynamic = import selectedPath;
  4620. in
  4621. {
  4622. inherit pkgs fromSources dynamic;
  4623. }
  4624. `
  4625. );
  4626. cg = await CodeGraph.init(tempDir, { index: true });
  4627. cg.resolveReferences();
  4628. expect(importedFilePaths('main.nix')).toEqual([]);
  4629. });
  4630. });
  4631. });