resolution.test.ts 238 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999
  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 built-in string method off an unrelated project method (#1840)', async () => {
  2178. fs.writeFileSync(path.join(tempDir, 'strings.ts'), `
  2179. export async function listPaths(): Promise<string> { return "a\0b"; }
  2180. export async function snapshot(): Promise<string[]> {
  2181. const listed = await listPaths();
  2182. return listed.split('\0');
  2183. }
  2184. `);
  2185. fs.writeFileSync(path.join(tempDir, 'pane.ts'), `
  2186. export class PaneManager {
  2187. split(): string { return "new pane"; }
  2188. }
  2189. `);
  2190. cg = await CodeGraph.init(tempDir, { index: true });
  2191. cg.resolveReferences();
  2192. const caller = cg.getNodesByName('snapshot').find((n) => n.kind === 'function');
  2193. expect(caller).toBeDefined();
  2194. expect(
  2195. cg.getCallees(caller!.id)
  2196. .filter(({ edge }) => edge.kind === 'calls')
  2197. .map(({ node }) => node.qualifiedName)
  2198. .sort(),
  2199. ).toEqual(['listPaths']);
  2200. });
  2201. it('types an awaited receiver from the callee\'s declared return (#1840)', async () => {
  2202. fs.writeFileSync(path.join(tempDir, 'engine.ts'), `
  2203. export class Engine {
  2204. run(): string { return "ran"; }
  2205. }
  2206. export class Decoy {
  2207. run(): string { return "decoy"; }
  2208. }
  2209. export async function makeEngine(): Promise<Engine> { return new Engine(); }
  2210. export async function drive(): Promise<string> {
  2211. const handle = await makeEngine();
  2212. return handle.run();
  2213. }
  2214. `);
  2215. cg = await CodeGraph.init(tempDir, { index: true });
  2216. cg.resolveReferences();
  2217. const caller = cg.getNodesByName('drive').find((n) => n.kind === 'function');
  2218. expect(caller).toBeDefined();
  2219. expect(
  2220. cg.getCallees(caller!.id)
  2221. .filter(({ edge }) => edge.kind === 'calls')
  2222. .map(({ node }) => node.qualifiedName)
  2223. .sort(),
  2224. ).toEqual(['Engine::run', 'makeEngine']);
  2225. });
  2226. it('keeps a validated project class that shadows Map (#1566)', async () => {
  2227. fs.writeFileSync(path.join(tempDir, 'shadow.ts'), `
  2228. export class Map { get() { return 1; } }
  2229. export class Other { get() { return 2; } }
  2230. export function useShadow() {
  2231. const values = new Map();
  2232. return values.get();
  2233. }
  2234. `);
  2235. cg = await CodeGraph.init(tempDir, { index: true });
  2236. const caller = cg.getNodesByName('useShadow').find((n) => n.kind === 'function');
  2237. expect(caller).toBeDefined();
  2238. expect(cg.getCallees(caller!.id).filter(({ edge }) => edge.kind === 'calls').map(({ node }) => node.qualifiedName))
  2239. .toEqual(['Map::get']);
  2240. });
  2241. it.each([
  2242. ['Set', 'has'], ['WeakMap', 'get'], ['WeakSet', 'has'], ['Array', 'map'], ['Promise', 'then'],
  2243. ])('declines same-name guesses for an inferred %s receiver (#1566)', async (type, method) => {
  2244. fs.writeFileSync(path.join(tempDir, 'builtin.ts'), `
  2245. export class Collision { ${method}() { return 1; } }
  2246. export function constructed() {
  2247. const values = new ${type}();
  2248. return values.${method}();
  2249. }
  2250. export function annotated(values: ${type}<string>) {
  2251. return values.${method}();
  2252. }
  2253. `);
  2254. cg = await CodeGraph.init(tempDir, { index: true });
  2255. cg.resolveReferences();
  2256. expect(cg.getNodesByKind('method').some((n) => n.name === method)).toBe(true);
  2257. for (const name of ['constructed', 'annotated']) {
  2258. const caller = cg.getNodesByName(name).find((n) => n.kind === 'function');
  2259. expect(caller, name).toBeDefined();
  2260. expect.soft(cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls'), name).toEqual([]);
  2261. }
  2262. });
  2263. // `lg.log()` where `lg` is a local whose type is inferred from its
  2264. // declaration/initializer. Before this, only C++ resolved these; every
  2265. // other language produced no method edge. Each case is one file with a
  2266. // single Logger + a caller using a local-variable receiver — a correct
  2267. // resolution makes the caller a caller of `log`.
  2268. const cases: Array<{ lang: string; file: string; src: string }> = [
  2269. { lang: 'TypeScript (= new T)', file: 'svc.ts',
  2270. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  2271. { lang: 'JavaScript (= new T)', file: 'svc.js',
  2272. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  2273. { lang: 'Python (= T())', file: 'svc.py',
  2274. src: `class Logger:\n def log(self):\n return 1\ndef use():\n lg = Logger()\n return lg.log()\n` },
  2275. { lang: 'Java (T x = new T)', file: 'Svc.java',
  2276. src: `class Logger { void log() { int a = 1; } }\nclass Use { void run() { Logger lg = new Logger(); lg.log(); } }\n` },
  2277. { lang: 'C# (var x = new T)', file: 'Svc.cs',
  2278. src: `class Logger { void Log() { int a = 1; } }\nclass Use { void Run() { var lg = new Logger(); lg.Log(); } }\n` },
  2279. { lang: 'Kotlin (val x = T())', file: 'Svc.kt',
  2280. src: `class Logger { fun log(): Int { return 1 } }\nfun use(): Int { val lg = Logger(); return lg.log() }\n` },
  2281. { lang: 'Swift (let x = T())', file: 'svc.swift',
  2282. src: `class Logger { func log() -> Int { return 1 } }\nfunc use() -> Int { let lg = Logger(); return lg.log() }\n` },
  2283. { lang: 'Go (x := T{})', file: 'svc.go',
  2284. src: `package a\ntype Logger struct{}\nfunc (l Logger) Log() int { return 1 }\nfunc Use() int { lg := Logger{}; return lg.Log() }\n` },
  2285. { lang: 'Rust (let x = T{})', file: 'svc.rs',
  2286. 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` },
  2287. { lang: 'Dart (var x = T())', file: 'svc.dart',
  2288. src: `class Logger { int log() { return 1; } }\nint use() { var lg = Logger(); return lg.log(); }\n` },
  2289. { lang: 'PHP ($x = new T)', file: 'svc.php',
  2290. src: `<?php\nclass Logger { function log() { return 1; } }\nfunction useIt() { $lg = new Logger(); return $lg->log(); }\n` },
  2291. { lang: 'Scala (val x = new T)', file: 'Svc.scala',
  2292. src: `class Logger { def log(): Int = 1 }\nobject A { def use(): Int = { val lg = new Logger(); lg.log() } }\n` },
  2293. { lang: 'Ruby (x = T.new)', file: 'svc.rb',
  2294. src: `class Logger\n def log\n 1\n end\nend\ndef use\n lg = Logger.new\n lg.log\nend\n` },
  2295. { lang: 'Lua (x = T.new(); x:log())', file: 'svc.lua',
  2296. 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` },
  2297. { lang: 'Luau (x = T.new(); x:log())', file: 'svc.luau',
  2298. 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` },
  2299. { lang: 'R (x <- T$new(); x$log())', file: 'svc.R',
  2300. src: `Logger <- R6::R6Class("Logger", public = list(log = function() 1))\nuse <- function() { lg <- Logger$new(); lg$log() }\n` },
  2301. { lang: 'Pascal (var x: T; x.Method)', file: 'svc.pas',
  2302. 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` },
  2303. ];
  2304. for (const c of cases) {
  2305. it(`resolves a local-variable method call — ${c.lang}`, async () => {
  2306. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  2307. cg = await CodeGraph.init(tempDir, { index: true });
  2308. cg.resolveReferences();
  2309. const logMethod = cg
  2310. .getNodesByKind('method')
  2311. .find((n) => n.name.toLowerCase() === 'log');
  2312. expect(logMethod, `${c.lang}: log method should be indexed`).toBeDefined();
  2313. // The enclosing caller resolves through the local variable to `log`.
  2314. const callers = cg.getCallers(logMethod!.id).map((x) => x.node.name);
  2315. expect(
  2316. callers.length,
  2317. `${c.lang}: log should have a caller (got [${callers.join(', ')}])`,
  2318. ).toBeGreaterThan(0);
  2319. });
  2320. }
  2321. it('Ruby: builds receiver.method and keeps Foo.new as an instantiation', async () => {
  2322. // The Ruby extractor previously took the receiver as the callee and
  2323. // dropped the method name (`lg.log()` -> a call to `lg`). Now it builds
  2324. // `lg.log`, while `Logger.new` must still record an instantiation.
  2325. fs.writeFileSync(
  2326. path.join(tempDir, 'svc.rb'),
  2327. `class Logger\n def log\n 1\n end\nend\ndef run\n lg = Logger.new\n lg.log\nend\n`,
  2328. );
  2329. cg = await CodeGraph.init(tempDir, { index: true });
  2330. cg.resolveReferences();
  2331. const run = cg.getNodesByKind('function').find((n) => n.name === 'run')!;
  2332. const logMethod = cg.getNodesByKind('method').find((n) => n.name === 'log')!;
  2333. const logger = cg.getNodesByKind('class').find((n) => n.name === 'Logger')!;
  2334. const out = cg.getOutgoingEdges(run.id);
  2335. // lg.log resolved to the method (the receiver-type inference kicked in).
  2336. expect(out.some((e) => e.kind === 'calls' && e.target === logMethod.id)).toBe(true);
  2337. // Logger.new is still an instantiation of the class.
  2338. expect(out.some((e) => e.kind === 'instantiates' && e.target === logger.id)).toBe(true);
  2339. });
  2340. it('TypeScript: infers a typed-parameter receiver, disambiguating same-named methods (#1125)', async () => {
  2341. // A typed function parameter used as a receiver — `function use(lg: Logger)`
  2342. // — never matched the old TS/JS pattern (it required a const|let|var
  2343. // prefix), so `lg.log()` fell through to no edge once a second class shared
  2344. // the method name. Two ambiguous classes are load-bearing here: a
  2345. // single-class version resolves via a same-name fallback even without
  2346. // inference, so only the collision proves type inference actually fired.
  2347. fs.writeFileSync(
  2348. path.join(tempDir, 'svc.ts'),
  2349. `class Logger { log() { return 1; } }\n` +
  2350. `class Other { log() { return 2; } }\n` +
  2351. `export function use(lg: Logger) { return lg.log(); }\n` +
  2352. `export function useOther(o: Other) { return o.log(); }\n`,
  2353. );
  2354. cg = await CodeGraph.init(tempDir, { index: true });
  2355. cg.resolveReferences();
  2356. const classes = cg.getNodesByKind('class');
  2357. const logger = classes.find((n) => n.name === 'Logger')!;
  2358. const other = classes.find((n) => n.name === 'Other')!;
  2359. const logs = cg.getNodesByKind('method').filter((n) => n.name === 'log');
  2360. expect(logs.length, 'both log methods should be indexed').toBe(2);
  2361. // Associate each same-named `log` with its class by line containment.
  2362. const inClass = (m: (typeof logs)[number], c: typeof logger) =>
  2363. m.startLine >= c.startLine && m.startLine <= (c.endLine ?? c.startLine);
  2364. const loggerLog = logs.find((m) => inClass(m, logger))!;
  2365. const otherLog = logs.find((m) => inClass(m, other))!;
  2366. expect(loggerLog, "Logger's log").toBeDefined();
  2367. expect(otherLog, "Other's log").toBeDefined();
  2368. const loggerCallers = cg.getCallers(loggerLog.id).map((x) => x.node.name);
  2369. const otherCallers = cg.getCallers(otherLog.id).map((x) => x.node.name);
  2370. // Each typed-param call routes to its OWN class's method, not the other's.
  2371. expect(loggerCallers).toContain('use');
  2372. expect(loggerCallers).not.toContain('useOther');
  2373. expect(otherCallers).toContain('useOther');
  2374. expect(otherCallers).not.toContain('use');
  2375. });
  2376. // The same typed-parameter gap existed in every language whose pattern set
  2377. // only matched keyword-anchored locals (let/var/:=/= new), not the bare
  2378. // parameter form — Rust, Go, Dart, PHP (#1125). Each case: two classes
  2379. // sharing a method name + two functions taking one as a typed param; a
  2380. // correct fix routes each call to its OWN type's method (the collision is
  2381. // load-bearing — a single class resolves via the same-name fallback either
  2382. // way). Method↔type association is by qualifiedName, robust where the method
  2383. // lives outside the type's line range (Rust `impl`, Go method decl).
  2384. const typedParamCases: Array<{
  2385. lang: string; file: string; method: string; callerA: string; callerB: string; src: string;
  2386. }> = [
  2387. { lang: 'Rust (fn f(x: &T))', file: 'svc.rs', method: 'log', callerA: 'use_it', callerB: 'use_other',
  2388. 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` },
  2389. { lang: 'Go (func f(x T))', file: 'svc.go', method: 'Log', callerA: 'UseIt', callerB: 'UseOther',
  2390. 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` },
  2391. { lang: 'Dart (T f(U x))', file: 'svc.dart', method: 'log', callerA: 'useIt', callerB: 'useOther',
  2392. 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` },
  2393. { lang: 'PHP (f(T $x))', file: 'svc.php', method: 'log', callerA: 'useIt', callerB: 'useOther',
  2394. 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` },
  2395. ];
  2396. for (const c of typedParamCases) {
  2397. it(`infers a typed-parameter receiver, disambiguating same-named methods — ${c.lang} (#1125)`, async () => {
  2398. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  2399. cg = await CodeGraph.init(tempDir, { index: true });
  2400. cg.resolveReferences();
  2401. const methods = cg.getNodesByKind('method').filter((n) => n.name === c.method);
  2402. expect(methods.length, `${c.lang}: both ${c.method} methods indexed`).toBe(2);
  2403. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  2404. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  2405. expect(loggerLog, `${c.lang}: Logger's ${c.method}`).toBeDefined();
  2406. expect(otherLog, `${c.lang}: Other's ${c.method}`).toBeDefined();
  2407. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  2408. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  2409. expect(loggerCallers, `${c.lang}: Logger callers`).toContain(c.callerA);
  2410. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain(c.callerB);
  2411. expect(otherCallers, `${c.lang}: Other callers`).toContain(c.callerB);
  2412. expect(otherCallers, `${c.lang}: Other callers`).not.toContain(c.callerA);
  2413. });
  2414. }
  2415. // Lua/Luau: a PascalCase method call (`lg:Log()`, the Roblox convention)
  2416. // is the identical `receiver:Name` shape as a Luau type annotation, so it
  2417. // self-matched the annotation pattern on the call's own line and inferred
  2418. // "type = Log" (#1124). Two things are load-bearing in these fixtures:
  2419. // the declaration sits on an EARLIER line than the call (on one line,
  2420. // pattern order resolves it — the `.new` pattern wins first), and TWO
  2421. // classes share the method name (a single class resolves via the
  2422. // same-name fallback even when inference misfires). Luau's `useLogger`
  2423. // takes a typed param instead of calling `.new()`, pinning that the
  2424. // gated pattern still matches a genuine annotation.
  2425. const pascalMethodCases: Array<{ lang: string; file: string; src: string }> = [
  2426. { lang: 'Lua', file: 'svc.lua',
  2427. 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` },
  2428. { lang: 'Luau', file: 'svc.luau',
  2429. 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` },
  2430. ];
  2431. for (const c of pascalMethodCases) {
  2432. it(`resolves a PascalCase method call without self-matching the annotation pattern — ${c.lang} (#1124)`, async () => {
  2433. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  2434. cg = await CodeGraph.init(tempDir, { index: true });
  2435. cg.resolveReferences();
  2436. const methods = cg.getNodesByKind('method').filter((n) => n.name === 'Log');
  2437. expect(methods.length, `${c.lang}: both Log methods indexed`).toBe(2);
  2438. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  2439. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  2440. expect(loggerLog, `${c.lang}: Logger's Log`).toBeDefined();
  2441. expect(otherLog, `${c.lang}: Other's Log`).toBeDefined();
  2442. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  2443. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  2444. expect(loggerCallers, `${c.lang}: Logger callers`).toContain('useLogger');
  2445. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain('useOther');
  2446. expect(otherCallers, `${c.lang}: Other callers`).toContain('useOther');
  2447. expect(otherCallers, `${c.lang}: Other callers`).not.toContain('useLogger');
  2448. });
  2449. }
  2450. });
  2451. describe('Name Matcher: kind bias for new ref kinds', () => {
  2452. const baseContext = (candidates: Node[]): ResolutionContext => ({
  2453. getNodesInFile: () => [],
  2454. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  2455. getNodesByQualifiedName: () => [],
  2456. getNodesByKind: () => [],
  2457. fileExists: () => true,
  2458. readFile: () => null,
  2459. getProjectRoot: () => '/test',
  2460. getAllFiles: () => [],
  2461. getNodesByLowerName: () => [],
  2462. getImportMappings: () => [],
  2463. });
  2464. it('prefers a class candidate over a function for `instantiates` refs', () => {
  2465. // A class and a function share a name across the codebase.
  2466. // Without the kind bias, the function (which gets the +25 `calls`
  2467. // bonus historically applied to all candidates of that kind) would
  2468. // win. Now the instantiates branch reverses it.
  2469. const fn: Node = {
  2470. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  2471. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  2472. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2473. };
  2474. const cls: Node = {
  2475. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  2476. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  2477. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2478. };
  2479. const ref = {
  2480. fromNodeId: 'func:main.ts:bootstrap:1',
  2481. referenceName: 'Logger',
  2482. referenceKind: 'instantiates' as const,
  2483. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  2484. };
  2485. const result = matchReference(ref, baseContext([fn, cls]));
  2486. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  2487. });
  2488. it('prefers a union candidate over a function for `instantiates` refs', () => {
  2489. const fn: Node = {
  2490. id: 'func:packet.cpp:Packet:5', kind: 'function', name: 'Packet',
  2491. qualifiedName: 'packet.cpp::Packet', filePath: 'packet.cpp', language: 'cpp',
  2492. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2493. };
  2494. const union: Node = {
  2495. id: 'union:packet.hpp:Packet:10', kind: 'union', name: 'Packet',
  2496. qualifiedName: 'packet.hpp::Packet', filePath: 'packet.hpp', language: 'cpp',
  2497. startLine: 10, endLine: 14, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2498. };
  2499. const ref = {
  2500. fromNodeId: 'func:main.cpp:initialize:1',
  2501. referenceName: 'Packet',
  2502. referenceKind: 'instantiates' as const,
  2503. line: 5, column: 0, filePath: 'main.cpp', language: 'cpp' as const,
  2504. };
  2505. const result = matchReference(ref, baseContext([fn, union]));
  2506. expect(result?.targetNodeId).toBe('union:packet.hpp:Packet:10');
  2507. });
  2508. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  2509. const variable: Node = {
  2510. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  2511. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  2512. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2513. };
  2514. const decorator: Node = {
  2515. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  2516. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  2517. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  2518. };
  2519. const ref = {
  2520. fromNodeId: 'class:svc.ts:UserService:1',
  2521. referenceName: 'Inject',
  2522. referenceKind: 'decorates' as const,
  2523. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  2524. };
  2525. const result = matchReference(ref, baseContext([variable, decorator]));
  2526. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  2527. });
  2528. });
  2529. describe('tsconfig path aliases', () => {
  2530. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  2531. // Two same-named exports in different directories. Without alias
  2532. // resolution, name-matcher would pick whichever it finds first;
  2533. // with alias resolution, the import path uniquely picks one.
  2534. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  2535. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  2536. fs.writeFileSync(
  2537. path.join(tempDir, 'src/utils/format.ts'),
  2538. `export function pickMe(): number { return 1; }\n`
  2539. );
  2540. fs.writeFileSync(
  2541. path.join(tempDir, 'src/legacy/format.ts'),
  2542. `export function pickMe(): number { return 99; }\n`
  2543. );
  2544. fs.writeFileSync(
  2545. path.join(tempDir, 'src/main.ts'),
  2546. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  2547. );
  2548. fs.writeFileSync(
  2549. path.join(tempDir, 'tsconfig.json'),
  2550. JSON.stringify({
  2551. compilerOptions: {
  2552. baseUrl: './src',
  2553. paths: { '@utils/*': ['utils/*'] },
  2554. },
  2555. })
  2556. );
  2557. cg = await CodeGraph.init(tempDir, { index: true });
  2558. cg.resolveReferences();
  2559. // The two pickMe nodes live in different files. The aliased
  2560. // import should attach the call edge to the @utils-mapped one,
  2561. // not the legacy duplicate.
  2562. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  2563. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  2564. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  2565. expect(utilsNode).toBeDefined();
  2566. expect(legacyNode).toBeDefined();
  2567. const utilsCallers = cg.getCallers(utilsNode!.id);
  2568. const legacyCallers = cg.getCallers(legacyNode!.id);
  2569. expect(utilsCallers.length).toBeGreaterThan(0);
  2570. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2571. // The legacy node should NOT have a caller from src/main.ts —
  2572. // the alias correctly picked the utils version.
  2573. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  2574. });
  2575. it('falls back gracefully when tsconfig is absent', async () => {
  2576. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2577. fs.writeFileSync(
  2578. path.join(tempDir, 'src/a.ts'),
  2579. `export function aFn(): void {}\n`
  2580. );
  2581. fs.writeFileSync(
  2582. path.join(tempDir, 'src/b.ts'),
  2583. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  2584. );
  2585. cg = await CodeGraph.init(tempDir, { index: true });
  2586. // No tsconfig present — index should still complete and the
  2587. // relative-import-based call edge should be created.
  2588. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  2589. expect(aFn).toBeDefined();
  2590. const callers = cg.getCallers(aFn!.id);
  2591. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  2592. });
  2593. });
  2594. describe('re-export chain following', () => {
  2595. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  2596. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  2597. // Without chain following, `signIn` resolves to nothing because
  2598. // none of the barrel files declare it directly.
  2599. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  2600. fs.writeFileSync(
  2601. path.join(tempDir, 'src/services/auth.ts'),
  2602. `export function signIn(): void {}\n`
  2603. );
  2604. fs.writeFileSync(
  2605. path.join(tempDir, 'src/services/index.ts'),
  2606. `export { signIn } from './auth';\n`
  2607. );
  2608. fs.writeFileSync(
  2609. path.join(tempDir, 'src/all.ts'),
  2610. `export * from './services/index';\n`
  2611. );
  2612. fs.writeFileSync(
  2613. path.join(tempDir, 'src/main.ts'),
  2614. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  2615. );
  2616. cg = await CodeGraph.init(tempDir, { index: true });
  2617. cg.resolveReferences();
  2618. const signInNode = cg
  2619. .getNodesByKind('function')
  2620. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  2621. expect(signInNode).toBeDefined();
  2622. const callers = cg.getCallers(signInNode!.id);
  2623. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2624. });
  2625. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  2626. // The chase has to look up `foo` in the upstream module even
  2627. // though the importer asked for `bar` — exercises the rename
  2628. // branch of findExportedSymbol.
  2629. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2630. fs.writeFileSync(
  2631. path.join(tempDir, 'src/auth.ts'),
  2632. `export function signIn(): void {}\n`
  2633. );
  2634. fs.writeFileSync(
  2635. path.join(tempDir, 'src/index.ts'),
  2636. `export { signIn as login } from './auth';\n`
  2637. );
  2638. fs.writeFileSync(
  2639. path.join(tempDir, 'src/main.ts'),
  2640. `import { login } from './index';\nexport function go(): void { login(); }\n`
  2641. );
  2642. cg = await CodeGraph.init(tempDir, { index: true });
  2643. cg.resolveReferences();
  2644. const signInNode = cg
  2645. .getNodesByKind('function')
  2646. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  2647. expect(signInNode).toBeDefined();
  2648. const callers = cg.getCallers(signInNode!.id);
  2649. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2650. });
  2651. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  2652. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  2653. // .svelte component (extracted as kind 'component', the default
  2654. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  2655. // component's real name (`RealButton`) so the name-matcher fallback
  2656. // can't coincidentally connect them — the only path to the edge is
  2657. // the import-chase, which must match a `component` (not just
  2658. // function/class) for the default export. Otherwise the
  2659. // consumer↔component edge is never created and `callers` returns a
  2660. // false 0.
  2661. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2662. fs.writeFileSync(
  2663. path.join(tempDir, 'src/lib/RealButton.svelte'),
  2664. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2665. );
  2666. fs.writeFileSync(
  2667. path.join(tempDir, 'src/lib/index.ts'),
  2668. `export { default as Foo } from './RealButton.svelte';\n`
  2669. );
  2670. fs.writeFileSync(
  2671. path.join(tempDir, 'src/Bar.svelte'),
  2672. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  2673. );
  2674. cg = await CodeGraph.init(tempDir, { index: true });
  2675. cg.resolveReferences();
  2676. const fooNode = cg
  2677. .getNodesByKind('component')
  2678. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  2679. expect(fooNode).toBeDefined();
  2680. const callers = cg.getCallers(fooNode!.id);
  2681. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  2682. });
  2683. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  2684. // The canonical Astro shape: a page imports a layout/component in
  2685. // frontmatter and uses it as a template tag; the component's template
  2686. // calls an imported .ts util. Both hops must produce graph edges or
  2687. // an Astro project is invisible to callers/impact.
  2688. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  2689. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  2690. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  2691. fs.writeFileSync(
  2692. path.join(tempDir, 'src/utils/format.ts'),
  2693. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  2694. );
  2695. fs.writeFileSync(
  2696. path.join(tempDir, 'src/components/PostCard.astro'),
  2697. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  2698. );
  2699. fs.writeFileSync(
  2700. path.join(tempDir, 'src/pages/index.astro'),
  2701. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  2702. );
  2703. cg = await CodeGraph.init(tempDir, { index: true });
  2704. cg.resolveReferences();
  2705. // Hop 1: page → component (template tag through the frontmatter import)
  2706. const cardNode = cg
  2707. .getNodesByKind('component')
  2708. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  2709. expect(cardNode).toBeDefined();
  2710. const cardCallers = cg.getCallers(cardNode!.id);
  2711. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  2712. // Hop 2: component template call → .ts util
  2713. const fmtNode = cg
  2714. .getNodesByKind('function')
  2715. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  2716. expect(fmtNode).toBeDefined();
  2717. const fmtCallers = cg.getCallers(fmtNode!.id);
  2718. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  2719. });
  2720. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  2721. // `import { helper } from '.'` (or './') must map to the
  2722. // directory's index.ts before the re-export chase can run. The
  2723. // barrel renames `realHelper` → `helper` so the name-matcher can't
  2724. // mask a path-resolution failure: only the bare-dir resolution +
  2725. // rename chase can connect the edge.
  2726. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2727. fs.writeFileSync(
  2728. path.join(tempDir, 'src/util.ts'),
  2729. `export function realHelper(): void {}\n`
  2730. );
  2731. fs.writeFileSync(
  2732. path.join(tempDir, 'src/index.ts'),
  2733. `export { realHelper as helper } from './util';\n`
  2734. );
  2735. fs.writeFileSync(
  2736. path.join(tempDir, 'src/main.ts'),
  2737. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  2738. );
  2739. fs.writeFileSync(
  2740. path.join(tempDir, 'src/main2.ts'),
  2741. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  2742. );
  2743. cg = await CodeGraph.init(tempDir, { index: true });
  2744. cg.resolveReferences();
  2745. const helperNode = cg
  2746. .getNodesByKind('function')
  2747. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  2748. expect(helperNode).toBeDefined();
  2749. const callers = cg.getCallers(helperNode!.id);
  2750. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  2751. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  2752. });
  2753. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  2754. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  2755. // `widgets/` subdir index, which re-exports a .svelte component.
  2756. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  2757. // only workspace-package resolution can connect the edge.
  2758. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  2759. fs.writeFileSync(
  2760. path.join(tempDir, 'package.json'),
  2761. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  2762. );
  2763. fs.writeFileSync(
  2764. path.join(tempDir, 'packages/ui/package.json'),
  2765. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  2766. );
  2767. fs.writeFileSync(
  2768. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  2769. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  2770. );
  2771. fs.writeFileSync(
  2772. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  2773. `export { default as Thing } from './Widget.svelte';\n`
  2774. );
  2775. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  2776. fs.writeFileSync(
  2777. path.join(tempDir, 'app/App.svelte'),
  2778. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  2779. );
  2780. cg = await CodeGraph.init(tempDir, { index: true });
  2781. cg.resolveReferences();
  2782. const buttonNode = cg
  2783. .getNodesByKind('component')
  2784. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  2785. expect(buttonNode).toBeDefined();
  2786. const callers = cg.getCallers(buttonNode!.id);
  2787. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  2788. });
  2789. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  2790. // The same import-resolution gaps (no SFC import mappings, no SFC
  2791. // extension list, barrel parsed in the consumer's language) broke
  2792. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  2793. // The barrel renames `realRun` → `run` so only the import-chase (not
  2794. // the name-matcher) can connect the call.
  2795. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  2796. fs.writeFileSync(
  2797. path.join(tempDir, 'src/util.ts'),
  2798. `export function realRun(): void {}\n`
  2799. );
  2800. fs.writeFileSync(
  2801. path.join(tempDir, 'src/index.ts'),
  2802. `export { realRun as run } from './util';\n`
  2803. );
  2804. fs.writeFileSync(
  2805. path.join(tempDir, 'src/App.vue'),
  2806. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  2807. );
  2808. cg = await CodeGraph.init(tempDir, { index: true });
  2809. cg.resolveReferences();
  2810. const runNode = cg
  2811. .getNodesByKind('function')
  2812. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  2813. expect(runNode).toBeDefined();
  2814. const callers = cg.getCallers(runNode!.id);
  2815. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2816. });
  2817. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  2818. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  2819. // component re-exported under an alias (`Thing`) that differs from its
  2820. // real name (`Widget`), and the consumer uses it ONLY in markup
  2821. // (`<Thing />`). Requires both the new template-tag extraction AND the
  2822. // barrel default-export chase to connect the edge.
  2823. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2824. fs.writeFileSync(
  2825. path.join(tempDir, 'src/lib/Widget.vue'),
  2826. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  2827. );
  2828. fs.writeFileSync(
  2829. path.join(tempDir, 'src/lib/index.ts'),
  2830. `export { default as Thing } from './Widget.vue';\n`
  2831. );
  2832. fs.writeFileSync(
  2833. path.join(tempDir, 'src/App.vue'),
  2834. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  2835. );
  2836. cg = await CodeGraph.init(tempDir, { index: true });
  2837. cg.resolveReferences();
  2838. const widgetNode = cg
  2839. .getNodesByKind('component')
  2840. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  2841. expect(widgetNode).toBeDefined();
  2842. const callers = cg.getCallers(widgetNode!.id);
  2843. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2844. });
  2845. });
  2846. describe('Literal receivers and nested-local scope (#1230)', () => {
  2847. // Two stacked fabrications: `", ".join(...)` (a builtin on a string
  2848. // literal) exact-matched a project function named `join` — one that was
  2849. // moreover nested inside a DIFFERENT function and thus lexically
  2850. // unreachable. Literal receivers now emit no call ref at all, and
  2851. // exact-match refuses candidates nested in a function the ref isn't in.
  2852. it("str-literal builtin calls don't bind to project symbols; nested locals only resolve from inside their container", async () => {
  2853. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1230-'));
  2854. try {
  2855. fs.writeFileSync(
  2856. path.join(tmpDir, 'repro.py'),
  2857. `def format_fields(values):
  2858. def join(vals):
  2859. return "-".join(sorted(vals))
  2860. return join(values)
  2861. def report_missing(unresolved):
  2862. missing_list = ", ".join(sorted(unresolved))
  2863. return f"Could not resolve: {missing_list}"
  2864. `
  2865. );
  2866. const cg = CodeGraph.initSync(tmpDir);
  2867. await cg.indexAll();
  2868. const join = (await cg.searchNodes('join', { limit: 5 })).find(
  2869. (r) => r.node.kind === 'function' && r.node.name === 'join'
  2870. );
  2871. expect(join).toBeDefined();
  2872. // Exactly one caller: the enclosing format_fields. Neither
  2873. // report_missing (literal receiver) nor join itself (its own literal
  2874. // "-".join) may appear.
  2875. const callers = await cg.getCallers(join!.node.id);
  2876. expect(callers.map((c) => c.node.name)).toEqual(['format_fields']);
  2877. // report_missing has zero project callees.
  2878. const reportMissing = (await cg.searchNodes('report_missing', { limit: 5 })).find(
  2879. (r) => r.node.kind === 'function'
  2880. );
  2881. const callees = await cg.getCallees(reportMissing!.node.id);
  2882. expect(callees.filter((c) => c.node.name === 'join')).toHaveLength(0);
  2883. cg.close();
  2884. } finally {
  2885. fs.rmSync(tmpDir, { recursive: true, force: true });
  2886. }
  2887. }, 30000);
  2888. });
  2889. describe('Go field-chain receiver calls (#1276)', () => {
  2890. // `target.conn.Exec(...)` where `conn *sql.DB` used to emit a BARE `Exec`
  2891. // ref, which exact-matched the only local `Exec` — an unrelated
  2892. // interface's method — fabricating an internal dependency. Chained Go
  2893. // receivers now resolve exclusively via validated field-hop inference:
  2894. // external field types produce NO edge; in-project ones produce the
  2895. // correct edge (new recall).
  2896. it('external receiver types produce no edge; in-project field chains resolve correctly', async () => {
  2897. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1276-'));
  2898. try {
  2899. fs.writeFileSync(path.join(tmpDir, 'go.mod'), 'module example.com/app\n\ngo 1.22\n');
  2900. fs.mkdirSync(path.join(tmpDir, 'flow'));
  2901. fs.writeFileSync(
  2902. path.join(tmpDir, 'flow', 'flow.go'),
  2903. `package flow
  2904. import "database/sql"
  2905. type InternalStore interface {
  2906. Exec(string, ...any) (sql.Result, error)
  2907. QueryRow(string, ...any) *sql.Row
  2908. }
  2909. type Target struct{ conn *sql.DB }
  2910. func (target *Target) Write() error {
  2911. _, err := target.conn.Exec("insert")
  2912. return err
  2913. }
  2914. func (target *Target) Read() *sql.Row {
  2915. return target.conn.QueryRow("select")
  2916. }
  2917. type Store struct{}
  2918. func (s *Store) Put(key string) {}
  2919. type Repo struct{ db *Store }
  2920. func (r *Repo) Save() {
  2921. r.db.Put("k")
  2922. }
  2923. `
  2924. );
  2925. const cg = CodeGraph.initSync(tmpDir);
  2926. await cg.indexAll();
  2927. // The unrelated local interface's methods have NO callers — the
  2928. // external sql.DB calls must not bind to them.
  2929. const execDecl = (await cg.searchNodes('Exec', { limit: 10 })).find(
  2930. (r) => r.node.kind === 'method'
  2931. );
  2932. if (execDecl) {
  2933. const execCallers = await cg.getCallers(execDecl.node.id);
  2934. expect(execCallers.map((c) => c.node.name)).not.toContain('Write');
  2935. }
  2936. const qrDecl = (await cg.searchNodes('QueryRow', { limit: 10 })).find(
  2937. (r) => r.node.kind === 'method'
  2938. );
  2939. if (qrDecl) {
  2940. const qrCallers = await cg.getCallers(qrDecl.node.id);
  2941. expect(qrCallers.map((c) => c.node.name)).not.toContain('Read');
  2942. }
  2943. // The in-project field chain resolves (validated), gaining an edge the
  2944. // bare-name era never produced.
  2945. const put = (await cg.searchNodes('Put', { limit: 10 })).find(
  2946. (r) => r.node.kind === 'method' && r.node.qualifiedName?.includes('Store')
  2947. );
  2948. expect(put).toBeDefined();
  2949. const putCallers = await cg.getCallers(put!.node.id);
  2950. expect(putCallers.map((c) => c.node.name)).toContain('Save');
  2951. cg.close();
  2952. } finally {
  2953. fs.rmSync(tmpDir, { recursive: true, force: true });
  2954. }
  2955. }, 30000);
  2956. it('unexported field types resolve; stdlib-qualified types never bind a same-named local decoy', async () => {
  2957. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1276b-'));
  2958. try {
  2959. fs.writeFileSync(path.join(tmpDir, 'go.mod'), 'module example.com/b\n\ngo 1.22\n');
  2960. fs.writeFileSync(
  2961. path.join(tmpDir, 'm.go'),
  2962. `package m
  2963. import "net/http"
  2964. type node struct{}
  2965. func (n *node) InsertRoute(path string) {}
  2966. // A local type sharing the stdlib interface's name — the decoy the
  2967. // package-qualifier gate exists for.
  2968. type Handler func()
  2969. func (h Handler) ServeHTTP() {}
  2970. type Mux struct {
  2971. // the tree router lives below this comment (the comment must not
  2972. // donate a field type)
  2973. handler http.Handler
  2974. tree *node
  2975. }
  2976. func (mx *Mux) handle(path string) {
  2977. mx.tree.InsertRoute(path)
  2978. }
  2979. func (mx *Mux) dispatch() {
  2980. mx.handler.ServeHTTP(nil, nil)
  2981. }
  2982. `
  2983. );
  2984. const cg = CodeGraph.initSync(tmpDir);
  2985. await cg.indexAll();
  2986. // Unexported in-package field type: chain resolves (chi's mx.tree shape),
  2987. // and the doc comment above the field donates nothing.
  2988. const insert = (await cg.searchNodes('InsertRoute', { limit: 5 })).find(
  2989. (r) => r.node.kind === 'method'
  2990. );
  2991. expect(insert).toBeDefined();
  2992. const insertCallers = await cg.getCallers(insert!.node.id);
  2993. expect(insertCallers.map((c) => c.node.name)).toContain('handle');
  2994. // `handler http.Handler` is stdlib — the call must NOT bind to the
  2995. // local decoy `Handler.ServeHTTP`.
  2996. const serve = (await cg.searchNodes('ServeHTTP', { limit: 5 })).find(
  2997. (r) => r.node.kind === 'method'
  2998. );
  2999. if (serve) {
  3000. const serveCallers = await cg.getCallers(serve.node.id);
  3001. expect(serveCallers.map((c) => c.node.name)).not.toContain('dispatch');
  3002. }
  3003. cg.close();
  3004. } finally {
  3005. fs.rmSync(tmpDir, { recursive: true, force: true });
  3006. }
  3007. }, 30000);
  3008. });
  3009. describe('Imported singleton instance-method calls (#1292)', () => {
  3010. // `reproStore.notifyJoinGuildStatus()` after `import { reproStore }` used
  3011. // to emit its calls edge to the CONSTANT (resolvedBy:'import'), while the
  3012. // identical call in the defining file resolved to the method — so callers
  3013. // of the method missed every cross-file use. The import path now infers
  3014. // the value's type from its own declaration and resolves the member on it.
  3015. it('cross-file call through an imported singleton resolves to the class method', async () => {
  3016. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1292-'));
  3017. try {
  3018. fs.mkdirSync(path.join(tmpDir, 'src'));
  3019. fs.writeFileSync(
  3020. path.join(tmpDir, 'src', 'store.ts'),
  3021. `export class ReproStore {
  3022. notifyJoinGuildStatus(): void {
  3023. console.log('notified');
  3024. }
  3025. }
  3026. export const reproStore = new ReproStore();
  3027. export function callInDefinitionFile(): void {
  3028. reproStore.notifyJoinGuildStatus();
  3029. }
  3030. `
  3031. );
  3032. fs.writeFileSync(
  3033. path.join(tmpDir, 'src', 'caller.ts'),
  3034. `import { reproStore } from './store';
  3035. export function callFromImportedFile(): void {
  3036. reproStore.notifyJoinGuildStatus();
  3037. }
  3038. `
  3039. );
  3040. const cg = CodeGraph.initSync(tmpDir);
  3041. await cg.indexAll();
  3042. const method = (await cg.searchNodes('notifyJoinGuildStatus', { limit: 5 })).find(
  3043. (r) => r.node.kind === 'method'
  3044. );
  3045. expect(method).toBeDefined();
  3046. // BOTH functions call the method — the cross-file one included.
  3047. const callers = await cg.getCallers(method!.node.id);
  3048. const callerNames = callers.map((c) => c.node.name).sort();
  3049. expect(callerNames).toContain('callInDefinitionFile');
  3050. expect(callerNames).toContain('callFromImportedFile');
  3051. cg.close();
  3052. } finally {
  3053. fs.rmSync(tmpDir, { recursive: true, force: true });
  3054. }
  3055. }, 30000);
  3056. });
  3057. describe('Object-literal namespace members (#1573)', () => {
  3058. // `export const api = { call() {…}, get: () => {…} }` used as the module's
  3059. // API surface: the members are plain functions with bare names inside the
  3060. // constant's extent, so `api.call()` resolved to nothing in the defining
  3061. // file and to the CONSTANT through an import — zero callers everywhere.
  3062. const setup = (files: Record<string, string>) => {
  3063. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1573-'));
  3064. for (const [name, content] of Object.entries(files)) {
  3065. fs.mkdirSync(path.dirname(path.join(tmpDir, name)), { recursive: true });
  3066. fs.writeFileSync(path.join(tmpDir, name), content);
  3067. }
  3068. return tmpDir;
  3069. };
  3070. const callersOf = async (cg: CodeGraph, name: string, kind: string, filePath?: string) => {
  3071. const target = (await cg.searchNodes(name, { limit: 20 })).find(
  3072. (r) => r.node.kind === kind && r.node.name === name && (!filePath || r.node.filePath === filePath)
  3073. );
  3074. expect(target).toBeDefined();
  3075. return (await cg.getCallers(target!.node.id)).map((c) => c.node.name).sort();
  3076. };
  3077. it('resolves same-file and imported calls to the literal member, never to the constant (#1573)', async () => {
  3078. const tmpDir = setup({
  3079. 'a.ts': `export const obj = { m() { return 1; } };
  3080. export class C { static s() { return 2; } }
  3081. export function sameFileCallers() { return obj.m() + C.s(); }
  3082. `,
  3083. 'b.ts': `import { obj, C } from "./a";
  3084. export function crossFileCaller() { return obj.m() + C.s(); }
  3085. `,
  3086. // A same-named top-level function elsewhere must never be chosen.
  3087. 'decoy.ts': `export function m() { return 'decoy'; }
  3088. `,
  3089. });
  3090. try {
  3091. const cg = CodeGraph.initSync(tmpDir);
  3092. await cg.indexAll();
  3093. expect(await callersOf(cg, 'm', 'function', 'a.ts')).toEqual(['crossFileCaller', 'sameFileCallers']);
  3094. expect(await callersOf(cg, 'm', 'function', 'decoy.ts')).toEqual([]);
  3095. // The class static next to it resolves exactly as before (#825).
  3096. expect(await callersOf(cg, 's', 'method')).toEqual(['crossFileCaller', 'sameFileCallers']);
  3097. // The import edge no longer lands on the constant itself.
  3098. const obj = (await cg.searchNodes('obj', { limit: 5 })).find((r) => r.node.kind === 'constant');
  3099. expect(obj).toBeDefined();
  3100. const caller = (await cg.searchNodes('crossFileCaller', { limit: 5 })).find((r) => r.node.kind === 'function');
  3101. const toConstant = cg
  3102. .getOutgoingEdges(caller!.node.id)
  3103. .filter((e) => e.kind === 'calls' && e.target === obj!.node.id);
  3104. expect(toConstant).toHaveLength(0);
  3105. cg.close();
  3106. } finally {
  3107. fs.rmSync(tmpDir, { recursive: true, force: true });
  3108. }
  3109. }, 30000);
  3110. it('covers method and arrow-property members, and skips a declaration nested in a member body', async () => {
  3111. const tmpDir = setup({
  3112. 'src/api.ts': `export const api = {
  3113. call: () => { return 1; },
  3114. get() {
  3115. function call() { return 'nested in get, not a member'; }
  3116. return call();
  3117. },
  3118. };
  3119. `,
  3120. 'src/use.ts': `import { api } from './api';
  3121. export function useCall() { return api.call(); }
  3122. export function useGet() { return api.get(); }
  3123. `,
  3124. });
  3125. try {
  3126. const cg = CodeGraph.initSync(tmpDir);
  3127. await cg.indexAll();
  3128. const calls = (await cg.searchNodes('call', { limit: 20 }))
  3129. .map((r) => r.node)
  3130. .filter((n) => n.name === 'call' && n.filePath === 'src/api.ts' && (n.kind === 'function' || n.kind === 'method'));
  3131. // The member is the arrow on line 2; the nested declaration sits
  3132. // inside `get`'s body on line 4 and must never be taken for it.
  3133. const member = calls.find((n) => n.startLine === 2);
  3134. const nested = calls.find((n) => n.startLine === 4);
  3135. expect(member).toBeDefined();
  3136. expect(nested).toBeDefined();
  3137. expect((await cg.getCallers(member!.id)).map((c) => c.node.name)).toContain('useCall');
  3138. expect((await cg.getCallers(nested!.id)).map((c) => c.node.name)).not.toContain('useCall');
  3139. expect(await callersOf(cg, 'get', 'function')).toEqual(['useGet']);
  3140. cg.close();
  3141. } finally {
  3142. fs.rmSync(tmpDir, { recursive: true, force: true });
  3143. }
  3144. }, 30000);
  3145. it('leaves a non-literal value receiver on its existing path', async () => {
  3146. const tmpDir = setup({
  3147. 'src/mk.ts': `export function m() { return 'top-level, unrelated to obj'; }
  3148. export const obj = makeObj();
  3149. export function makeObj(): { m(): number } { return { m: () => 1 } as { m(): number }; }
  3150. export function localUse() { return obj.m(); }
  3151. `,
  3152. 'src/use.ts': `import { obj } from './mk';
  3153. export function remoteUse() { return obj.m(); }
  3154. `,
  3155. });
  3156. try {
  3157. const cg = CodeGraph.initSync(tmpDir);
  3158. await cg.indexAll();
  3159. // `obj` holds a call result, not a literal: the same-named top-level
  3160. // `m` lies outside its declaration, so containment finds nothing and
  3161. // both calls keep today's behavior (unresolved in the defining file;
  3162. // the constant edge through the import) rather than guessing.
  3163. expect(await callersOf(cg, 'm', 'function')).toEqual([]);
  3164. const obj = (await cg.searchNodes('obj', { limit: 5 })).find((r) => r.node.kind === 'constant');
  3165. const remote = (await cg.searchNodes('remoteUse', { limit: 5 })).find((r) => r.node.kind === 'function');
  3166. expect(
  3167. cg.getOutgoingEdges(remote!.node.id).some((e) => e.kind === 'calls' && e.target === obj!.node.id)
  3168. ).toBe(true);
  3169. cg.close();
  3170. } finally {
  3171. fs.rmSync(tmpDir, { recursive: true, force: true });
  3172. }
  3173. }, 30000);
  3174. });
  3175. describe('C++ namespace-qualified static method calls to out-of-line definitions (#1291)', () => {
  3176. // The issue's exact shape: nested types + out-of-line static method
  3177. // definition inside `namespace simulator { }` in the .cpp, called via the
  3178. // fully-qualified path from a different file. The definition's
  3179. // qualifiedName previously dropped the namespace (`ManifestStartup::Apply`
  3180. // vs the class's `simulator::ManifestStartup`), so `callers` came up empty.
  3181. it('resolves simulator::ManifestStartup::Apply(...) from another file', async () => {
  3182. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1291-'));
  3183. try {
  3184. fs.writeFileSync(
  3185. path.join(tmpDir, 'manifest_startup.h'),
  3186. `#pragma once
  3187. namespace simulator {
  3188. class ManifestStartup {
  3189. public:
  3190. struct Input { int a; };
  3191. struct Output { int b; };
  3192. static Output Apply(const Input& input);
  3193. };
  3194. }
  3195. `
  3196. );
  3197. fs.writeFileSync(
  3198. path.join(tmpDir, 'manifest_startup.cpp'),
  3199. `#include "manifest_startup.h"
  3200. namespace simulator {
  3201. ManifestStartup::Output ManifestStartup::Apply(const Input& input) {
  3202. return Output{input.a};
  3203. }
  3204. }
  3205. `
  3206. );
  3207. fs.writeFileSync(
  3208. path.join(tmpDir, 'main.cpp'),
  3209. `#include "manifest_startup.h"
  3210. int run() {
  3211. const auto manifest_result = simulator::ManifestStartup::Apply({1});
  3212. return manifest_result.b;
  3213. }
  3214. `
  3215. );
  3216. const cg = CodeGraph.initSync(tmpDir);
  3217. await cg.indexAll();
  3218. const applyDefs = (await cg.searchNodes('Apply', { limit: 20 })).filter(
  3219. (r) => r.node.name === 'Apply' && r.node.kind === 'method'
  3220. );
  3221. expect(applyDefs.length).toBeGreaterThan(0);
  3222. const def = applyDefs.find((r) => r.node.filePath.endsWith('manifest_startup.cpp'));
  3223. expect(def).toBeDefined();
  3224. expect(def!.node.qualifiedName).toBe('simulator::ManifestStartup::Apply');
  3225. // The qualified cross-file call resolves: run() is a caller of Apply.
  3226. const callers = await cg.getCallers(def!.node.id);
  3227. expect(callers.map((c) => c.node.name)).toContain('run');
  3228. cg.close();
  3229. } finally {
  3230. fs.rmSync(tmpDir, { recursive: true, force: true });
  3231. }
  3232. }, 30000);
  3233. });
  3234. describe('C/C++ Import Resolution', () => {
  3235. afterEach(() => {
  3236. clearCppIncludeDirCache();
  3237. });
  3238. it('should resolve C include to header in same directory', () => {
  3239. const context: ResolutionContext = {
  3240. getNodesInFile: () => [],
  3241. getNodesByName: () => [],
  3242. getNodesByQualifiedName: () => [],
  3243. getNodesByKind: () => [],
  3244. fileExists: (p) => p === 'utils.h',
  3245. readFile: () => null,
  3246. getProjectRoot: () => '',
  3247. getAllFiles: () => ['utils.h', 'main.c'],
  3248. };
  3249. const result = resolveImportPath(
  3250. 'utils.h',
  3251. 'main.c',
  3252. 'c',
  3253. context
  3254. );
  3255. expect(result).toBe('utils.h');
  3256. });
  3257. it('should resolve C++ include with .hpp extension', () => {
  3258. const context: ResolutionContext = {
  3259. getNodesInFile: () => [],
  3260. getNodesByName: () => [],
  3261. getNodesByQualifiedName: () => [],
  3262. getNodesByKind: () => [],
  3263. fileExists: (p) => p === 'include/myclass.hpp',
  3264. readFile: () => null,
  3265. getProjectRoot: () => '',
  3266. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  3267. getCppIncludeDirs: () => ['include'],
  3268. };
  3269. const result = resolveImportPath(
  3270. 'myclass.hpp',
  3271. 'src/main.cpp',
  3272. 'cpp',
  3273. context
  3274. );
  3275. expect(result).toBe('include/myclass.hpp');
  3276. });
  3277. it('should resolve include with subdirectory path', () => {
  3278. const context: ResolutionContext = {
  3279. getNodesInFile: () => [],
  3280. getNodesByName: () => [],
  3281. getNodesByQualifiedName: () => [],
  3282. getNodesByKind: () => [],
  3283. fileExists: (p) => p === 'utils/helpers.h',
  3284. readFile: () => null,
  3285. getProjectRoot: () => '',
  3286. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  3287. };
  3288. const result = resolveImportPath(
  3289. 'utils/helpers.h',
  3290. 'main.c',
  3291. 'c',
  3292. context
  3293. );
  3294. expect(result).toBe('utils/helpers.h');
  3295. });
  3296. it('should resolve include via include directories', () => {
  3297. const context: ResolutionContext = {
  3298. getNodesInFile: () => [],
  3299. getNodesByName: () => [],
  3300. getNodesByQualifiedName: () => [],
  3301. getNodesByKind: () => [],
  3302. fileExists: (p) => p === 'include/myheader.h',
  3303. readFile: () => null,
  3304. getProjectRoot: () => '',
  3305. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  3306. getCppIncludeDirs: () => ['include'],
  3307. };
  3308. const result = resolveImportPath(
  3309. 'myheader.h',
  3310. 'src/main.cpp',
  3311. 'cpp',
  3312. context
  3313. );
  3314. expect(result).toBe('include/myheader.h');
  3315. });
  3316. it('should resolve include trying multiple extensions', () => {
  3317. const context: ResolutionContext = {
  3318. getNodesInFile: () => [],
  3319. getNodesByName: () => [],
  3320. getNodesByQualifiedName: () => [],
  3321. getNodesByKind: () => [],
  3322. // myclass.h does not exist, but myclass.hpp does
  3323. fileExists: (p) => p === 'include/myclass.hpp',
  3324. readFile: () => null,
  3325. getProjectRoot: () => '',
  3326. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  3327. getCppIncludeDirs: () => ['include'],
  3328. };
  3329. const result = resolveImportPath(
  3330. 'myclass',
  3331. 'src/main.cpp',
  3332. 'cpp',
  3333. context
  3334. );
  3335. expect(result).toBe('include/myclass.hpp');
  3336. });
  3337. it('should return null for system headers', () => {
  3338. const context: ResolutionContext = {
  3339. getNodesInFile: () => [],
  3340. getNodesByName: () => [],
  3341. getNodesByQualifiedName: () => [],
  3342. getNodesByKind: () => [],
  3343. fileExists: () => true,
  3344. readFile: () => null,
  3345. getProjectRoot: () => '',
  3346. getAllFiles: () => [],
  3347. };
  3348. // C standard library header
  3349. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  3350. // C++ standard library header
  3351. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  3352. // C++ C-wrapper header
  3353. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  3354. });
  3355. it('should return null for single-component third-party paths that cannot be resolved', () => {
  3356. const context: ResolutionContext = {
  3357. getNodesInFile: () => [],
  3358. getNodesByName: () => [],
  3359. getNodesByQualifiedName: () => [],
  3360. getNodesByKind: () => [],
  3361. fileExists: () => false,
  3362. readFile: () => null,
  3363. getProjectRoot: () => '',
  3364. getAllFiles: () => [],
  3365. getCppIncludeDirs: () => [],
  3366. };
  3367. // Third-party bare header without path — not resolvable, returns null
  3368. const result = resolveImportPath(
  3369. 'openssl/ssl.h',
  3370. 'main.cpp',
  3371. 'cpp',
  3372. context
  3373. );
  3374. expect(result).toBeNull();
  3375. });
  3376. it('should not filter project headers with path separators', () => {
  3377. const context: ResolutionContext = {
  3378. getNodesInFile: () => [],
  3379. getNodesByName: () => [],
  3380. getNodesByQualifiedName: () => [],
  3381. getNodesByKind: () => [],
  3382. fileExists: (p) => p === 'mylib/utils.h',
  3383. readFile: () => null,
  3384. getProjectRoot: () => '',
  3385. getAllFiles: () => ['mylib/utils.h'],
  3386. };
  3387. // Path with separator should NOT be filtered as external
  3388. const result = resolveImportPath(
  3389. 'mylib/utils.h',
  3390. 'main.c',
  3391. 'c',
  3392. context
  3393. );
  3394. expect(result).toBe('mylib/utils.h');
  3395. });
  3396. it('should extract C/C++ import mappings from #include directives', () => {
  3397. const code = `#include <iostream>
  3398. #include "myheader.h"
  3399. #include "utils/helpers.hpp"`;
  3400. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  3401. expect(mappings.length).toBe(3);
  3402. expect(mappings[0]).toEqual({
  3403. localName: 'iostream',
  3404. exportedName: '*',
  3405. source: 'iostream',
  3406. isDefault: false,
  3407. isNamespace: true,
  3408. });
  3409. expect(mappings[1]).toEqual({
  3410. localName: 'myheader',
  3411. exportedName: '*',
  3412. source: 'myheader.h',
  3413. isDefault: false,
  3414. isNamespace: true,
  3415. });
  3416. expect(mappings[2]).toEqual({
  3417. localName: 'helpers',
  3418. exportedName: '*',
  3419. source: 'utils/helpers.hpp',
  3420. isDefault: false,
  3421. isNamespace: true,
  3422. });
  3423. });
  3424. it('should discover include directories from compile_commands.json', () => {
  3425. // Create a temp project with compile_commands.json
  3426. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  3427. try {
  3428. const compileDb = [
  3429. {
  3430. directory: tempProject,
  3431. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  3432. file: 'src/main.cpp',
  3433. },
  3434. ];
  3435. fs.writeFileSync(
  3436. path.join(tempProject, 'compile_commands.json'),
  3437. JSON.stringify(compileDb)
  3438. );
  3439. // Create the include dirs so they exist
  3440. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  3441. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  3442. clearCppIncludeDirCache();
  3443. const dirs = loadCppIncludeDirs(tempProject);
  3444. // Should find include and src/lib (relative to project root)
  3445. // /usr/include is absolute and outside project, should be excluded
  3446. expect(dirs).toContain('include');
  3447. expect(dirs).toContain('src/lib');
  3448. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  3449. } finally {
  3450. fs.rmSync(tempProject, { recursive: true });
  3451. }
  3452. });
  3453. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  3454. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  3455. try {
  3456. // Create include/ and src/ directories with headers
  3457. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  3458. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  3459. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  3460. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  3461. // Create a directory without headers — should not be included
  3462. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  3463. clearCppIncludeDirCache();
  3464. const dirs = loadCppIncludeDirs(tempProject);
  3465. expect(dirs).toContain('include');
  3466. expect(dirs).toContain('src');
  3467. expect(dirs).not.toContain('docs');
  3468. } finally {
  3469. fs.rmSync(tempProject, { recursive: true });
  3470. }
  3471. });
  3472. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  3473. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  3474. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  3475. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  3476. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  3477. // than missing real resolutions. The test pins this so a later
  3478. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  3479. // trade-off explicitly.
  3480. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  3481. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  3482. try {
  3483. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  3484. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  3485. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  3486. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  3487. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  3488. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  3489. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  3490. clearCppIncludeDirCache();
  3491. const dirs = loadCppIncludeDirs(tempProject);
  3492. // Both included — Obj-C dirs are intentionally allowed.
  3493. expect(dirs).toContain('cppmod');
  3494. expect(dirs).toContain('iosmod');
  3495. } finally {
  3496. fs.rmSync(tempProject, { recursive: true });
  3497. }
  3498. });
  3499. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  3500. // in the actual indexing pipeline (not just a phantom file→import-node
  3501. // edge). This pins the include-dir resolution path so the headline PR
  3502. // feature can't silently regress to a no-op in the indexing flow.
  3503. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  3504. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  3505. try {
  3506. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  3507. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  3508. fs.writeFileSync(
  3509. path.join(tempProject, 'include', 'utils.h'),
  3510. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  3511. );
  3512. fs.writeFileSync(
  3513. path.join(tempProject, 'src', 'main.cpp'),
  3514. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  3515. );
  3516. clearCppIncludeDirCache();
  3517. cg = await CodeGraph.init(tempProject, { index: true });
  3518. // Sanity: file nodes exist for the header and the cpp.
  3519. const allFiles = cg.getStats();
  3520. expect(allFiles.fileCount).toBe(2);
  3521. // The `#include "utils.h"` edge should target the real
  3522. // `include/utils.h` file node — not a floating `import` node
  3523. // living inside main.cpp.
  3524. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3525. const rows = db.getDb().prepare(`
  3526. select dst.kind as dstKind, dst.file_path as dstPath
  3527. from edges e
  3528. join nodes src on e.source = src.id
  3529. join nodes dst on e.target = dst.id
  3530. where e.kind = 'imports'
  3531. and src.kind = 'file'
  3532. and src.file_path = 'src/main.cpp'
  3533. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3534. const resolvedToHeader = rows.find(
  3535. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  3536. );
  3537. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  3538. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  3539. const stdlibFile = rows.find(
  3540. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  3541. );
  3542. expect(stdlibFile).toBeUndefined();
  3543. } finally {
  3544. fs.rmSync(tempProject, { recursive: true, force: true });
  3545. }
  3546. });
  3547. });
  3548. describe('C++ templated base-class inheritance (#1043)', () => {
  3549. // A class deriving from a TEMPLATE — `class D : public Base<int>` (or a CRTP
  3550. // `class W : public CRTPBase<W>`, or a qualified `class Q : public ns::Tpl<int>`)
  3551. // recorded its base as the full instantiation text (`Base<int>`), which never
  3552. // name-matched the template, indexed as the bare node `Base`. The `<…>` args
  3553. // are now stripped so the `extends` edge resolves end-to-end.
  3554. it('resolves an extends edge to a templated base (plain, CRTP, struct, multi-base)', async () => {
  3555. fs.writeFileSync(
  3556. path.join(tempDir, 'lib.hpp'),
  3557. `#pragma once
  3558. template<typename T> class Base { public: void foo(); };
  3559. template<typename Derived> class CRTPBase {};
  3560. class Plain {};
  3561. class Widget : public Base<int> {}; // plain template base
  3562. class App : public CRTPBase<App> {}; // CRTP (curiously-recurring)
  3563. struct Node : public Base<double> {}; // struct inheriting a template
  3564. class Both : public Base<char>, public Plain {}; // templated + plain in one clause
  3565. `
  3566. );
  3567. cg = await CodeGraph.init(tempDir, { index: true });
  3568. const db = DatabaseConnection.open(path.join(tempDir, '.codegraph', 'codegraph.db'));
  3569. const edges = db
  3570. .getDb()
  3571. .prepare(
  3572. `select src.name as fromName, dst.name as toName
  3573. from edges e
  3574. join nodes src on e.source = src.id
  3575. join nodes dst on e.target = dst.id
  3576. where e.kind = 'extends'`
  3577. )
  3578. .all() as Array<{ fromName: string; toName: string }>;
  3579. const has = (from: string, to: string) =>
  3580. edges.some((r) => r.fromName === from && r.toName === to);
  3581. // Every templated base now resolves to the bare template node.
  3582. expect(has('Widget', 'Base'), 'Widget : Base<int>').toBe(true);
  3583. expect(has('App', 'CRTPBase'), 'App : CRTPBase<App> (CRTP)').toBe(true);
  3584. expect(has('Node', 'Base'), 'struct Node : Base<double>').toBe(true);
  3585. // A mixed clause resolves BOTH the templated and the plain base.
  3586. expect(has('Both', 'Base'), 'Both : Base<char>').toBe(true);
  3587. expect(has('Both', 'Plain'), 'Both : Plain (non-templated, regression guard)').toBe(true);
  3588. });
  3589. });
  3590. describe('PHP Include Resolution', () => {
  3591. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  3592. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  3593. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  3594. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  3595. });
  3596. // include paths: contain a slash or a file extension
  3597. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  3598. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  3599. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  3600. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  3601. // so they must NOT be treated as includes (would mis-connect to a
  3602. // same-named Closure.php / Bar.php file).
  3603. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  3604. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  3605. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  3606. // scoped to PHP imports only
  3607. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  3608. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  3609. });
  3610. it('resolves require_once to a file→file imports edge (#660)', async () => {
  3611. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  3612. try {
  3613. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  3614. fs.writeFileSync(
  3615. path.join(tempProject, 'src', 'lib.php'),
  3616. `<?php\nfunction greet() { return "hi"; }\n`
  3617. );
  3618. fs.writeFileSync(
  3619. path.join(tempProject, 'src', 'page.php'),
  3620. `<?php\nrequire_once("lib.php");\necho greet();\n`
  3621. );
  3622. cg = await CodeGraph.init(tempProject, { index: true });
  3623. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  3624. // to the real src/lib.php file node — a file→file `imports` edge, so
  3625. // callers(lib.php) now includes page.php.
  3626. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3627. const rows = db.getDb().prepare(`
  3628. select dst.kind as dstKind, dst.file_path as dstPath
  3629. from edges e
  3630. join nodes src on e.source = src.id
  3631. join nodes dst on e.target = dst.id
  3632. where e.kind = 'imports'
  3633. and src.kind = 'file'
  3634. and src.file_path = 'src/page.php'
  3635. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3636. const resolved = rows.find(
  3637. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  3638. );
  3639. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  3640. } finally {
  3641. fs.rmSync(tempProject, { recursive: true, force: true });
  3642. }
  3643. });
  3644. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  3645. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  3646. try {
  3647. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  3648. fs.writeFileSync(
  3649. path.join(tempProject, 'inc', 'db.php'),
  3650. `<?php\nfunction query() { return 1; }\n`
  3651. );
  3652. fs.writeFileSync(
  3653. path.join(tempProject, 'index.php'),
  3654. `<?php\nrequire "inc/db.php";\nquery();\n`
  3655. );
  3656. cg = await CodeGraph.init(tempProject, { index: true });
  3657. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3658. const rows = db.getDb().prepare(`
  3659. select dst.kind as dstKind, dst.file_path as dstPath
  3660. from edges e
  3661. join nodes src on e.source = src.id
  3662. join nodes dst on e.target = dst.id
  3663. where e.kind = 'imports'
  3664. and src.kind = 'file'
  3665. and src.file_path = 'index.php'
  3666. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3667. expect(
  3668. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  3669. 'index.php → inc/db.php imports edge missing'
  3670. ).toBeDefined();
  3671. } finally {
  3672. fs.rmSync(tempProject, { recursive: true, force: true });
  3673. }
  3674. });
  3675. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  3676. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  3677. try {
  3678. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  3679. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  3680. // but is unrelated — no edge should be created (a wrong edge is worse
  3681. // than a missing one).
  3682. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  3683. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  3684. fs.writeFileSync(
  3685. path.join(tempProject, 'lib', 'inc', 'db.php'),
  3686. `<?php\nfunction unrelated() {}\n`
  3687. );
  3688. fs.writeFileSync(
  3689. path.join(tempProject, 'app', 'page.php'),
  3690. `<?php\nrequire "inc/db.php";\n`
  3691. );
  3692. cg = await CodeGraph.init(tempProject, { index: true });
  3693. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  3694. const rows = db.getDb().prepare(`
  3695. select dst.kind as dstKind, dst.file_path as dstPath
  3696. from edges e
  3697. join nodes src on e.source = src.id
  3698. join nodes dst on e.target = dst.id
  3699. where e.kind = 'imports'
  3700. and src.kind = 'file'
  3701. and src.file_path = 'app/page.php'
  3702. `).all() as Array<{ dstKind: string; dstPath: string }>;
  3703. expect(
  3704. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  3705. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  3706. ).toBeUndefined();
  3707. } finally {
  3708. fs.rmSync(tempProject, { recursive: true, force: true });
  3709. }
  3710. });
  3711. });
  3712. describe('C++ chained-call receiver resolution (#645)', () => {
  3713. async function indexCpp(files: Record<string, string>): Promise<void> {
  3714. for (const [name, content] of Object.entries(files)) {
  3715. fs.writeFileSync(path.join(tempDir, name), content);
  3716. }
  3717. cg = await CodeGraph.init(tempDir, { index: true });
  3718. }
  3719. function callerNamesOf(qualifiedName: string): string[] {
  3720. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3721. if (!target) return [];
  3722. const names = cg
  3723. .getIncomingEdges(target.id)
  3724. .filter((e) => e.kind === 'calls')
  3725. .map((e) => cg.getNode(e.source)?.name)
  3726. .filter((n): n is string => !!n);
  3727. return [...new Set(names)].sort();
  3728. }
  3729. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  3730. // Two classes share writeLog; Logger sorts first so it wins any name-only
  3731. // tie. All three call forms target Metrics.
  3732. await indexCpp({
  3733. 'logger.hpp': `#pragma once
  3734. #include <string>
  3735. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  3736. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  3737. `,
  3738. 'impl.cpp': `#include "logger.hpp"
  3739. Logger& Logger::instance() { static Logger l; return l; }
  3740. Metrics& Metrics::instance() { static Metrics m; return m; }
  3741. void Logger::writeLog(const std::string&) {}
  3742. void Metrics::writeLog(const std::string&) {}
  3743. `,
  3744. 'app.cpp': `#include "logger.hpp"
  3745. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  3746. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  3747. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  3748. `,
  3749. });
  3750. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  3751. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  3752. });
  3753. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  3754. await indexCpp({
  3755. 'types.hpp': `#pragma once
  3756. #include <memory>
  3757. struct Widget { void draw(); };
  3758. struct Session { void run(); };
  3759. struct View { void render(); };
  3760. class WidgetFactory { public: static Widget create(); };
  3761. class Manager { public: View view(); };
  3762. Session* openSession();
  3763. // Decoy that sorts first and has all three methods — must never win.
  3764. struct Aaa { void draw(); void run(); void render(); };
  3765. `,
  3766. 'impl.cpp': `#include "types.hpp"
  3767. void Widget::draw() {}
  3768. void Session::run() {}
  3769. void View::render() {}
  3770. void Aaa::draw() {}
  3771. void Aaa::run() {}
  3772. void Aaa::render() {}
  3773. Widget WidgetFactory::create() { return Widget(); }
  3774. View Manager::view() { return View(); }
  3775. Session* openSession() { return nullptr; }
  3776. `,
  3777. 'app.cpp': `#include "types.hpp"
  3778. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  3779. void freefunc() { openSession()->run(); } // -> Session::run
  3780. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  3781. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  3782. `,
  3783. });
  3784. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  3785. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  3786. expect(callerNamesOf('View::render')).toEqual(['member']);
  3787. // The first-sorted decoy never captures any of them.
  3788. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  3789. expect(callerNamesOf('Aaa::run')).toEqual([]);
  3790. expect(callerNamesOf('Aaa::render')).toEqual([]);
  3791. });
  3792. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  3793. await indexCpp({
  3794. 'types.hpp': `#pragma once
  3795. struct Widget { void draw(); };
  3796. struct Other { void onlyOther(); };
  3797. class WidgetFactory { public: static Widget create(); };
  3798. `,
  3799. 'impl.cpp': `#include "types.hpp"
  3800. void Widget::draw() {}
  3801. void Other::onlyOther() {}
  3802. Widget WidgetFactory::create() { return Widget(); }
  3803. `,
  3804. 'app.cpp': `#include "types.hpp"
  3805. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  3806. void wrong() { WidgetFactory::create().onlyOther(); }
  3807. `,
  3808. });
  3809. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3810. });
  3811. });
  3812. describe('C++ explicit operator-call resolution (#1247)', () => {
  3813. // `a.operator+(b)` produced no calls edge: the operator_name lands in an
  3814. // ERROR node (never a field_expression callee), so the extractor emitted a
  3815. // ref named just `a`. With the ERROR-node recovery it emits `a.operator+`,
  3816. // and matchMethodCall (dot pattern extended to admit operator method parts)
  3817. // resolves it through receiver-type inference. Infix `a + b` / `a[i]` need
  3818. // real type inference and are out of scope here (#1258).
  3819. async function indexCpp(files: Record<string, string>): Promise<void> {
  3820. for (const [name, content] of Object.entries(files)) {
  3821. fs.writeFileSync(path.join(tempDir, name), content);
  3822. }
  3823. cg = await CodeGraph.init(tempDir, { index: true });
  3824. }
  3825. function callerNamesOf(qualifiedName: string): string[] {
  3826. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3827. if (!target) return [];
  3828. const names = cg
  3829. .getIncomingEdges(target.id)
  3830. .filter((e) => e.kind === 'calls')
  3831. .map((e) => cg.getNode(e.source)?.name)
  3832. .filter((n): n is string => !!n);
  3833. return [...new Set(names)].sort();
  3834. }
  3835. it('resolves explicit operator calls to the receiver type, never a same-named decoy', async () => {
  3836. // Aaa sorts first and declares the same operators — only receiver-type
  3837. // inference (const V& a → V) can pick V, so a name-only tie can't win.
  3838. await indexCpp({
  3839. 'optest.cpp': `struct Aaa {
  3840. Aaa operator+(const Aaa& o) const { return o; }
  3841. Aaa operator[](int i) const { return *this; }
  3842. };
  3843. struct V {
  3844. int x;
  3845. V operator+(const V& o) const { return V{x + o.x}; }
  3846. V operator[](int i) const { return V{x + i}; }
  3847. int get() const { return x; }
  3848. };
  3849. int plainCaller(const V& a) { return a.get(); }
  3850. V explicitCaller(const V& a, const V& b) { return a.operator+(b); }
  3851. V subscriptCaller(const V& a) { return a.operator[](3); }
  3852. V pointerCaller(const V* p, const V& b) { return p->operator+(b); }
  3853. `,
  3854. });
  3855. expect(callerNamesOf('V::operator+')).toEqual(['explicitCaller', 'pointerCaller']);
  3856. expect(callerNamesOf('V::operator[]')).toEqual(['subscriptCaller']);
  3857. expect(callerNamesOf('V::get')).toEqual(['plainCaller']); // control: plain calls unaffected
  3858. expect(callerNamesOf('Aaa::operator+')).toEqual([]);
  3859. expect(callerNamesOf('Aaa::operator[]')).toEqual([]);
  3860. });
  3861. it('resolves an out-of-line operator definition (declaration in header)', async () => {
  3862. await indexCpp({
  3863. 'v.hpp': `#pragma once
  3864. struct V { int x; V operator+(const V& o) const; };
  3865. `,
  3866. 'v.cpp': `#include "v.hpp"
  3867. V V::operator+(const V& o) const { return V{x + o.x}; }
  3868. `,
  3869. 'app.cpp': `#include "v.hpp"
  3870. V add(const V& a, const V& b) { return a.operator+(b); }
  3871. `,
  3872. });
  3873. expect(callerNamesOf('V::operator+')).toEqual(['add']);
  3874. });
  3875. });
  3876. describe('PHP chained static-factory call resolution (#608)', () => {
  3877. function callerNamesOf(qualifiedName: string): string[] {
  3878. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3879. if (!target) return [];
  3880. const names = cg
  3881. .getIncomingEdges(target.id)
  3882. .filter((e) => e.kind === 'calls')
  3883. .map((e) => cg.getNode(e.source)?.name)
  3884. .filter((n): n is string => !!n);
  3885. return [...new Set(names)].sort();
  3886. }
  3887. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  3888. fs.writeFileSync(
  3889. path.join(tempDir, 'ApiClient.php'),
  3890. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  3891. );
  3892. fs.writeFileSync(
  3893. path.join(tempDir, 'DispatchOrder.php'),
  3894. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  3895. );
  3896. cg = await CodeGraph.init(tempDir, { index: true });
  3897. // The chained call's edge attaches to the factory result's method.
  3898. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  3899. });
  3900. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  3901. fs.writeFileSync(
  3902. path.join(tempDir, 'lib.php'),
  3903. `<?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`
  3904. );
  3905. cg = await CodeGraph.init(tempDir, { index: true });
  3906. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3907. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3908. });
  3909. });
  3910. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  3911. function callerNamesOf(qualifiedName: string): string[] {
  3912. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3913. if (!target) return [];
  3914. const names = cg
  3915. .getIncomingEdges(target.id)
  3916. .filter((e) => e.kind === 'calls')
  3917. .map((e) => cg.getNode(e.source)?.name)
  3918. .filter((n): n is string => !!n);
  3919. return [...new Set(names)].sort();
  3920. }
  3921. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  3922. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  3923. fs.writeFileSync(
  3924. path.join(tempDir, 'Main.java'),
  3925. `class Aaa { void bar() {} }
  3926. class Foo {
  3927. static Foo getInstance() { return new Foo(); }
  3928. void bar() {}
  3929. }
  3930. class Caller {
  3931. void run() { Foo.getInstance().bar(); }
  3932. }
  3933. `
  3934. );
  3935. cg = await CodeGraph.init(tempDir, { index: true });
  3936. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  3937. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  3938. });
  3939. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  3940. // The factory call carries an argument; the extractor must normalize the
  3941. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  3942. fs.writeFileSync(
  3943. path.join(tempDir, 'Main.java'),
  3944. `class Config {}
  3945. class Foo {
  3946. static Foo create(Config c) { return new Foo(); }
  3947. void build() {}
  3948. }
  3949. class Caller {
  3950. void run() { Foo.create(new Config()).build(); }
  3951. }
  3952. `
  3953. );
  3954. cg = await CodeGraph.init(tempDir, { index: true });
  3955. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  3956. });
  3957. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  3958. fs.writeFileSync(
  3959. path.join(tempDir, 'Main.java'),
  3960. `class Foo {
  3961. static Foo getInstance() { return new Foo(); }
  3962. }
  3963. class Other { void onlyOther() {} }
  3964. class Caller {
  3965. void run() { Foo.getInstance().onlyOther(); }
  3966. }
  3967. `
  3968. );
  3969. cg = await CodeGraph.init(tempDir, { index: true });
  3970. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3971. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3972. });
  3973. });
  3974. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  3975. function callerNamesOf(qualifiedName: string): string[] {
  3976. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3977. if (!target) return [];
  3978. const names = cg
  3979. .getIncomingEdges(target.id)
  3980. .filter((e) => e.kind === 'calls')
  3981. .map((e) => cg.getNode(e.source)?.name)
  3982. .filter((n): n is string => !!n);
  3983. return [...new Set(names)].sort();
  3984. }
  3985. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  3986. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  3987. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  3988. fs.writeFileSync(
  3989. path.join(tempDir, 'Main.kt'),
  3990. `class Aaa { fun bar() {} }
  3991. class Foo {
  3992. companion object {
  3993. fun getInstance(): Foo = Foo()
  3994. }
  3995. fun bar() {}
  3996. }
  3997. class Caller {
  3998. fun run() { Foo.getInstance().bar() }
  3999. }
  4000. `
  4001. );
  4002. cg = await CodeGraph.init(tempDir, { index: true });
  4003. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  4004. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  4005. });
  4006. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  4007. fs.writeFileSync(
  4008. path.join(tempDir, 'Main.kt'),
  4009. `class Config
  4010. class Foo {
  4011. companion object {
  4012. fun create(c: Config): Foo = Foo()
  4013. }
  4014. fun build() {}
  4015. }
  4016. class Caller {
  4017. fun run() { Foo.create(Config()).build() }
  4018. }
  4019. `
  4020. );
  4021. cg = await CodeGraph.init(tempDir, { index: true });
  4022. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  4023. });
  4024. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  4025. fs.writeFileSync(
  4026. path.join(tempDir, 'Main.kt'),
  4027. `class Foo {
  4028. companion object {
  4029. fun getInstance(): Foo = Foo()
  4030. }
  4031. }
  4032. class Other { fun onlyOther() {} }
  4033. class Caller {
  4034. fun run() { Foo.getInstance().onlyOther() }
  4035. }
  4036. `
  4037. );
  4038. cg = await CodeGraph.init(tempDir, { index: true });
  4039. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  4040. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4041. });
  4042. });
  4043. describe('C# chained static-factory call resolution (#645/#608 mechanism)', () => {
  4044. function callerNamesOf(qualifiedName: string): string[] {
  4045. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4046. if (!target) return [];
  4047. const names = cg
  4048. .getIncomingEdges(target.id)
  4049. .filter((e) => e.kind === 'calls')
  4050. .map((e) => cg.getNode(e.source)?.name)
  4051. .filter((n): n is string => !!n);
  4052. return [...new Set(names)].sort();
  4053. }
  4054. it('resolves Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  4055. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  4056. fs.writeFileSync(
  4057. path.join(tempDir, 'Main.cs'),
  4058. `class Aaa { void Bar() {} }
  4059. class Foo {
  4060. static Foo Create() { return new Foo(); }
  4061. void Bar() {}
  4062. }
  4063. class Caller {
  4064. void Run() { Foo.Create().Bar(); }
  4065. }
  4066. `
  4067. );
  4068. cg = await CodeGraph.init(tempDir, { index: true });
  4069. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  4070. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  4071. });
  4072. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  4073. fs.writeFileSync(
  4074. path.join(tempDir, 'Main.cs'),
  4075. `class Config {}
  4076. class Foo {
  4077. static Foo Make(Config c) { return new Foo(); }
  4078. void Build() {}
  4079. }
  4080. class Caller {
  4081. void Run() { Foo.Make(new Config()).Build(); }
  4082. }
  4083. `
  4084. );
  4085. cg = await CodeGraph.init(tempDir, { index: true });
  4086. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  4087. });
  4088. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  4089. fs.writeFileSync(
  4090. path.join(tempDir, 'Main.cs'),
  4091. `class Foo {
  4092. static Foo Create() { return new Foo(); }
  4093. }
  4094. class Other { void OnlyOther() {} }
  4095. class Caller {
  4096. void Run() { Foo.Create().OnlyOther(); }
  4097. }
  4098. `
  4099. );
  4100. cg = await CodeGraph.init(tempDir, { index: true });
  4101. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  4102. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  4103. });
  4104. });
  4105. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  4106. function callerNamesOf(qualifiedName: string): string[] {
  4107. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4108. if (!target) return [];
  4109. const names = cg
  4110. .getIncomingEdges(target.id)
  4111. .filter((e) => e.kind === 'calls')
  4112. .map((e) => cg.getNode(e.source)?.name)
  4113. .filter((n): n is string => !!n);
  4114. return [...new Set(names)].sort();
  4115. }
  4116. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  4117. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  4118. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  4119. fs.writeFileSync(
  4120. path.join(tempDir, 'Main.swift'),
  4121. `class Aaa { func draw() {} }
  4122. class Foo {
  4123. static func make() -> Foo { return Foo() }
  4124. func draw() {}
  4125. }
  4126. func runCaller() { Foo.make().draw() }
  4127. `
  4128. );
  4129. cg = await CodeGraph.init(tempDir, { index: true });
  4130. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  4131. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  4132. });
  4133. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  4134. fs.writeFileSync(
  4135. path.join(tempDir, 'Main.swift'),
  4136. `class Config {}
  4137. class Foo {
  4138. static func build(_ c: Config) -> Foo { return Foo() }
  4139. func draw() {}
  4140. func render() {}
  4141. }
  4142. func runCaller() {
  4143. Foo().draw()
  4144. Foo.build(Config()).render()
  4145. }
  4146. `
  4147. );
  4148. cg = await CodeGraph.init(tempDir, { index: true });
  4149. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  4150. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  4151. });
  4152. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  4153. fs.writeFileSync(
  4154. path.join(tempDir, 'Main.swift'),
  4155. `class Foo {
  4156. static func make() -> Foo { return Foo() }
  4157. }
  4158. class Other { func onlyOther() {} }
  4159. func runCaller() { Foo.make().onlyOther() }
  4160. `
  4161. );
  4162. cg = await CodeGraph.init(tempDir, { index: true });
  4163. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  4164. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4165. });
  4166. });
  4167. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  4168. function callerNamesOf(qualifiedName: string): string[] {
  4169. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4170. if (!target) return [];
  4171. const names = cg
  4172. .getIncomingEdges(target.id)
  4173. .filter((e) => e.kind === 'calls')
  4174. .map((e) => cg.getNode(e.source)?.name)
  4175. .filter((n): n is string => !!n);
  4176. return [...new Set(names)].sort();
  4177. }
  4178. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  4179. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  4180. // its own. Decoy.draw must never win. Needs the conformance second pass.
  4181. fs.writeFileSync(
  4182. path.join(tempDir, 'Main.java'),
  4183. `class Base { void draw() {} }
  4184. class Widget extends Base {}
  4185. class Decoy { void draw() {} }
  4186. class Factory { static Widget create() { return new Widget(); } }
  4187. class Caller {
  4188. void run() { Factory.create().draw(); }
  4189. }
  4190. `
  4191. );
  4192. cg = await CodeGraph.init(tempDir, { index: true });
  4193. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  4194. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  4195. });
  4196. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  4197. fs.writeFileSync(
  4198. path.join(tempDir, 'Main.java'),
  4199. `interface Drawable { default void draw() {} }
  4200. class Widget implements Drawable {}
  4201. class Decoy { void draw() {} }
  4202. class Factory { static Widget create() { return new Widget(); } }
  4203. class Caller {
  4204. void run() { Factory.create().draw(); }
  4205. }
  4206. `
  4207. );
  4208. cg = await CodeGraph.init(tempDir, { index: true });
  4209. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  4210. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  4211. });
  4212. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  4213. fs.writeFileSync(
  4214. path.join(tempDir, 'Main.java'),
  4215. `class Base {}
  4216. class Widget extends Base {}
  4217. class Other { void onlyOther() {} }
  4218. class Factory { static Widget create() { return new Widget(); } }
  4219. class Caller {
  4220. void run() { Factory.create().onlyOther(); }
  4221. }
  4222. `
  4223. );
  4224. cg = await CodeGraph.init(tempDir, { index: true });
  4225. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  4226. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4227. });
  4228. });
  4229. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  4230. function callerNamesOf(qualifiedName: string): string[] {
  4231. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4232. if (!target) return [];
  4233. const names = cg
  4234. .getIncomingEdges(target.id)
  4235. .filter((e) => e.kind === 'calls')
  4236. .map((e) => cg.getNode(e.source)?.name)
  4237. .filter((n): n is string => !!n);
  4238. return [...new Set(names)].sort();
  4239. }
  4240. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  4241. fs.writeFileSync(
  4242. path.join(tempDir, 'main.rs'),
  4243. `struct Aaa { _x: i32 }
  4244. impl Aaa { fn bar(&self) {} }
  4245. struct Foo { _x: i32 }
  4246. impl Foo {
  4247. fn new() -> Foo { Foo { _x: 0 } }
  4248. fn make() -> Self { Foo { _x: 0 } }
  4249. fn bar(&self) {}
  4250. }
  4251. fn caller() {
  4252. Foo::new().bar();
  4253. Foo::make().bar();
  4254. }
  4255. `
  4256. );
  4257. cg = await CodeGraph.init(tempDir, { index: true });
  4258. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  4259. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  4260. });
  4261. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  4262. fs.writeFileSync(
  4263. path.join(tempDir, 'main.rs'),
  4264. `struct Config;
  4265. struct Foo { _x: i32 }
  4266. impl Foo {
  4267. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  4268. fn build(&self) {}
  4269. }
  4270. fn caller() { Foo::with(Config).build(); }
  4271. `
  4272. );
  4273. cg = await CodeGraph.init(tempDir, { index: true });
  4274. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  4275. });
  4276. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  4277. fs.writeFileSync(
  4278. path.join(tempDir, 'main.rs'),
  4279. `struct Foo { _x: i32 }
  4280. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  4281. struct Decoy { _x: i32 }
  4282. impl Decoy { fn draw(&self) {} }
  4283. trait Drawable { fn draw(&self) {} }
  4284. impl Drawable for Foo {}
  4285. fn caller() { Foo::new().draw(); }
  4286. `
  4287. );
  4288. cg = await CodeGraph.init(tempDir, { index: true });
  4289. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  4290. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  4291. });
  4292. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  4293. fs.writeFileSync(
  4294. path.join(tempDir, 'main.rs'),
  4295. `struct Foo { _x: i32 }
  4296. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  4297. struct Other { _x: i32 }
  4298. impl Other { fn only_other(&self) {} }
  4299. fn caller() { Foo::new().only_other(); }
  4300. `
  4301. );
  4302. cg = await CodeGraph.init(tempDir, { index: true });
  4303. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  4304. expect(callerNamesOf('Other::only_other')).toEqual([]);
  4305. });
  4306. });
  4307. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  4308. function callerNamesOf(qualifiedName: string): string[] {
  4309. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4310. if (!target) return [];
  4311. const names = cg
  4312. .getIncomingEdges(target.id)
  4313. .filter((e) => e.kind === 'calls')
  4314. .map((e) => cg.getNode(e.source)?.name)
  4315. .filter((n): n is string => !!n);
  4316. return [...new Set(names)].sort();
  4317. }
  4318. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  4319. fs.writeFileSync(
  4320. path.join(tempDir, 'main.go'),
  4321. `package main
  4322. type Aaa struct{}
  4323. func (a *Aaa) Bar() {}
  4324. type Foo struct{}
  4325. func New() *Foo { return &Foo{} }
  4326. func (f *Foo) Bar() {}
  4327. func caller() { New().Bar() }
  4328. `
  4329. );
  4330. cg = await CodeGraph.init(tempDir, { index: true });
  4331. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  4332. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  4333. });
  4334. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  4335. fs.writeFileSync(
  4336. path.join(tempDir, 'main.go'),
  4337. `package main
  4338. type Config struct{}
  4339. type Foo struct{}
  4340. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  4341. func (f *Foo) Build() {}
  4342. func caller() { With(Config{}).Build() }
  4343. `
  4344. );
  4345. cg = await CodeGraph.init(tempDir, { index: true });
  4346. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  4347. });
  4348. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  4349. fs.writeFileSync(
  4350. path.join(tempDir, 'main.go'),
  4351. `package main
  4352. type Base struct{}
  4353. func (b *Base) Embedded() {}
  4354. type Decoy struct{}
  4355. func (d *Decoy) Embedded() {}
  4356. type Widget struct{ Base }
  4357. func NewWidget() *Widget { return &Widget{} }
  4358. func caller() { NewWidget().Embedded() }
  4359. `
  4360. );
  4361. cg = await CodeGraph.init(tempDir, { index: true });
  4362. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  4363. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  4364. });
  4365. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  4366. fs.writeFileSync(
  4367. path.join(tempDir, 'main.go'),
  4368. `package main
  4369. type Foo struct{}
  4370. func New() *Foo { return &Foo{} }
  4371. type Other struct{}
  4372. func (o *Other) OnlyOther() {}
  4373. func caller() { New().OnlyOther() }
  4374. `
  4375. );
  4376. cg = await CodeGraph.init(tempDir, { index: true });
  4377. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  4378. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  4379. });
  4380. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  4381. // `engine` is a package-level VARIABLE holding a func value, not a factory
  4382. // FUNCTION — so its return type can't be recovered and the chain falls back
  4383. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  4384. // Regression for the runaway this fallback originally caused: it resolved
  4385. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  4386. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  4387. // no-oped, the offset-0 batch never drained, and edges inserted forever
  4388. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  4389. // the original ref, and a non-progress guard backstops the loop.
  4390. fs.writeFileSync(
  4391. path.join(tempDir, 'main.go'),
  4392. `package main
  4393. type Server struct{}
  4394. func (s *Server) ServeHTTP() {}
  4395. var engine = func() *Server { return &Server{} }
  4396. func caller() { engine().ServeHTTP() }
  4397. `
  4398. );
  4399. cg = await CodeGraph.init(tempDir, { index: true });
  4400. // Recall: the variable-inner chain still finds the method by bare name.
  4401. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  4402. // No runaway: a single call site yields a single edge, not millions.
  4403. const target = cg
  4404. .getNodesByKind('method')
  4405. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  4406. const rawCalls = cg
  4407. .getIncomingEdges(target.id)
  4408. .filter((e) => e.kind === 'calls');
  4409. expect(rawCalls.length).toBeLessThan(5);
  4410. });
  4411. });
  4412. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  4413. function callerNamesOf(qualifiedName: string): string[] {
  4414. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4415. if (!target) return [];
  4416. const names = cg
  4417. .getIncomingEdges(target.id)
  4418. .filter((e) => e.kind === 'calls')
  4419. .map((e) => cg.getNode(e.source)?.name)
  4420. .filter((n): n is string => !!n);
  4421. return [...new Set(names)].sort();
  4422. }
  4423. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  4424. fs.writeFileSync(
  4425. path.join(tempDir, 'Main.scala'),
  4426. `object Foo {
  4427. def create(): Bar = new Bar()
  4428. }
  4429. class Bar {
  4430. def doIt(): Unit = {}
  4431. }
  4432. class Decoy {
  4433. def doIt(): Unit = {}
  4434. }
  4435. object Main {
  4436. def run(): Unit = { Foo.create().doIt() }
  4437. }
  4438. `
  4439. );
  4440. cg = await CodeGraph.init(tempDir, { index: true });
  4441. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  4442. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  4443. });
  4444. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  4445. fs.writeFileSync(
  4446. path.join(tempDir, 'Main.scala'),
  4447. `class Point(x: Int) {
  4448. def dist(): Int = x
  4449. }
  4450. class Other {
  4451. def dist(): Int = 0
  4452. }
  4453. object Main {
  4454. def run(): Unit = { Point(3).dist() }
  4455. }
  4456. `
  4457. );
  4458. cg = await CodeGraph.init(tempDir, { index: true });
  4459. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  4460. expect(callerNamesOf('Other::dist')).toEqual([]);
  4461. });
  4462. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  4463. fs.writeFileSync(
  4464. path.join(tempDir, 'Main.scala'),
  4465. `trait Base {
  4466. def shared(): Unit = {}
  4467. }
  4468. class Widget extends Base
  4469. class Decoy {
  4470. def shared(): Unit = {}
  4471. }
  4472. object Factory {
  4473. def make(): Widget = new Widget()
  4474. }
  4475. object Main {
  4476. def run(): Unit = { Factory.make().shared() }
  4477. }
  4478. `
  4479. );
  4480. cg = await CodeGraph.init(tempDir, { index: true });
  4481. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  4482. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  4483. });
  4484. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  4485. fs.writeFileSync(
  4486. path.join(tempDir, 'Main.scala'),
  4487. `object Foo {
  4488. def create(): Bar = new Bar()
  4489. }
  4490. class Bar {
  4491. }
  4492. class Other {
  4493. def onlyOther(): Unit = {}
  4494. }
  4495. object Main {
  4496. def run(): Unit = { Foo.create().onlyOther() }
  4497. }
  4498. `
  4499. );
  4500. cg = await CodeGraph.init(tempDir, { index: true });
  4501. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  4502. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4503. });
  4504. });
  4505. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  4506. function callerNamesOf(qualifiedName: string): string[] {
  4507. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4508. if (!target) return [];
  4509. const names = cg
  4510. .getIncomingEdges(target.id)
  4511. .filter((e) => e.kind === 'calls')
  4512. .map((e) => cg.getNode(e.source)?.name)
  4513. .filter((n): n is string => !!n);
  4514. return [...new Set(names)].sort();
  4515. }
  4516. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  4517. fs.writeFileSync(
  4518. path.join(tempDir, 'main.dart'),
  4519. `class Foo {
  4520. static Bar makeBar() => Bar();
  4521. }
  4522. class Bar {
  4523. void doIt() {}
  4524. }
  4525. class Decoy {
  4526. void doIt() {}
  4527. }
  4528. void run() {
  4529. Foo.makeBar().doIt();
  4530. }
  4531. `
  4532. );
  4533. cg = await CodeGraph.init(tempDir, { index: true });
  4534. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  4535. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  4536. });
  4537. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  4538. fs.writeFileSync(
  4539. path.join(tempDir, 'main.dart'),
  4540. `class Foo {
  4541. Foo._();
  4542. factory Foo.create() => Foo._();
  4543. void ship() {}
  4544. }
  4545. class Decoy {
  4546. void ship() {}
  4547. }
  4548. void run() {
  4549. Foo.create().ship();
  4550. }
  4551. `
  4552. );
  4553. cg = await CodeGraph.init(tempDir, { index: true });
  4554. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  4555. // so `ship` resolves on Foo, not the same-named Decoy.
  4556. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  4557. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  4558. });
  4559. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  4560. fs.writeFileSync(
  4561. path.join(tempDir, 'main.dart'),
  4562. `class Bar {
  4563. void doIt() {}
  4564. }
  4565. class Decoy {
  4566. void doIt() {}
  4567. }
  4568. void run() {
  4569. Bar().doIt();
  4570. }
  4571. `
  4572. );
  4573. cg = await CodeGraph.init(tempDir, { index: true });
  4574. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  4575. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  4576. });
  4577. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  4578. fs.writeFileSync(
  4579. path.join(tempDir, 'main.dart'),
  4580. `class Base {
  4581. void render() {}
  4582. }
  4583. class Widget extends Base {
  4584. static Widget make() => Widget();
  4585. }
  4586. class Decoy {
  4587. void render() {}
  4588. }
  4589. void run() {
  4590. Widget.make().render();
  4591. }
  4592. `
  4593. );
  4594. cg = await CodeGraph.init(tempDir, { index: true });
  4595. expect(callerNamesOf('Base::render')).toEqual(['run']);
  4596. expect(callerNamesOf('Decoy::render')).toEqual([]);
  4597. });
  4598. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  4599. fs.writeFileSync(
  4600. path.join(tempDir, 'main.dart'),
  4601. `class Foo {
  4602. static Bar makeBar() => Bar();
  4603. }
  4604. class Bar {
  4605. }
  4606. class Other {
  4607. void onlyOther() {}
  4608. }
  4609. void run() {
  4610. Foo.makeBar().onlyOther();
  4611. }
  4612. `
  4613. );
  4614. cg = await CodeGraph.init(tempDir, { index: true });
  4615. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  4616. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4617. });
  4618. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  4619. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  4620. // swallows the record return type, so `reduce()` looks like a single-
  4621. // identifier constructor_signature. It must NOT be skipped as an unnamed
  4622. // ctor (its name doesn't match the class); its body call must attribute to
  4623. // `reduce`, not the class.
  4624. fs.writeFileSync(
  4625. path.join(tempDir, 'main.dart'),
  4626. `class Base {}
  4627. class Action extends Base {
  4628. Action({required int x});
  4629. @override
  4630. (int, String) reduce() {
  4631. return (compute(), "y");
  4632. }
  4633. int compute() => 1;
  4634. }
  4635. `
  4636. );
  4637. cg = await CodeGraph.init(tempDir, { index: true });
  4638. // reduce must be a node and its body call must resolve to Action::compute.
  4639. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  4640. });
  4641. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  4642. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  4643. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  4644. // never hijacked into a call to a phantom constructor method.
  4645. fs.writeFileSync(
  4646. path.join(tempDir, 'main.dart'),
  4647. `class Widget {
  4648. final int x;
  4649. Widget(this.x);
  4650. }
  4651. void run() {
  4652. Widget(3);
  4653. }
  4654. `
  4655. );
  4656. cg = await CodeGraph.init(tempDir, { index: true });
  4657. // No Foo::Foo phantom method node.
  4658. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  4659. // The construction resolves to the class as an `instantiates` edge.
  4660. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  4661. const incoming = cg.getIncomingEdges(widget.id);
  4662. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  4663. });
  4664. });
  4665. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  4666. function callerNamesOf(qualifiedName: string): string[] {
  4667. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4668. if (!target) return [];
  4669. const names = cg
  4670. .getIncomingEdges(target.id)
  4671. .filter((e) => e.kind === 'calls')
  4672. .map((e) => cg.getNode(e.source)?.name)
  4673. .filter((n): n is string => !!n);
  4674. return [...new Set(names)].sort();
  4675. }
  4676. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  4677. fs.writeFileSync(
  4678. path.join(tempDir, 'main.m'),
  4679. `@interface Bar : NSObject
  4680. - (void)doIt;
  4681. @end
  4682. @implementation Bar
  4683. - (void)doIt {}
  4684. @end
  4685. @interface Decoy : NSObject
  4686. - (void)doIt;
  4687. @end
  4688. @implementation Decoy
  4689. - (void)doIt {}
  4690. @end
  4691. @interface Foo : NSObject
  4692. + (Bar *)create;
  4693. @end
  4694. @implementation Foo
  4695. + (Bar *)create { return nil; }
  4696. - (void)run { [[Foo create] doIt]; }
  4697. @end
  4698. `
  4699. );
  4700. cg = await CodeGraph.init(tempDir, { index: true });
  4701. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  4702. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  4703. });
  4704. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  4705. fs.writeFileSync(
  4706. path.join(tempDir, 'main.m'),
  4707. `@interface Base : NSObject
  4708. - (void)render;
  4709. @end
  4710. @implementation Base
  4711. - (void)render {}
  4712. @end
  4713. @interface Widget : Base
  4714. @end
  4715. @implementation Widget
  4716. @end
  4717. @interface Decoy : NSObject
  4718. - (void)render;
  4719. @end
  4720. @implementation Decoy
  4721. - (void)render {}
  4722. @end
  4723. @interface Factory : NSObject
  4724. + (Widget *)make;
  4725. @end
  4726. @implementation Factory
  4727. + (Widget *)make { return nil; }
  4728. - (void)run { [[Factory make] render]; }
  4729. @end
  4730. `
  4731. );
  4732. cg = await CodeGraph.init(tempDir, { index: true });
  4733. expect(callerNamesOf('Base::render')).toEqual(['run']);
  4734. expect(callerNamesOf('Decoy::render')).toEqual([]);
  4735. });
  4736. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  4737. fs.writeFileSync(
  4738. path.join(tempDir, 'main.m'),
  4739. `@interface Bar : NSObject
  4740. @end
  4741. @implementation Bar
  4742. @end
  4743. @interface Other : NSObject
  4744. - (void)onlyOther;
  4745. @end
  4746. @implementation Other
  4747. - (void)onlyOther {}
  4748. @end
  4749. @interface Foo : NSObject
  4750. + (Bar *)create;
  4751. @end
  4752. @implementation Foo
  4753. + (Bar *)create { return nil; }
  4754. - (void)run { [[Foo create] onlyOther]; }
  4755. @end
  4756. `
  4757. );
  4758. cg = await CodeGraph.init(tempDir, { index: true });
  4759. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  4760. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  4761. });
  4762. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  4763. // The factory returns `nonnull instancetype` — the nullability qualifier must
  4764. // be skipped (not captured AS the type), and an instancetype class-message
  4765. // factory returns the receiver class, so clearAll resolves on Cache, never a
  4766. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  4767. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  4768. fs.writeFileSync(
  4769. path.join(tempDir, 'main.m'),
  4770. `@interface Cache : NSObject
  4771. + (nonnull instancetype)shared;
  4772. - (void)clearAll;
  4773. @end
  4774. @implementation Cache
  4775. + (nonnull instancetype)shared { return nil; }
  4776. - (void)clearAll {}
  4777. @end
  4778. @interface Decoy : NSObject
  4779. - (void)clearAll;
  4780. @end
  4781. @implementation Decoy
  4782. - (void)clearAll {}
  4783. @end
  4784. @interface Caller : NSObject
  4785. - (void)run;
  4786. @end
  4787. @implementation Caller
  4788. - (void)run { [[Cache shared] clearAll]; }
  4789. @end
  4790. `
  4791. );
  4792. cg = await CodeGraph.init(tempDir, { index: true });
  4793. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  4794. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  4795. });
  4796. });
  4797. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  4798. function callerNamesOf(qualifiedName: string): string[] {
  4799. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  4800. if (!target) return [];
  4801. const names = cg
  4802. .getIncomingEdges(target.id)
  4803. .filter((e) => e.kind === 'calls')
  4804. .map((e) => cg.getNode(e.source)?.name)
  4805. .filter((n): n is string => !!n);
  4806. return [...new Set(names)].sort();
  4807. }
  4808. function isCalled(qn: string): boolean {
  4809. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  4810. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  4811. }
  4812. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  4813. fs.writeFileSync(
  4814. path.join(tempDir, 'main.pas'),
  4815. `unit Main;
  4816. interface
  4817. type
  4818. TBar = class
  4819. procedure DoIt;
  4820. end;
  4821. TDecoy = class
  4822. procedure DoIt;
  4823. end;
  4824. TFoo = class
  4825. class function GetInstance: TBar;
  4826. end;
  4827. implementation
  4828. procedure TBar.DoIt; begin end;
  4829. procedure TDecoy.DoIt; begin end;
  4830. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4831. procedure Run;
  4832. begin
  4833. TFoo.GetInstance().DoIt();
  4834. end;
  4835. end.
  4836. `
  4837. );
  4838. cg = await CodeGraph.init(tempDir, { index: true });
  4839. expect(isCalled('TBar::DoIt')).toBe(true);
  4840. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4841. });
  4842. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  4843. fs.writeFileSync(
  4844. path.join(tempDir, 'main.pas'),
  4845. `unit Main;
  4846. interface
  4847. type
  4848. TFoo = class
  4849. constructor Create;
  4850. procedure Configure;
  4851. end;
  4852. TDecoy = class
  4853. procedure Configure;
  4854. end;
  4855. implementation
  4856. constructor TFoo.Create; begin end;
  4857. procedure TFoo.Configure; begin end;
  4858. procedure TDecoy.Configure; begin end;
  4859. procedure Run;
  4860. begin
  4861. TFoo.Create().Configure();
  4862. end;
  4863. end.
  4864. `
  4865. );
  4866. cg = await CodeGraph.init(tempDir, { index: true });
  4867. // A constructor returns its own class (no `: TBar` annotation), so Configure
  4868. // resolves on TFoo, not the same-named decoy.
  4869. expect(isCalled('TFoo::Configure')).toBe(true);
  4870. expect(isCalled('TDecoy::Configure')).toBe(false);
  4871. });
  4872. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  4873. fs.writeFileSync(
  4874. path.join(tempDir, 'main.pas'),
  4875. `unit Main;
  4876. interface
  4877. type
  4878. TFoo = class
  4879. procedure DoIt;
  4880. end;
  4881. TDecoy = class
  4882. procedure DoIt;
  4883. end;
  4884. implementation
  4885. procedure TFoo.DoIt; begin end;
  4886. procedure TDecoy.DoIt; begin end;
  4887. procedure Run(obj: TObject);
  4888. begin
  4889. TFoo(obj).DoIt();
  4890. end;
  4891. end.
  4892. `
  4893. );
  4894. cg = await CodeGraph.init(tempDir, { index: true });
  4895. expect(isCalled('TFoo::DoIt')).toBe(true);
  4896. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4897. });
  4898. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  4899. fs.writeFileSync(
  4900. path.join(tempDir, 'main.pas'),
  4901. `unit Main;
  4902. interface
  4903. type
  4904. TBar = class
  4905. end;
  4906. TOther = class
  4907. procedure OnlyOther;
  4908. end;
  4909. TFoo = class
  4910. class function GetInstance: TBar;
  4911. end;
  4912. implementation
  4913. procedure TOther.OnlyOther; begin end;
  4914. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4915. procedure Run;
  4916. begin
  4917. TFoo.GetInstance().OnlyOther();
  4918. end;
  4919. end.
  4920. `
  4921. );
  4922. cg = await CodeGraph.init(tempDir, { index: true });
  4923. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  4924. expect(isCalled('TOther::OnlyOther')).toBe(false);
  4925. });
  4926. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  4927. fs.writeFileSync(
  4928. path.join(tempDir, 'main.pas'),
  4929. `unit Main;
  4930. interface
  4931. type
  4932. TFoo = class
  4933. procedure DoThing;
  4934. procedure Reset;
  4935. end;
  4936. implementation
  4937. procedure TFoo.DoThing; begin end;
  4938. procedure TFoo.Reset; begin end;
  4939. procedure Run(f: TFoo);
  4940. begin
  4941. f.DoThing;
  4942. f.Reset;
  4943. end;
  4944. end.
  4945. `
  4946. );
  4947. cg = await CodeGraph.init(tempDir, { index: true });
  4948. expect(isCalled('TFoo::DoThing')).toBe(true);
  4949. expect(isCalled('TFoo::Reset')).toBe(true);
  4950. });
  4951. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  4952. fs.writeFileSync(
  4953. path.join(tempDir, 'main.pas'),
  4954. `unit Main;
  4955. interface
  4956. type
  4957. TBar = class
  4958. procedure DoIt;
  4959. end;
  4960. TDecoy = class
  4961. procedure DoIt;
  4962. end;
  4963. TFoo = class
  4964. class function GetInstance: TBar;
  4965. end;
  4966. implementation
  4967. procedure TBar.DoIt; begin end;
  4968. procedure TDecoy.DoIt; begin end;
  4969. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  4970. procedure Run;
  4971. begin
  4972. TFoo.GetInstance.DoIt;
  4973. end;
  4974. end.
  4975. `
  4976. );
  4977. cg = await CodeGraph.init(tempDir, { index: true });
  4978. expect(isCalled('TBar::DoIt')).toBe(true);
  4979. expect(isCalled('TDecoy::DoIt')).toBe(false);
  4980. });
  4981. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  4982. fs.writeFileSync(
  4983. path.join(tempDir, 'main.pas'),
  4984. `unit Main;
  4985. interface
  4986. type
  4987. TFoo = class
  4988. function GetValue: Integer;
  4989. procedure SetValue(v: Integer);
  4990. property Value: Integer read GetValue write SetValue;
  4991. end;
  4992. implementation
  4993. function TFoo.GetValue: Integer; begin Result := 0; end;
  4994. procedure TFoo.SetValue(v: Integer); begin end;
  4995. procedure Run(f: TFoo);
  4996. var x: Integer;
  4997. begin
  4998. f.Value := 5;
  4999. x := f.Value;
  5000. end;
  5001. end.
  5002. `
  5003. );
  5004. cg = await CodeGraph.init(tempDir, { index: true });
  5005. // A property read/write is a bare dot in assignment position, not a statement,
  5006. // so it must not be mis-extracted as a call to the property's getter/setter.
  5007. expect(isCalled('TFoo::GetValue')).toBe(false);
  5008. expect(isCalled('TFoo::SetValue')).toBe(false);
  5009. });
  5010. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  5011. fs.writeFileSync(
  5012. path.join(tempDir, 'main.pas'),
  5013. `unit Main;
  5014. interface
  5015. type
  5016. TTgt = class
  5017. procedure Hit;
  5018. end;
  5019. TFoo = class
  5020. procedure DoStuff;
  5021. end;
  5022. implementation
  5023. procedure TTgt.Hit; begin end;
  5024. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  5025. procedure Helper; var t: TTgt; begin t.Hit; end;
  5026. `
  5027. );
  5028. cg = await CodeGraph.init(tempDir, { index: true });
  5029. // `Helper` is implementation-only (no interface decl, not a method), but its
  5030. // body's call must attribute to `Helper`, not the file/module — alongside the
  5031. // method `DoStuff`.
  5032. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  5033. });
  5034. });
  5035. describe('Nix path import resolution', () => {
  5036. function fileNode(filePath: string) {
  5037. return cg.getNodesByKind('file').find((n) => n.filePath === filePath);
  5038. }
  5039. function importedFilePaths(fromFile: string): string[] {
  5040. const source = fileNode(fromFile);
  5041. expect(source, `${fromFile} file node`).toBeDefined();
  5042. return cg
  5043. .getOutgoingEdges(source!.id)
  5044. .filter((edge) => edge.kind === 'imports')
  5045. .map((edge) => cg.getNodesByKind('file').find((n) => n.id === edge.target)?.filePath)
  5046. .filter((filePath): filePath is string => Boolean(filePath))
  5047. .sort();
  5048. }
  5049. it('resolves relative Nix imports to indexed file nodes', async () => {
  5050. fs.mkdirSync(path.join(tempDir, 'core'), { recursive: true });
  5051. fs.mkdirSync(path.join(tempDir, 'data'), { recursive: true });
  5052. fs.writeFileSync(path.join(tempDir, 'core', 'ports.nix'), '{ http = 80; https = 443; }');
  5053. fs.writeFileSync(
  5054. path.join(tempDir, 'data', 'postgresql.nix'),
  5055. `let
  5056. ports = import ../core/ports.nix;
  5057. in
  5058. {
  5059. port = ports.https;
  5060. }
  5061. `
  5062. );
  5063. cg = await CodeGraph.init(tempDir, { index: true });
  5064. cg.resolveReferences();
  5065. expect(importedFilePaths('data/postgresql.nix')).toEqual(['core/ports.nix']);
  5066. });
  5067. it('resolves Nix directory imports through default.nix and deduplicates called imports', async () => {
  5068. fs.mkdirSync(path.join(tempDir, 'dir'), { recursive: true });
  5069. fs.writeFileSync(path.join(tempDir, 'dir', 'default.nix'), '{ value = 1; }');
  5070. fs.writeFileSync(path.join(tempDir, 'x.nix'), '{ value = 2; }');
  5071. fs.writeFileSync(
  5072. path.join(tempDir, 'main.nix'),
  5073. `let
  5074. dir = import ./dir;
  5075. x = import ./x.nix {};
  5076. in
  5077. {
  5078. inherit dir x;
  5079. }
  5080. `
  5081. );
  5082. cg = await CodeGraph.init(tempDir, { index: true });
  5083. cg.resolveReferences();
  5084. expect(importedFilePaths('main.nix')).toEqual(['dir/default.nix', 'x.nix']);
  5085. });
  5086. it('resolves NixOS module imports lists and callPackage paths to file nodes', async () => {
  5087. fs.mkdirSync(path.join(tempDir, 'modules'), { recursive: true });
  5088. fs.mkdirSync(path.join(tempDir, 'common'), { recursive: true });
  5089. fs.mkdirSync(path.join(tempDir, 'pkgs', 'hello'), { recursive: true });
  5090. fs.writeFileSync(path.join(tempDir, 'modules', 'users.nix'), '{ users.users.demo.isNormalUser = true; }');
  5091. fs.writeFileSync(path.join(tempDir, 'common', 'default.nix'), '{ time.timeZone = "UTC"; }');
  5092. fs.writeFileSync(
  5093. path.join(tempDir, 'pkgs', 'hello', 'default.nix'),
  5094. '{ stdenv }: stdenv.mkDerivation { pname = "hello"; }'
  5095. );
  5096. fs.writeFileSync(
  5097. path.join(tempDir, 'configuration.nix'),
  5098. `{ config, pkgs, ... }:
  5099. {
  5100. imports = [ ./modules/users.nix ./common ];
  5101. environment.systemPackages = [ (pkgs.callPackage ./pkgs/hello { }) ];
  5102. }
  5103. `
  5104. );
  5105. cg = await CodeGraph.init(tempDir, { index: true });
  5106. cg.resolveReferences();
  5107. expect(importedFilePaths('configuration.nix')).toEqual([
  5108. 'common/default.nix',
  5109. 'modules/users.nix',
  5110. 'pkgs/hello/default.nix',
  5111. ]);
  5112. });
  5113. it('never resolves another language\'s calls into nix bindings', async () => {
  5114. // Nix bindings are not linkable symbols from any other language —
  5115. // interop is eval/CLI. Without the target-side gate, a Python script's
  5116. // bare `resolve(...)` exact-matches a module's `resolve = ...` binding.
  5117. fs.writeFileSync(
  5118. path.join(tempDir, 'helpers.nix'),
  5119. `let
  5120. resolve = x: x;
  5121. in
  5122. {
  5123. inherit resolve;
  5124. }
  5125. `
  5126. );
  5127. fs.writeFileSync(path.join(tempDir, 'tool.py'), 'def main():\n return resolve("target")\n');
  5128. cg = await CodeGraph.init(tempDir, { index: true });
  5129. cg.resolveReferences();
  5130. const nixNodeIds = new Set(
  5131. cg.getNodesByKind('variable').filter((n) => n.language === 'nix').map((n) => n.id)
  5132. );
  5133. const pyFns = cg.getNodesByKind('function').filter((n) => n.language === 'python');
  5134. expect(pyFns.length).toBeGreaterThan(0);
  5135. const crossEdges = pyFns.flatMap((f) => cg.getOutgoingEdges(f.id)).filter((e) => nixNodeIds.has(e.target));
  5136. expect(crossEdges).toEqual([]);
  5137. });
  5138. it('never cross-links Nix calls by bare name across files (lexical scope only)', async () => {
  5139. // Both modules `inherit (lib) mkOption` — the nixpkgs idiom. A call to
  5140. // mkOption in one file must NOT resolve to the other file's inherit
  5141. // binding: Nix has no ambient cross-file namespace, so any such edge is
  5142. // wrong by construction. Same-file bindings still resolve.
  5143. fs.writeFileSync(
  5144. path.join(tempDir, 'alpha.nix'),
  5145. `{ lib, ... }:
  5146. let
  5147. inherit (lib) mkOption;
  5148. mkPort = default: mkOption { inherit default; };
  5149. in
  5150. {
  5151. options.alpha.port = mkPort 8080;
  5152. }
  5153. `
  5154. );
  5155. fs.writeFileSync(
  5156. path.join(tempDir, 'beta.nix'),
  5157. `{ lib, ... }:
  5158. let
  5159. inherit (lib) mkOption;
  5160. in
  5161. {
  5162. options.beta.enable = mkOption { default = false; };
  5163. }
  5164. `
  5165. );
  5166. cg = await CodeGraph.init(tempDir, { index: true });
  5167. cg.resolveReferences();
  5168. const crossFileCalls = cg
  5169. .getNodesByKind('file')
  5170. .flatMap((f) => cg.getOutgoingEdges(f.id))
  5171. .concat(
  5172. cg.getNodesByKind('function').flatMap((f) => cg.getOutgoingEdges(f.id)),
  5173. cg.getNodesByKind('variable').flatMap((v) => cg.getOutgoingEdges(v.id))
  5174. )
  5175. .filter((e) => e.kind === 'calls')
  5176. .map((e) => {
  5177. const src = cg.getNode(e.source);
  5178. const tgt = cg.getNode(e.target);
  5179. return { from: src?.filePath, to: tgt?.filePath, name: tgt?.name };
  5180. });
  5181. // No calls edge may cross files by bare-name matching.
  5182. expect(crossFileCalls.filter((e) => e.from !== e.to)).toEqual([]);
  5183. // The same-file chain still resolves: mkPort's mkOption call hits
  5184. // alpha.nix's own inherit binding.
  5185. const sameFile = crossFileCalls.filter((e) => e.from === e.to && e.name === 'mkOption');
  5186. expect(sameFile.length).toBeGreaterThan(0);
  5187. expect(sameFile.every((e) => e.from === 'alpha.nix' || e.from === 'beta.nix')).toBe(true);
  5188. });
  5189. it('does not resolve Nix angle-bracket, attribute, or variable imports as project file edges', async () => {
  5190. fs.writeFileSync(path.join(tempDir, 'nixpkgs.nix'), '{ bogus = true; }');
  5191. fs.writeFileSync(path.join(tempDir, 'selectedPath.nix'), '{ bogus = true; }');
  5192. fs.writeFileSync(
  5193. path.join(tempDir, 'main.nix'),
  5194. `let
  5195. pkgs = import <nixpkgs> {};
  5196. fromSources = import sources.nixpkgs {};
  5197. dynamic = import selectedPath;
  5198. in
  5199. {
  5200. inherit pkgs fromSources dynamic;
  5201. }
  5202. `
  5203. );
  5204. cg = await CodeGraph.init(tempDir, { index: true });
  5205. cg.resolveReferences();
  5206. expect(importedFilePaths('main.nix')).toEqual([]);
  5207. });
  5208. });
  5209. describe('Bindings in a module that exports nothing (#1719)', () => {
  5210. it('does not treat documentation headings as package imports', () => {
  5211. // Inject the planned Markdown node shape without depending on its extractor.
  5212. const heading: Node = {
  5213. id: 'heading:vite', name: 'vite', qualifiedName: 'guide.md#vite',
  5214. kind: 'module', language: 'markdown' as Node['language'], filePath: 'guide.md',
  5215. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  5216. };
  5217. const context = {
  5218. getNodesByName: () => [heading], getNodesInFile: () => [],
  5219. getNodesByQualifiedName: () => [], getNodesByKind: () => [],
  5220. fileExists: () => false, readFile: () => null,
  5221. getProjectRoot: () => tempDir, getAllFiles: () => [],
  5222. } as ResolutionContext;
  5223. const ref: UnresolvedRef = {
  5224. fromNodeId: 'file:consumer.ts', referenceName: 'vite', referenceKind: 'imports',
  5225. filePath: 'consumer.ts', language: 'typescript', line: 1, column: 0,
  5226. };
  5227. expect(matchByExactName(ref, context)).toBeNull();
  5228. expect(matchByExactName({ ...ref, language: 'markdown' as Node['language'] }, context)?.targetNodeId).toBe(heading.id);
  5229. context.getNodesByName = () => [{ ...heading, id: 'fn:vite', kind: 'function', language: 'typescript', filePath: 'vite.ts' }];
  5230. expect(matchByExactName(ref, context)?.targetNodeId).toBe('fn:vite');
  5231. });
  5232. it('ignores export examples in strings and comments when checking module visibility', async () => {
  5233. fs.mkdirSync(path.join(tempDir, 'src'));
  5234. fs.writeFileSync(path.join(tempDir, 'src/private.js'), [
  5235. "import fs from 'node:fs'",
  5236. 'const example = `',
  5237. 'export const example = 1',
  5238. '`',
  5239. '/*',
  5240. 'export { hidden }',
  5241. '*/',
  5242. 'function hidden() { return fs }',
  5243. 'hidden()',
  5244. ].join('\n'));
  5245. fs.writeFileSync(path.join(tempDir, 'src/consumer.js'), 'hidden()');
  5246. fs.mkdirSync(path.join(tempDir, 'legacy'));
  5247. fs.writeFileSync(path.join(tempDir, 'legacy/global.js'), 'function hidden() { return 1 }');
  5248. cg = await CodeGraph.init(tempDir, { index: true });
  5249. cg.resolveReferences();
  5250. const hidden = cg.getNodesByKind('function').find((n) => n.name === 'hidden' && n.filePath === 'src/private.js');
  5251. expect(hidden).toBeDefined();
  5252. const callers = cg.getIncomingEdges(hidden!.id).filter((e) => e.kind === 'calls');
  5253. expect(callers.some((e) => cg.getNode(e.source)?.filePath === 'src/consumer.js')).toBe(false);
  5254. expect(callers.some((e) => cg.getNode(e.source)?.filePath === 'src/private.js')).toBe(true);
  5255. const consumer = cg.getNodesByKind('file').find((n) => n.filePath === 'src/consumer.js');
  5256. expect(cg.getOutgoingEdges(consumer!.id).filter((e) => e.kind === 'calls')).toEqual([]);
  5257. });
  5258. it('does not name-match a method call to another file\'s JSON value', async () => {
  5259. fs.writeFileSync(path.join(tempDir, 'data.json'), '{"content": "hello"}');
  5260. fs.writeFileSync(path.join(tempDir, 'data.js'), "const content = require('./data.json')\nmodule.exports = { content }\n");
  5261. fs.writeFileSync(path.join(tempDir, 'consumer.js'), 'export async function read(page) { return page.frame("main").content() }');
  5262. fs.writeFileSync(path.join(tempDir, 'use-data.js'), "import { content } from './data'\nconsole.log(content)\n");
  5263. fs.writeFileSync(path.join(tempDir, 'callback.js'), "const callback = require('./handler.js')\nmodule.exports = { callback }\n");
  5264. fs.writeFileSync(path.join(tempDir, 'call.js'), 'callback()');
  5265. cg = await CodeGraph.init(tempDir, { index: true });
  5266. cg.resolveReferences();
  5267. const content = cg.getNodesByKind('constant').find((n) => n.name === 'content');
  5268. expect(content).toBeDefined();
  5269. expect(cg.getIncomingEdges(content!.id).filter((e) => e.kind === 'calls')).toEqual([]);
  5270. expect(cg.getIncomingEdges(content!.id).some((e) => e.kind === 'imports')).toBe(true);
  5271. const callback = cg.getNodesByKind('constant').find((n) => n.name === 'callback');
  5272. expect(callback).toBeDefined();
  5273. expect(cg.getIncomingEdges(callback!.id).some((e) => e.kind === 'calls')).toBe(true);
  5274. });
  5275. it('keeps a local file dependency import when a closer private name collides', async () => {
  5276. fs.writeFileSync(path.join(tempDir, 'package.json'), JSON.stringify({ dependencies: { 'local-dep': 'file:./dep' } }));
  5277. fs.mkdirSync(path.join(tempDir, 'dep'));
  5278. fs.mkdirSync(path.join(tempDir, 'src'));
  5279. fs.writeFileSync(path.join(tempDir, 'dep/package.json'), JSON.stringify({ name: 'local-dep', main: 'index.js' }));
  5280. fs.writeFileSync(path.join(tempDir, 'dep/index.js'), "export const msg = 'local'\n");
  5281. fs.writeFileSync(path.join(tempDir, 'src/private.js'), "import fs from 'node:fs'\nconst msg = 'private'\n");
  5282. fs.writeFileSync(path.join(tempDir, 'src/consumer.js'), "import { msg } from 'local-dep'\nconsole.log(msg)\n");
  5283. cg = await CodeGraph.init(tempDir, { index: true });
  5284. cg.resolveReferences();
  5285. const msg = cg.getNodesByKind('constant').find((n) => n.name === 'msg' && n.filePath === 'dep/index.js');
  5286. expect(msg).toBeDefined();
  5287. expect(cg.getIncomingEdges(msg!.id).some((e) => e.kind === 'imports')).toBe(true);
  5288. });
  5289. it('preserves executable CommonJS exports inside nested template interpolations', async () => {
  5290. fs.writeFileSync(path.join(tempDir, 'cjs.js'), [
  5291. "import fs from 'node:fs'",
  5292. 'function helper() { return fs }',
  5293. 'const text = `outer ${`inner ${module.exports = { helper }}`}`',
  5294. ].join('\n'));
  5295. fs.writeFileSync(path.join(tempDir, 'consumer.js'), 'helper()');
  5296. cg = await CodeGraph.init(tempDir, { index: true });
  5297. cg.resolveReferences();
  5298. const helper = cg.getNodesByKind('function').find((n) => n.name === 'helper');
  5299. expect(helper).toBeDefined();
  5300. expect(cg.getIncomingEdges(helper!.id).some((e) =>
  5301. e.kind === 'calls' && cg.getNode(e.source)?.filePath === 'consumer.js')).toBe(true);
  5302. });
  5303. 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) => {
  5304. 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');
  5305. fs.writeFileSync(path.join(tempDir, 'consumer.js'), 'visible()');
  5306. cg = await CodeGraph.init(tempDir, { index: true });
  5307. cg.resolveReferences();
  5308. const visible = cg.getNodesByKind('function').find((n) => n.name === 'visible');
  5309. expect(visible).toBeDefined();
  5310. expect(cg.getIncomingEdges(visible!.id).some((e) => e.kind === 'calls')).toBe(true);
  5311. });
  5312. // On vitejs/vite, every `import { defineConfig } from 'vite'` across the
  5313. // playground resolved onto `playground/ssr-html/test-stacktrace.js::vite`
  5314. // — `const vite = await createServer(…)` at module scope in a file with
  5315. // zero exports — because exact-match commits whenever one candidate
  5316. // survives, and nothing asked whether an import could reach it. Only
  5317. // `sealed.js` may be filtered; every other file here is a class that must
  5318. // NOT be — a classic script (a top-level binding really is a reachable
  5319. // global), a CommonJS module, one exporting through `exports["x"]`, an ESM
  5320. // file whose export is a later `export { … }` statement (which leaves
  5321. // `isExported` false on the declaration's node), and one contributing a
  5322. // name through `declare global` while exporting nothing of its own.
  5323. let tmpDir: string;
  5324. let cg: CodeGraph;
  5325. afterEach(() => {
  5326. cg?.close();
  5327. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  5328. });
  5329. it('drops them as cross-file candidates, and keeps scripts, CJS and later exports', async () => {
  5330. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1719-'));
  5331. fs.writeFileSync(
  5332. path.join(tmpDir, 'sealed.js'),
  5333. `import fsp from 'node:fs/promises'
  5334. function widget() {
  5335. return fsp
  5336. }
  5337. widget()
  5338. `
  5339. );
  5340. fs.writeFileSync(
  5341. path.join(tmpDir, 'script.js'),
  5342. `function gadget() {
  5343. return 1
  5344. }
  5345. `
  5346. );
  5347. fs.writeFileSync(
  5348. path.join(tmpDir, 'cjs.js'),
  5349. `import osp from 'node:os'
  5350. function helper() {
  5351. return osp
  5352. }
  5353. module.exports = { helper }
  5354. `
  5355. );
  5356. fs.writeFileSync(
  5357. path.join(tmpDir, 'later.js'),
  5358. `import pathp from 'node:path'
  5359. function parser() {
  5360. return pathp
  5361. }
  5362. export { parser }
  5363. `
  5364. );
  5365. // `exports["x"]` is a CommonJS export too, and a file declaring globals
  5366. // offers them to every other file whether or not it exports anything of
  5367. // its own. Both would read as sealed on a test that looked only for
  5368. // `export …`, `module.exports` and `exports.x`.
  5369. fs.writeFileSync(
  5370. path.join(tmpDir, 'bracket.js'),
  5371. `import urlp from 'node:url'
  5372. function bracketed() {
  5373. return urlp
  5374. }
  5375. exports["bracketed"] = bracketed
  5376. `
  5377. );
  5378. // A module with imports and no export of its own still contributes every
  5379. // name in `declare global` to every other file. `plain.ts` is the control
  5380. // that makes the assertion mean something: it is the same "import, no
  5381. // export" shape holding the same kind of declaration, so the pair differs
  5382. // only by the `declare global`, and an assertion on StrayFace alone would
  5383. // pass whatever the guard did.
  5384. fs.writeFileSync(
  5385. path.join(tmpDir, 'ambient.ts'),
  5386. `import './later'
  5387. declare global {
  5388. interface StrayFace {
  5389. a: number
  5390. }
  5391. }
  5392. `
  5393. );
  5394. fs.writeFileSync(
  5395. path.join(tmpDir, 'plain.ts'),
  5396. `import './later'
  5397. interface HiddenFace {
  5398. a: number
  5399. }
  5400. const unused: HiddenFace = { a: 1 }
  5401. `
  5402. );
  5403. // A type annotation is the reference here, so this consumer must be .ts.
  5404. fs.writeFileSync(
  5405. path.join(tmpDir, 'consumer.ts'),
  5406. `const face: StrayFace = { a: 1 }
  5407. const hidden: HiddenFace = { a: 2 }
  5408. export function use(): number {
  5409. return face.a + hidden.a
  5410. }
  5411. `
  5412. );
  5413. // Nothing here is bound by an import, so every name is a free reference
  5414. // that falls through to exact name matching — the path this rule sits on.
  5415. // A bare import would reach that path too, but a bare specifier names a
  5416. // package outside the graph, so no project node is the right target for
  5417. // it and such a fixture would assert a resolution nothing should make.
  5418. fs.writeFileSync(
  5419. path.join(tmpDir, 'consumer.js'),
  5420. `widget()
  5421. gadget()
  5422. helper()
  5423. parser()
  5424. bracketed()
  5425. `
  5426. );
  5427. cg = await CodeGraph.init(tmpDir, { index: true });
  5428. cg.resolveReferences();
  5429. // Incoming edges rather than callers, so the interfaces are asked the
  5430. // same question as the functions: a type annotation is a reference, not
  5431. // a call.
  5432. const reachedFrom = (consumer: string, name: string): boolean => {
  5433. const target = cg
  5434. .searchNodes(name, { limit: 10 })
  5435. .find((r) => r.node.name === name && r.node.filePath !== consumer);
  5436. expect(target, `no node named ${name}`).toBeDefined();
  5437. return cg
  5438. .getIncomingEdges(target!.node.id)
  5439. .some((e) => cg.getNode(e.source)?.filePath === consumer);
  5440. };
  5441. expect(reachedFrom('consumer.js', 'widget')).toBe(false);
  5442. expect(reachedFrom('consumer.js', 'gadget')).toBe(true);
  5443. expect(reachedFrom('consumer.js', 'helper')).toBe(true);
  5444. expect(reachedFrom('consumer.js', 'parser')).toBe(true);
  5445. expect(reachedFrom('consumer.js', 'bracketed')).toBe(true);
  5446. expect(reachedFrom('consumer.ts', 'StrayFace')).toBe(true);
  5447. expect(reachedFrom('consumer.ts', 'HiddenFace')).toBe(false);
  5448. }, 30000);
  5449. });
  5450. });