resolution.test.ts 191 KB

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