resolution.test.ts 226 KB

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