1
0

resolution.test.ts 211 KB

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