resolution.test.ts 236 KB

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