resolution.test.ts 198 KB

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