1
0

resolution.test.ts 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137
  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 } 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 prefer same-module candidates over cross-module matches', () => {
  77. // Simulates a Python monorepo where multiple apps define navigate()
  78. const candidateA: Node = {
  79. id: 'func:apps/app_a/src/server.py:navigate:10',
  80. kind: 'function',
  81. name: 'navigate',
  82. qualifiedName: 'apps/app_a/src/server.py::navigate',
  83. filePath: 'apps/app_a/src/server.py',
  84. language: 'python',
  85. startLine: 10,
  86. endLine: 20,
  87. startColumn: 0,
  88. endColumn: 0,
  89. updatedAt: Date.now(),
  90. };
  91. const candidateB: Node = {
  92. id: 'func:apps/app_b/src/server.py:navigate:15',
  93. kind: 'function',
  94. name: 'navigate',
  95. qualifiedName: 'apps/app_b/src/server.py::navigate',
  96. filePath: 'apps/app_b/src/server.py',
  97. language: 'python',
  98. startLine: 15,
  99. endLine: 25,
  100. startColumn: 0,
  101. endColumn: 0,
  102. updatedAt: Date.now(),
  103. };
  104. const context: ResolutionContext = {
  105. getNodesInFile: () => [],
  106. getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
  107. getNodesByQualifiedName: () => [],
  108. getNodesByKind: () => [],
  109. fileExists: () => true,
  110. readFile: () => null,
  111. getProjectRoot: () => '/test',
  112. getAllFiles: () => [],
  113. getNodesByLowerName: () => [],
  114. getImportMappings: () => [],
  115. };
  116. // Reference from app_a should resolve to app_a's navigate, not app_b's
  117. const ref = {
  118. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  119. referenceName: 'navigate',
  120. referenceKind: 'calls' as const,
  121. line: 5,
  122. column: 10,
  123. filePath: 'apps/app_a/src/handler.py',
  124. language: 'python' as const,
  125. };
  126. const result = matchReference(ref, context);
  127. expect(result).not.toBeNull();
  128. expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
  129. expect(result?.resolvedBy).toBe('exact-match');
  130. });
  131. it('should lower confidence for cross-module exact matches', () => {
  132. // Only one candidate but in a completely different module
  133. const candidates: Node[] = [
  134. {
  135. id: 'func:apps/app_b/src/server.py:navigate:10',
  136. kind: 'function',
  137. name: 'navigate',
  138. qualifiedName: 'apps/app_b/src/server.py::navigate',
  139. filePath: 'apps/app_b/src/server.py',
  140. language: 'python',
  141. startLine: 10,
  142. endLine: 20,
  143. startColumn: 0,
  144. endColumn: 0,
  145. updatedAt: Date.now(),
  146. },
  147. {
  148. id: 'func:apps/app_c/src/server.py:navigate:10',
  149. kind: 'function',
  150. name: 'navigate',
  151. qualifiedName: 'apps/app_c/src/server.py::navigate',
  152. filePath: 'apps/app_c/src/server.py',
  153. language: 'python',
  154. startLine: 10,
  155. endLine: 20,
  156. startColumn: 0,
  157. endColumn: 0,
  158. updatedAt: Date.now(),
  159. },
  160. ];
  161. const context: ResolutionContext = {
  162. getNodesInFile: () => [],
  163. getNodesByName: (name) => name === 'navigate' ? candidates : [],
  164. getNodesByQualifiedName: () => [],
  165. getNodesByKind: () => [],
  166. fileExists: () => true,
  167. readFile: () => null,
  168. getProjectRoot: () => '/test',
  169. getAllFiles: () => [],
  170. getNodesByLowerName: () => [],
  171. getImportMappings: () => [],
  172. };
  173. // Reference from app_a — neither candidate is in the same module
  174. const ref = {
  175. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  176. referenceName: 'navigate',
  177. referenceKind: 'calls' as const,
  178. line: 5,
  179. column: 10,
  180. filePath: 'apps/app_a/src/handler.py',
  181. language: 'python' as const,
  182. };
  183. const result = matchReference(ref, context);
  184. // Should still resolve but with low confidence
  185. expect(result).not.toBeNull();
  186. expect(result?.confidence).toBeLessThanOrEqual(0.4);
  187. });
  188. it('should match qualified name references', () => {
  189. const mockClassNode: Node = {
  190. id: 'class:user.ts:User:5',
  191. kind: 'class',
  192. name: 'User',
  193. qualifiedName: 'user.ts::User',
  194. filePath: 'user.ts',
  195. language: 'typescript',
  196. startLine: 5,
  197. endLine: 30,
  198. startColumn: 0,
  199. endColumn: 0,
  200. updatedAt: Date.now(),
  201. };
  202. const mockMethodNode: Node = {
  203. id: 'method:user.ts:User.save:15',
  204. kind: 'method',
  205. name: 'save',
  206. qualifiedName: 'user.ts::User::save',
  207. filePath: 'user.ts',
  208. language: 'typescript',
  209. startLine: 15,
  210. endLine: 25,
  211. startColumn: 0,
  212. endColumn: 0,
  213. updatedAt: Date.now(),
  214. };
  215. const context: ResolutionContext = {
  216. getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
  217. getNodesByName: (name) => {
  218. if (name === 'User') return [mockClassNode];
  219. if (name === 'save') return [mockMethodNode];
  220. return [];
  221. },
  222. getNodesByQualifiedName: (qn) => {
  223. if (qn === 'user.ts::User::save') return [mockMethodNode];
  224. return [];
  225. },
  226. getNodesByKind: () => [],
  227. fileExists: () => true,
  228. readFile: () => null,
  229. getProjectRoot: () => '/test',
  230. getAllFiles: () => ['user.ts'],
  231. };
  232. const ref = {
  233. fromNodeId: 'caller:main.ts:main:5',
  234. referenceName: 'User.save',
  235. referenceKind: 'calls' as const,
  236. line: 5,
  237. column: 10,
  238. filePath: 'main.ts',
  239. language: 'typescript' as const,
  240. };
  241. const result = matchReference(ref, context);
  242. expect(result).not.toBeNull();
  243. expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
  244. });
  245. });
  246. describe('Ubiquitous-name ceiling (#999)', () => {
  247. // A vendored theme/SDK re-declares the same method name across thousands of
  248. // files (Metronic's `init`/`update`/… on every widget). The fuzzy strategies
  249. // used to score every same-named candidate per ref — O(K) per ref, O(K²)
  250. // total — which pinned a core for 15-28 min at "Resolving refs … 94%". Above
  251. // the ceiling they must DECLINE instead, since no proximity/word-overlap
  252. // score can pick the one true target among thousands anyway.
  253. const CEILING = 500;
  254. // A spy context: counts how many nodes the strategy actually inspects, so we
  255. // can assert the cap short-circuits BEFORE the O(K) scoring (not just that it
  256. // returns null).
  257. const makeManyMethods = (n: number, name: string): Node[] =>
  258. Array.from({ length: n }, (_, i) => ({
  259. id: `method:widget${i}.js:Widget${i}.${name}:1`,
  260. kind: 'method' as const,
  261. name,
  262. qualifiedName: `widget${i}.js::Widget${i}::${name}`,
  263. filePath: `static/theme/widget${i}.js`,
  264. language: 'javascript' as const,
  265. startLine: 1,
  266. endLine: 5,
  267. startColumn: 0,
  268. endColumn: 0,
  269. updatedAt: Date.now(),
  270. }));
  271. const spyContext = (nodes: Node[]): { ctx: ResolutionContext; lookups: () => number } => {
  272. let scanned = 0;
  273. const ctx: ResolutionContext = {
  274. getNodesInFile: () => [],
  275. getNodesByName: (name) => {
  276. const hit = nodes.filter((n) => n.name === name);
  277. scanned += hit.length;
  278. return hit;
  279. },
  280. getNodesByQualifiedName: () => [],
  281. getNodesByKind: () => [],
  282. fileExists: () => true,
  283. readFile: () => null,
  284. getProjectRoot: () => '/test',
  285. getAllFiles: () => [],
  286. getNodesByLowerName: () => [],
  287. getImportMappings: () => [],
  288. };
  289. return { ctx, lookups: () => scanned };
  290. };
  291. it('declines a method call (`obj.init`) above the ceiling instead of scoring K candidates', () => {
  292. const { ctx } = spyContext(makeManyMethods(CEILING + 1, 'init'));
  293. const ref = {
  294. fromNodeId: 'method:caller.js:caller:1',
  295. referenceName: 'widget.init',
  296. referenceKind: 'calls' as const,
  297. line: 2,
  298. column: 4,
  299. filePath: 'static/theme/caller.js',
  300. language: 'javascript' as const,
  301. };
  302. expect(matchReference(ref, ctx)).toBeNull();
  303. });
  304. it('declines a bare exact-name ref above the ceiling', () => {
  305. const { ctx } = spyContext(makeManyMethods(CEILING + 1, 'render'));
  306. const ref = {
  307. fromNodeId: 'method:caller.js:caller:1',
  308. referenceName: 'render',
  309. referenceKind: 'calls' as const,
  310. line: 2,
  311. column: 4,
  312. filePath: 'static/theme/caller.js',
  313. language: 'javascript' as const,
  314. };
  315. expect(matchReference(ref, ctx)).toBeNull();
  316. });
  317. it('still resolves a SAME-FILE definition when one exists (precise path unaffected)', () => {
  318. // Strategy 1 (class-name) and same-file matching are precise — a ubiquitous
  319. // name with an unambiguous local target still resolves.
  320. const nodes = makeManyMethods(CEILING + 1, 'init');
  321. const local: Node = {
  322. id: 'class:static/theme/caller.js:Widgetly:1',
  323. kind: 'class',
  324. name: 'Widgetly',
  325. qualifiedName: 'static/theme/caller.js::Widgetly',
  326. filePath: 'static/theme/caller.js',
  327. language: 'javascript',
  328. startLine: 1, endLine: 9, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  329. };
  330. const localMethod: Node = {
  331. id: 'method:static/theme/caller.js:Widgetly.init:2',
  332. kind: 'method',
  333. name: 'init',
  334. qualifiedName: 'static/theme/caller.js::Widgetly::init',
  335. filePath: 'static/theme/caller.js',
  336. language: 'javascript',
  337. startLine: 2, endLine: 4, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  338. };
  339. const all = [...nodes, local, localMethod];
  340. const ctx: ResolutionContext = {
  341. getNodesInFile: (fp) => all.filter((n) => n.filePath === fp),
  342. getNodesByName: (name) => all.filter((n) => n.name === name),
  343. getNodesByQualifiedName: () => [],
  344. getNodesByKind: () => [],
  345. fileExists: () => true,
  346. readFile: () => null,
  347. getProjectRoot: () => '/test',
  348. getAllFiles: () => [],
  349. getNodesByLowerName: () => [],
  350. getImportMappings: () => [],
  351. };
  352. // `Widgetly.init` names the class explicitly → Strategy 1 resolves it.
  353. const ref = {
  354. fromNodeId: 'method:static/theme/caller.js:caller:6',
  355. referenceName: 'Widgetly.init',
  356. referenceKind: 'calls' as const,
  357. line: 6,
  358. column: 4,
  359. filePath: 'static/theme/caller.js',
  360. language: 'javascript' as const,
  361. };
  362. const result = matchReference(ref, ctx);
  363. expect(result?.targetNodeId).toBe('method:static/theme/caller.js:Widgetly.init:2');
  364. });
  365. it('still scores normally JUST below the ceiling (no behavior change for normal repos)', () => {
  366. // Real repos top out near ~40 same-named methods; this proves a sub-ceiling
  367. // collision still resolves via proximity, so the cap is invisible to them.
  368. const nodes = makeManyMethods(CEILING - 1, 'update');
  369. // Make ONE candidate share the caller's directory so proximity picks it.
  370. nodes[0] = {
  371. ...nodes[0]!,
  372. id: 'method:static/theme/app/Widget0.update:1',
  373. qualifiedName: 'static/theme/app/widget.js::Widget0::update',
  374. filePath: 'static/theme/app/widget.js',
  375. };
  376. const ctx: ResolutionContext = {
  377. getNodesInFile: () => [],
  378. getNodesByName: (name) => nodes.filter((n) => n.name === name),
  379. getNodesByQualifiedName: () => [],
  380. getNodesByKind: () => [],
  381. fileExists: () => true,
  382. readFile: () => null,
  383. getProjectRoot: () => '/test',
  384. getAllFiles: () => [],
  385. getNodesByLowerName: () => [],
  386. getImportMappings: () => [],
  387. };
  388. const ref = {
  389. fromNodeId: 'method:static/theme/app/caller.js:caller:1',
  390. referenceName: 'update',
  391. referenceKind: 'calls' as const,
  392. line: 2,
  393. column: 4,
  394. filePath: 'static/theme/app/caller.js',
  395. language: 'javascript' as const,
  396. };
  397. // Below the ceiling the fuzzy path runs and resolves SOMETHING (not capped).
  398. expect(matchReference(ref, ctx)).not.toBeNull();
  399. });
  400. });
  401. describe('Import Resolver', () => {
  402. it('should resolve relative import paths', () => {
  403. const context: ResolutionContext = {
  404. getNodesInFile: () => [],
  405. getNodesByName: () => [],
  406. getNodesByQualifiedName: () => [],
  407. getNodesByKind: () => [],
  408. fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
  409. readFile: () => null,
  410. getProjectRoot: () => '',
  411. getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
  412. };
  413. const result = resolveImportPath(
  414. './utils',
  415. 'src/components/Button.ts',
  416. 'typescript',
  417. context
  418. );
  419. expect(result).toBe('src/components/utils.ts');
  420. });
  421. it('should resolve parent directory imports', () => {
  422. const context: ResolutionContext = {
  423. getNodesInFile: () => [],
  424. getNodesByName: () => [],
  425. getNodesByQualifiedName: () => [],
  426. getNodesByKind: () => [],
  427. fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
  428. readFile: () => null,
  429. getProjectRoot: () => '',
  430. getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
  431. };
  432. const result = resolveImportPath(
  433. '../helpers',
  434. 'src/components/Button.ts',
  435. 'typescript',
  436. context
  437. );
  438. expect(result).toBe('src/helpers.ts');
  439. });
  440. it('should extract JS/TS import mappings', () => {
  441. const content = `
  442. import { foo } from './foo';
  443. import bar from '../bar';
  444. import * as utils from './utils';
  445. import { baz, qux } from './baz';
  446. `;
  447. const mappings = extractImportMappings(
  448. 'src/index.ts',
  449. content,
  450. 'typescript'
  451. );
  452. expect(mappings.length).toBeGreaterThan(0);
  453. expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
  454. expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
  455. });
  456. it('should extract Python import mappings', () => {
  457. const content = `
  458. from utils import helper
  459. from .models import User
  460. import os
  461. from ..services import auth_service
  462. `;
  463. const mappings = extractImportMappings(
  464. 'src/main.py',
  465. content,
  466. 'python'
  467. );
  468. expect(mappings.length).toBeGreaterThan(0);
  469. expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
  470. expect(mappings.some((m) => m.localName === 'User')).toBe(true);
  471. });
  472. });
  473. describe('JVM FQN Import Resolution', () => {
  474. // Build a ResolutionContext stub whose getNodesByQualifiedName answers
  475. // from a fixed table — the only context method resolveJvmImport touches.
  476. const makeContext = (byQName: Record<string, Node[]>): ResolutionContext => ({
  477. getNodesInFile: () => [],
  478. getNodesByName: () => [],
  479. getNodesByQualifiedName: (q) => byQName[q] ?? [],
  480. getNodesByKind: () => [],
  481. fileExists: () => false,
  482. readFile: () => null,
  483. getProjectRoot: () => '',
  484. getAllFiles: () => [],
  485. });
  486. const node = (id: string, name: string, qualifiedName: string, kind: Node['kind'] = 'class', language: Node['language'] = 'kotlin'): Node => ({
  487. id, kind, name, qualifiedName,
  488. filePath: 'Models.kt', language,
  489. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0,
  490. updatedAt: 0,
  491. });
  492. const importRef = (referenceName: string, language: Node['language'] = 'kotlin'): UnresolvedRef => ({
  493. fromNodeId: 'caller',
  494. referenceName,
  495. referenceKind: 'imports',
  496. line: 1, column: 0,
  497. filePath: 'Caller.kt',
  498. language,
  499. });
  500. it('resolves a Kotlin class import by FQN regardless of filename', () => {
  501. const target = node('n1', 'Bar', 'com.example.foo::Bar');
  502. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  503. const result = resolveJvmImport(importRef('com.example.foo.Bar'), ctx);
  504. expect(result?.targetNodeId).toBe('n1');
  505. expect(result?.resolvedBy).toBe('import');
  506. });
  507. it('resolves a Kotlin top-level function import by FQN', () => {
  508. const util = node('n2', 'util', 'com.example.foo::util', 'function');
  509. const ctx = makeContext({ 'com.example.foo::util': [util] });
  510. const result = resolveJvmImport(importRef('com.example.foo.util'), ctx);
  511. expect(result?.targetNodeId).toBe('n2');
  512. });
  513. it('resolves a Java import by FQN', () => {
  514. const target = node('n3', 'Bar', 'com.example.foo::Bar', 'class', 'java');
  515. const ctx = makeContext({ 'com.example.foo::Bar': [target] });
  516. const result = resolveJvmImport(importRef('com.example.foo.Bar', 'java'), ctx);
  517. expect(result?.targetNodeId).toBe('n3');
  518. });
  519. it('resolves cross-language: Kotlin importing a Java class', () => {
  520. // The Kotlin file declares `import com.example.JavaBar` — the target is
  521. // a Java class node. JVM interop means the resolver doesn't care about
  522. // the source language of the target, only that the FQN matches.
  523. const target = node('n4', 'JavaBar', 'com.example::JavaBar', 'class', 'java');
  524. const ctx = makeContext({ 'com.example::JavaBar': [target] });
  525. const result = resolveJvmImport(importRef('com.example.JavaBar'), ctx);
  526. expect(result?.targetNodeId).toBe('n4');
  527. });
  528. it('disambiguates a name collision across packages', () => {
  529. // Two classes named `Bar` in different packages. Each import resolves
  530. // to the one whose FQN matches — not to "whichever was found first".
  531. const barA = node('n5a', 'Bar', 'com.example.alpha::Bar');
  532. const barB = node('n5b', 'Bar', 'com.example.beta::Bar');
  533. const ctx = makeContext({
  534. 'com.example.alpha::Bar': [barA],
  535. 'com.example.beta::Bar': [barB],
  536. });
  537. expect(resolveJvmImport(importRef('com.example.alpha.Bar'), ctx)?.targetNodeId).toBe('n5a');
  538. expect(resolveJvmImport(importRef('com.example.beta.Bar'), ctx)?.targetNodeId).toBe('n5b');
  539. });
  540. it('returns null for wildcard imports', () => {
  541. const ctx = makeContext({});
  542. expect(resolveJvmImport(importRef('com.example.foo.*'), ctx)).toBeNull();
  543. });
  544. it('returns null for unqualified names', () => {
  545. // A single-segment name has no package; nothing to look up by FQN.
  546. const ctx = makeContext({ 'Bar': [node('n6', 'Bar', 'Bar')] });
  547. expect(resolveJvmImport(importRef('Bar'), ctx)).toBeNull();
  548. });
  549. it('returns null for non-JVM languages', () => {
  550. const target = node('n7', 'Bar', 'com.example::Bar');
  551. const ctx = makeContext({ 'com.example::Bar': [target] });
  552. expect(resolveJvmImport(importRef('com.example.Bar', 'typescript'), ctx)).toBeNull();
  553. });
  554. it('returns null for non-imports reference kinds', () => {
  555. // The resolver intentionally only acts on `imports` refs; ordinary
  556. // `calls`/`extends` refs fall through to the framework + name-matcher
  557. // strategies.
  558. const target = node('n8', 'Bar', 'com.example::Bar');
  559. const ctx = makeContext({ 'com.example::Bar': [target] });
  560. const ref: UnresolvedRef = {
  561. fromNodeId: 'caller', referenceName: 'com.example.Bar',
  562. referenceKind: 'calls', line: 1, column: 0,
  563. filePath: 'Caller.kt', language: 'kotlin',
  564. };
  565. expect(resolveJvmImport(ref, ctx)).toBeNull();
  566. });
  567. it('returns null when the FQN is not in the index', () => {
  568. const ctx = makeContext({});
  569. expect(resolveJvmImport(importRef('com.example.Unknown'), ctx)).toBeNull();
  570. });
  571. });
  572. describe('Framework Detection', () => {
  573. it('should detect React framework', () => {
  574. const context: ResolutionContext = {
  575. getNodesInFile: () => [],
  576. getNodesByName: () => [],
  577. getNodesByQualifiedName: () => [],
  578. getNodesByKind: () => [],
  579. fileExists: () => false,
  580. readFile: (p) => {
  581. if (p === 'package.json') {
  582. return JSON.stringify({
  583. dependencies: { react: '^18.0.0' },
  584. });
  585. }
  586. return null;
  587. },
  588. getProjectRoot: () => '/test',
  589. getAllFiles: () => ['package.json', 'src/App.tsx'],
  590. };
  591. const frameworks = detectFrameworks(context);
  592. expect(frameworks.some((f) => f.name === 'react')).toBe(true);
  593. });
  594. it('should detect Express framework', () => {
  595. const context: ResolutionContext = {
  596. getNodesInFile: () => [],
  597. getNodesByName: () => [],
  598. getNodesByQualifiedName: () => [],
  599. getNodesByKind: () => [],
  600. fileExists: () => false,
  601. readFile: (p) => {
  602. if (p === 'package.json') {
  603. return JSON.stringify({
  604. dependencies: { express: '^4.18.0' },
  605. });
  606. }
  607. return null;
  608. },
  609. getProjectRoot: () => '/test',
  610. getAllFiles: () => ['package.json', 'src/app.js'],
  611. };
  612. const frameworks = detectFrameworks(context);
  613. expect(frameworks.some((f) => f.name === 'express')).toBe(true);
  614. });
  615. it('should detect Laravel framework', () => {
  616. const context: ResolutionContext = {
  617. getNodesInFile: () => [],
  618. getNodesByName: () => [],
  619. getNodesByQualifiedName: () => [],
  620. getNodesByKind: () => [],
  621. fileExists: (p) => p === 'artisan',
  622. readFile: () => null,
  623. getProjectRoot: () => '/test',
  624. getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
  625. };
  626. const frameworks = detectFrameworks(context);
  627. expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
  628. });
  629. it('should return all framework resolvers', () => {
  630. const resolvers = getAllFrameworkResolvers();
  631. expect(resolvers.length).toBeGreaterThan(0);
  632. expect(resolvers.some((r) => r.name === 'react')).toBe(true);
  633. expect(resolvers.some((r) => r.name === 'express')).toBe(true);
  634. expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
  635. });
  636. });
  637. describe('React Framework Resolver', () => {
  638. it('should resolve React component references', () => {
  639. const mockNodes: Node[] = [
  640. {
  641. id: 'component:src/Button.tsx:Button:5',
  642. kind: 'component',
  643. name: 'Button',
  644. qualifiedName: 'src/Button.tsx::Button',
  645. filePath: 'src/Button.tsx',
  646. language: 'tsx',
  647. startLine: 5,
  648. endLine: 20,
  649. startColumn: 0,
  650. endColumn: 0,
  651. updatedAt: Date.now(),
  652. },
  653. ];
  654. const context: ResolutionContext = {
  655. getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
  656. getNodesByName: () => mockNodes,
  657. getNodesByQualifiedName: () => [],
  658. getNodesByKind: () => [],
  659. fileExists: () => false,
  660. readFile: (p) => {
  661. if (p === 'package.json') {
  662. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  663. }
  664. return null;
  665. },
  666. getProjectRoot: () => '/test',
  667. getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
  668. };
  669. const frameworks = detectFrameworks(context);
  670. const reactResolver = frameworks.find((f) => f.name === 'react');
  671. expect(reactResolver).toBeDefined();
  672. const ref = {
  673. fromNodeId: 'component:src/App.tsx:App:1',
  674. referenceName: 'Button',
  675. referenceKind: 'renders' as const,
  676. line: 10,
  677. column: 5,
  678. filePath: 'src/App.tsx',
  679. // Refs extracted from .tsx files carry language 'tsx' — component
  680. // resolution is gated to JSX-capable refs (#764: PascalCase TYPE refs
  681. // from plain .ts files were resolving to arbitrary same-named classes).
  682. language: 'tsx' as const,
  683. };
  684. const result = reactResolver!.resolve(ref, context);
  685. expect(result).not.toBeNull();
  686. expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
  687. // The same PascalCase name referenced from a plain .ts file is a TYPE
  688. // reference, not a component usage — component resolution must decline
  689. // and leave it to proximity-aware name matching (#764: a .ts GraphQL
  690. // types file's own `Account` alias was losing to an arbitrary same-named
  691. // class in another monorepo package).
  692. const tsRef = { ...ref, filePath: 'src/models.ts', language: 'typescript' as const };
  693. expect(reactResolver!.resolve(tsRef, context)).toBeNull();
  694. });
  695. it('should resolve custom hook references', () => {
  696. const mockNodes: Node[] = [
  697. {
  698. id: 'hook:src/hooks/useAuth.ts:useAuth:1',
  699. kind: 'function',
  700. name: 'useAuth',
  701. qualifiedName: 'src/hooks/useAuth.ts::useAuth',
  702. filePath: 'src/hooks/useAuth.ts',
  703. language: 'typescript',
  704. startLine: 1,
  705. endLine: 20,
  706. startColumn: 0,
  707. endColumn: 0,
  708. updatedAt: Date.now(),
  709. },
  710. ];
  711. const context: ResolutionContext = {
  712. getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
  713. getNodesByName: () => mockNodes,
  714. getNodesByQualifiedName: () => [],
  715. getNodesByKind: () => [],
  716. fileExists: () => false,
  717. readFile: (p) => {
  718. if (p === 'package.json') {
  719. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  720. }
  721. return null;
  722. },
  723. getProjectRoot: () => '/test',
  724. getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
  725. };
  726. const frameworks = detectFrameworks(context);
  727. const reactResolver = frameworks.find((f) => f.name === 'react');
  728. const ref = {
  729. fromNodeId: 'component:src/App.tsx:App:1',
  730. referenceName: 'useAuth',
  731. referenceKind: 'calls' as const,
  732. line: 5,
  733. column: 10,
  734. filePath: 'src/App.tsx',
  735. language: 'typescript' as const,
  736. };
  737. const result = reactResolver!.resolve(ref, context);
  738. expect(result).not.toBeNull();
  739. expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
  740. });
  741. });
  742. describe('Integration Tests', () => {
  743. it('should create resolver from CodeGraph instance', async () => {
  744. // Create a simple TypeScript project
  745. fs.writeFileSync(
  746. path.join(tempDir, 'package.json'),
  747. JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
  748. );
  749. const srcDir = path.join(tempDir, 'src');
  750. fs.mkdirSync(srcDir);
  751. // Create utility file
  752. fs.writeFileSync(
  753. path.join(srcDir, 'utils.ts'),
  754. `export function formatDate(date: Date): string {
  755. return date.toISOString();
  756. }
  757. export function parseDate(str: string): Date {
  758. return new Date(str);
  759. }`
  760. );
  761. // Create main file that uses utils
  762. fs.writeFileSync(
  763. path.join(srcDir, 'main.ts'),
  764. `import { formatDate, parseDate } from './utils';
  765. function processDate(input: string): string {
  766. const date = parseDate(input);
  767. return formatDate(date);
  768. }`
  769. );
  770. // Initialize and index
  771. cg = await CodeGraph.init(tempDir, { index: true });
  772. // Check that resolver detected React framework
  773. const frameworks = cg.getDetectedFrameworks();
  774. expect(frameworks).toContain('react');
  775. // Get stats to verify indexing worked
  776. const stats = cg.getStats();
  777. expect(stats.fileCount).toBe(2);
  778. expect(stats.nodeCount).toBeGreaterThan(0);
  779. });
  780. it('should resolve references after indexing', async () => {
  781. // Create a project with references
  782. const srcDir = path.join(tempDir, 'src');
  783. fs.mkdirSync(srcDir, { recursive: true });
  784. fs.writeFileSync(
  785. path.join(srcDir, 'helper.ts'),
  786. `export function helperFunction(): void {
  787. console.log('helper');
  788. }`
  789. );
  790. fs.writeFileSync(
  791. path.join(srcDir, 'main.ts'),
  792. `import { helperFunction } from './helper';
  793. function main(): void {
  794. helperFunction();
  795. }`
  796. );
  797. cg = await CodeGraph.init(tempDir, { index: true });
  798. // Run reference resolution
  799. const result = cg.resolveReferences();
  800. // Should have attempted resolution
  801. expect(result.stats.total).toBeGreaterThanOrEqual(0);
  802. });
  803. it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
  804. // Python has no `new` keyword — `Foo()` is the standard
  805. // instantiation syntax. Extraction can't tell that apart from
  806. // a function call without symbol info, so it emits a `calls`
  807. // ref. Resolution promotes it to `instantiates` once the
  808. // target is known to be a class.
  809. const srcDir = path.join(tempDir, 'src');
  810. fs.mkdirSync(srcDir, { recursive: true });
  811. fs.writeFileSync(
  812. path.join(srcDir, 'app.py'),
  813. `class UserService:
  814. def __init__(self):
  815. self.db = None
  816. def bootstrap():
  817. return UserService()
  818. `
  819. );
  820. cg = await CodeGraph.init(tempDir, { index: true });
  821. cg.resolveReferences();
  822. const bootstrap = cg
  823. .getNodesByKind('function')
  824. .find((n) => n.name === 'bootstrap');
  825. expect(bootstrap).toBeDefined();
  826. const outgoing = cg.getOutgoingEdges(bootstrap!.id);
  827. const instantiates = outgoing.find((e) => e.kind === 'instantiates');
  828. expect(instantiates).toBeDefined();
  829. // Same edge must NOT also appear as a `calls` edge — promotion
  830. // replaces the kind, doesn't duplicate.
  831. const callsToUserService = outgoing.filter(
  832. (e) => e.kind === 'calls' && e.target === instantiates!.target
  833. );
  834. expect(callsToUserService).toHaveLength(0);
  835. });
  836. it('records instantiates for C++ stack/brace construction, targeting the class (#1035)', async () => {
  837. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init)
  838. // carry the constructor args directly on the declarator — there's no
  839. // call/new node — so they recorded no `instantiates` edge, while heap
  840. // `new Calculator(0)` did. Both stack forms now do.
  841. fs.writeFileSync(
  842. path.join(tempDir, 'm.cpp'),
  843. `class Calculator { public: Calculator(int seed) {} int add(int a, int b){ return a+b; } };
  844. class Widget { public: Widget(int a, int b) {} };
  845. int runStack(int a, int b) { Calculator calc(0); return calc.add(a, b); }
  846. int runBrace() { Widget w{1, 2}; return 0; }
  847. int runHeap(int a, int b) { Calculator* c = new Calculator(0); return c->add(a, b); }
  848. void noise() { int x(5); int y{6}; Calculator deferred; }
  849. `
  850. );
  851. cg = await CodeGraph.init(tempDir, { index: true });
  852. const fn = (name: string) => cg.getNodesByKind('function').find((n) => n.name === name)!;
  853. const instTargets = (name: string) =>
  854. cg
  855. .getOutgoingEdges(fn(name).id)
  856. .filter((e) => e.kind === 'instantiates')
  857. .map((e) => cg.getNode(e.target)!);
  858. // Direct-init (the issue) and brace-init both instantiate, targeting the
  859. // CLASS node — not the same-named constructor method.
  860. const stack = instTargets('runStack');
  861. expect(stack.map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  862. expect(instTargets('runBrace').map((n) => `${n.kind}:${n.name}`)).toContain('class:Widget');
  863. // Heap still works (regression guard).
  864. expect(instTargets('runHeap').map((n) => `${n.kind}:${n.name}`)).toContain('class:Calculator');
  865. // Primitives (`int x(0)`/`int y{6}`) and bare default construction
  866. // (`Calculator deferred;`) must NOT mint an instantiates edge.
  867. expect(instTargets('noise')).toHaveLength(0);
  868. });
  869. it('resolves a cross-file static method call to the method, not the class (#825)', async () => {
  870. // `Foo.bar()` where `Foo` is an imported class must link to the static
  871. // method `Foo::bar`, NOT to the class `Foo`. Previously the import
  872. // resolver dropped the `.bar` member and resolved to `Foo`, which the
  873. // calls→instantiates promotion then turned into `run instantiates Foo`,
  874. // leaving the static method with zero callers and a hollow impact radius.
  875. fs.writeFileSync(
  876. path.join(tempDir, 'helpers.ts'),
  877. `export class Foo {\n static bar(x: number) { return x + 1; }\n}\n`
  878. );
  879. fs.writeFileSync(
  880. path.join(tempDir, 'caller.ts'),
  881. `import { Foo } from './helpers';\nexport function run() { return Foo.bar(41); }\n`
  882. );
  883. cg = await CodeGraph.init(tempDir, { index: true });
  884. cg.resolveReferences();
  885. const bar = cg.getNodesByKind('method').find((n) => n.name === 'bar');
  886. const foo = cg.getNodesByKind('class').find((n) => n.name === 'Foo');
  887. const run = cg.getNodesByKind('function').find((n) => n.name === 'run');
  888. expect(bar).toBeDefined();
  889. expect(foo).toBeDefined();
  890. expect(run).toBeDefined();
  891. // `run` is reported as a caller of the static method `Foo.bar`.
  892. const barCallers = cg.getCallers(bar!.id).map((c) => c.node.name);
  893. expect(barCallers).toContain('run');
  894. // And the call is NOT mis-promoted to `run instantiates Foo`.
  895. const outgoing = cg.getOutgoingEdges(run!.id);
  896. expect(
  897. outgoing.filter((e) => e.kind === 'instantiates' && e.target === foo!.id)
  898. ).toHaveLength(0);
  899. // The real edge is a `calls` edge to the method.
  900. expect(
  901. outgoing.some((e) => e.kind === 'calls' && e.target === bar!.id)
  902. ).toBe(true);
  903. });
  904. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  905. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  906. // external (isExternalImport returned true for any non-`/internal/`
  907. // import without `.`-prefix) and resolution fell through to name-match
  908. // with path proximity — recall on cross-package callers was ~<1%.
  909. fs.writeFileSync(
  910. path.join(tempDir, 'go.mod'),
  911. 'module github.com/example/myproject\n\ngo 1.21\n'
  912. );
  913. const pkgaDir = path.join(tempDir, 'pkga');
  914. const pkgbDir = path.join(tempDir, 'pkgb');
  915. const pkgcDir = path.join(tempDir, 'pkgc');
  916. fs.mkdirSync(pkgaDir);
  917. fs.mkdirSync(pkgbDir);
  918. fs.mkdirSync(pkgcDir);
  919. // Same-name exported function in two packages — only the imported one
  920. // should resolve. Exercises disambiguation, not just connectivity.
  921. fs.writeFileSync(
  922. path.join(pkgaDir, 'conv.go'),
  923. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  924. );
  925. fs.writeFileSync(
  926. path.join(pkgbDir, 'conv.go'),
  927. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  928. );
  929. fs.writeFileSync(
  930. path.join(pkgcDir, 'use.go'),
  931. `package pkgc
  932. import "github.com/example/myproject/pkga"
  933. func UsePkga() {
  934. pkga.Convert(5)
  935. }
  936. `
  937. );
  938. cg = await CodeGraph.init(tempDir, { index: true });
  939. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  940. expect(usePkga).toBeDefined();
  941. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  942. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  943. expect(callEdges).toHaveLength(1);
  944. const target = cg.getNode(callEdges[0]!.target);
  945. expect(target?.name).toBe('Convert');
  946. // Critical: the resolver must pick the imported pkga's Convert,
  947. // not pkgb's. With the broken (pre-fix) resolver this lands on
  948. // whichever Convert happens to be cheaper under path proximity.
  949. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  950. });
  951. it('resolves Go aliased imports across packages (#388)', async () => {
  952. fs.writeFileSync(
  953. path.join(tempDir, 'go.mod'),
  954. 'module github.com/example/myproject\n\ngo 1.21\n'
  955. );
  956. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  957. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  958. fs.writeFileSync(
  959. path.join(tempDir, 'pkgb', 'lib.go'),
  960. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  961. );
  962. fs.writeFileSync(
  963. path.join(tempDir, 'pkgd', 'use.go'),
  964. `package pkgd
  965. import (
  966. "fmt"
  967. alias "github.com/example/myproject/pkgb"
  968. )
  969. func UseAliased() {
  970. fmt.Println("hi")
  971. alias.Compute(3)
  972. }
  973. `
  974. );
  975. cg = await CodeGraph.init(tempDir, { index: true });
  976. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  977. expect(useAliased).toBeDefined();
  978. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  979. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  980. expect(calls).toHaveLength(1);
  981. const target = cg.getNode(calls[0]!.target);
  982. expect(target?.name).toBe('Compute');
  983. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  984. });
  985. it('resolves Python module-attribute calls after `from pkg import module` (#578)', async () => {
  986. // Pre-#578, a `module.func()` call where `module` was bound via
  987. // `from pkg import module` dropped its `calls` edge. The file→file import
  988. // edge resolved (resolveModuleImportToFile falls back to a dotted-module
  989. // file lookup for absolute package paths), but resolvePythonModuleMember
  990. // had no such fallback — resolveImportPath returns null for an absolute
  991. // package path like `pkg.module`, so the member never resolved and
  992. // callers/callees/impact on the target came back empty. Same root-cause
  993. // class as the Go cross-package qualified call (#388).
  994. fs.mkdirSync(path.join(tempDir, 'pkg'));
  995. fs.writeFileSync(path.join(tempDir, 'pkg', '__init__.py'), '');
  996. fs.writeFileSync(
  997. path.join(tempDir, 'pkg', 'module.py'),
  998. 'def func():\n return 1\n'
  999. );
  1000. fs.writeFileSync(
  1001. path.join(tempDir, 'main.py'),
  1002. `from pkg import module
  1003. import os
  1004. def caller():
  1005. return module.func()
  1006. def external_caller():
  1007. return os.getcwd()
  1008. `
  1009. );
  1010. cg = await CodeGraph.init(tempDir, { index: true });
  1011. const caller = cg.getNodesByKind('function').filter((n) => n.name === 'caller')[0];
  1012. expect(caller).toBeDefined();
  1013. const calls = cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls');
  1014. // module.func() must resolve to the real function in the submodule file.
  1015. expect(calls).toHaveLength(1);
  1016. const target = cg.getNode(calls[0]!.target);
  1017. expect(target?.name).toBe('func');
  1018. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkg/module.py');
  1019. // The flip side of the fix: an attribute call through a *stdlib* module
  1020. // (`os.getcwd()`) must still create no edge — the fallback only matches
  1021. // real in-repo module files.
  1022. const externalCaller = cg.getNodesByKind('function').filter((n) => n.name === 'external_caller')[0];
  1023. expect(externalCaller).toBeDefined();
  1024. const externalCalls = cg.getOutgoingEdges(externalCaller!.id).filter((e) => e.kind === 'calls');
  1025. expect(externalCalls).toHaveLength(0);
  1026. });
  1027. it('attaches Go methods to their receiver type across files (#583, cross-file half)', async () => {
  1028. // In Go a type's methods are commonly declared in a different file from the
  1029. // `type` declaration (`type Box` in box.go, `func (b *Box) Get()` in
  1030. // box_methods.go). Extraction only attaches the struct→method `contains`
  1031. // edge when the type is in the SAME file (the owner lookup is file-scoped),
  1032. // so a cross-file method was orphaned from its struct — breaking member
  1033. // outlines and any callers/callees/impact traversal through `contains`. A
  1034. // resolution-phase pass now links them within the package (= directory).
  1035. fs.writeFileSync(
  1036. path.join(tempDir, 'box.go'),
  1037. 'package main\n\ntype Box struct{ v int }\n'
  1038. );
  1039. fs.writeFileSync(
  1040. path.join(tempDir, 'box_methods.go'),
  1041. 'package main\n\nfunc (b *Box) Get() int { return b.v }\nfunc (b *Box) Set(x int) { b.v = x }\n'
  1042. );
  1043. // Generic receiver declared cross-file too — exercises #583 half A
  1044. // (generic `*Stack[T]` receiver parsing) and half B (cross-file) together.
  1045. fs.writeFileSync(
  1046. path.join(tempDir, 'stack.go'),
  1047. 'package main\n\ntype Stack[T any] struct {\n\titems []T\n}\n'
  1048. );
  1049. fs.writeFileSync(
  1050. path.join(tempDir, 'stack_push.go'),
  1051. 'package main\n\nfunc (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }\n'
  1052. );
  1053. // A same-named type in another package must NOT capture this package's
  1054. // methods — the link is scoped to the receiver type's own directory.
  1055. fs.mkdirSync(path.join(tempDir, 'other'));
  1056. fs.writeFileSync(
  1057. path.join(tempDir, 'other', 'box.go'),
  1058. 'package other\n\ntype Box struct{ w int }\n'
  1059. );
  1060. cg = await CodeGraph.init(tempDir, { index: true });
  1061. const methodsOf = (typeName: string, file: string): string[] => {
  1062. const node = cg
  1063. .getNodesByKind('struct')
  1064. .find((n) => n.name === typeName && n.filePath.replace(/\\/g, '/') === file);
  1065. expect(node, `${typeName} @ ${file}`).toBeDefined();
  1066. return cg
  1067. .getOutgoingEdges(node!.id)
  1068. .filter((e) => e.kind === 'contains')
  1069. .map((e) => cg.getNode(e.target))
  1070. .filter((n) => !!n && n.kind === 'method')
  1071. .map((n) => n!.name)
  1072. .sort();
  1073. };
  1074. // Cross-file (non-generic) methods now attach to their struct.
  1075. expect(methodsOf('Box', 'box.go')).toEqual(['Get', 'Set']);
  1076. // Generic + cross-file.
  1077. expect(methodsOf('Stack', 'stack.go')).toEqual(['Push']);
  1078. // Cross-package isolation: other/Box defines no methods of its own.
  1079. expect(methodsOf('Box', 'other/box.go')).toEqual([]);
  1080. });
  1081. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  1082. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  1083. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  1084. // because the type_alias had no `stop` node — only the unrelated
  1085. // class did. Now type_alias produces member nodes (property/method),
  1086. // so the camelCase receiver↔type word overlap pulls the call to
  1087. // `RecorderHandle::stop` instead of the look-alike class.
  1088. fs.mkdirSync(path.join(tempDir, 'voice'));
  1089. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  1090. fs.writeFileSync(
  1091. path.join(tempDir, 'voice', 'recorder.ts'),
  1092. `export type RecorderHandle = {
  1093. wavPath: string;
  1094. stop: () => Promise<{ ok: true }>;
  1095. };
  1096. `
  1097. );
  1098. fs.writeFileSync(
  1099. path.join(tempDir, 'voice', 'controller.ts'),
  1100. `import type { RecorderHandle } from "./recorder";
  1101. export async function finaliseRecording(recorder: RecorderHandle) {
  1102. return await recorder.stop();
  1103. }
  1104. `
  1105. );
  1106. fs.writeFileSync(
  1107. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  1108. `export class StdioMcpClient {
  1109. private stopped = false;
  1110. async stop(): Promise<void> { this.stopped = true; }
  1111. }
  1112. `
  1113. );
  1114. cg = await CodeGraph.init(tempDir, { index: true });
  1115. const handleStop = cg
  1116. .getNodesByKind('method')
  1117. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  1118. expect(handleStop).toBeDefined();
  1119. const clientStop = cg
  1120. .getNodesByKind('method')
  1121. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  1122. expect(clientStop).toBeDefined();
  1123. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  1124. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  1125. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  1126. // The class method must have NO callers — voice/'s call must NOT
  1127. // mis-attribute. A non-empty list would mean the false-positive
  1128. // path is still firing.
  1129. expect(clientCallers).toHaveLength(0);
  1130. // Function-typed property surfaces as a `method` node, not `property`,
  1131. // because `stop()` semantics at the call site are method semantics.
  1132. expect(handleStop!.kind).toBe('method');
  1133. });
  1134. it('Java import disambiguates same-name classes across modules (#314)', async () => {
  1135. // Pre-#314 the import resolver had no Java branch at all, so a
  1136. // multi-module Maven repo where `dao/converter/FooConverter` and
  1137. // `service/converter/FooConverter` both export a `convert` method
  1138. // resolved by file-path proximity — picking whichever class was
  1139. // closer to the caller, which is wrong any time the caller lives
  1140. // in an equidistant cross-cutting module.
  1141. const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
  1142. const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
  1143. const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
  1144. fs.mkdirSync(daoDir, { recursive: true });
  1145. fs.mkdirSync(serviceDir, { recursive: true });
  1146. fs.mkdirSync(webDir, { recursive: true });
  1147. fs.writeFileSync(
  1148. path.join(daoDir, 'FooConverter.java'),
  1149. `package com.example.dao.converter;
  1150. public class FooConverter { public String convert(String x) { return "dao:" + x; } }
  1151. `
  1152. );
  1153. fs.writeFileSync(
  1154. path.join(serviceDir, 'FooConverter.java'),
  1155. `package com.example.service.converter;
  1156. public class FooConverter { public String convert(String x) { return "svc:" + x; } }
  1157. `
  1158. );
  1159. // The caller imports the SERVICE version — even though dao is
  1160. // alphabetically/lexically first in the candidate list, the
  1161. // import must trump that order.
  1162. fs.writeFileSync(
  1163. path.join(webDir, 'Handler.java'),
  1164. `package com.example.web;
  1165. import com.example.service.converter.FooConverter;
  1166. public class Handler {
  1167. private FooConverter fooConverter;
  1168. public String use() { return fooConverter.convert("input"); }
  1169. }
  1170. `
  1171. );
  1172. cg = await CodeGraph.init(tempDir, { index: true });
  1173. const use = cg
  1174. .getNodesByKind('method')
  1175. .find((n) => n.qualifiedName === 'com.example.web::Handler::use');
  1176. expect(use).toBeDefined();
  1177. const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
  1178. expect(calls.length).toBeGreaterThanOrEqual(1);
  1179. const target = cg.getNode(calls[0]!.target);
  1180. expect(target?.name).toBe('convert');
  1181. expect(target?.filePath.replace(/\\/g, '/')).toBe(
  1182. 'service/src/main/java/com/example/service/converter/FooConverter.java'
  1183. );
  1184. });
  1185. it('C# extracts references from method/property/field types (#381)', async () => {
  1186. // Pre-#381, every C# project produced ZERO `references` edges:
  1187. // csharp.ts was missing returnField, and the type-leaf walker
  1188. // only recognized TS/Java's `type_identifier` nodes — C# uses
  1189. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  1190. const srcDir = path.join(tempDir, 'src');
  1191. fs.mkdirSync(srcDir, { recursive: true });
  1192. fs.writeFileSync(
  1193. path.join(srcDir, 'Dtos.cs'),
  1194. `namespace MyApp;
  1195. public class SessionInfoDto { public string Id { get; set; } = ""; }
  1196. public class UserDto { public string Name { get; set; } = ""; }
  1197. `
  1198. );
  1199. fs.writeFileSync(
  1200. path.join(srcDir, 'Service.cs'),
  1201. `using System.Threading.Tasks;
  1202. namespace MyApp;
  1203. public class DataExporter
  1204. {
  1205. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  1206. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  1207. public SessionInfoDto Latest { get; set; } = new();
  1208. private UserDto _cached;
  1209. }
  1210. `
  1211. );
  1212. cg = await CodeGraph.init(tempDir, { index: true });
  1213. const sessionDto = cg
  1214. .getNodesByKind('class')
  1215. .find((n) => n.name === 'SessionInfoDto');
  1216. const userDto = cg
  1217. .getNodesByKind('class')
  1218. .find((n) => n.name === 'UserDto');
  1219. expect(sessionDto).toBeDefined();
  1220. expect(userDto).toBeDefined();
  1221. const sessionIncoming = cg
  1222. .getIncomingEdges(sessionDto!.id)
  1223. .filter((e) => e.kind === 'references');
  1224. const userIncoming = cg
  1225. .getIncomingEdges(userDto!.id)
  1226. .filter((e) => e.kind === 'references');
  1227. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  1228. // UserDto: Build param, BuildAsync param, _cached field.
  1229. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  1230. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  1231. });
  1232. it('C# primary-constructor parameters record their type dependencies (#237)', async () => {
  1233. // C# 12 primary constructors declare a type's injected dependencies inline
  1234. // (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache)`). Each
  1235. // ctor parameter's type is recorded as a `references` edge from the class,
  1236. // so a DI-registered contract reached only through a primary ctor is no
  1237. // longer reported as having no dependents.
  1238. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1239. fs.writeFileSync(
  1240. path.join(tempDir, 'src', 'Contracts.cs'),
  1241. `namespace App;
  1242. public interface IRepo { }
  1243. public class ICache { }
  1244. `
  1245. );
  1246. fs.writeFileSync(
  1247. path.join(tempDir, 'src', 'OrderService.cs'),
  1248. `namespace App;
  1249. public sealed class OrderService(IRepo repo, [FromKeyedServices("primary")] ICache cache)
  1250. {
  1251. public void Run() { }
  1252. }
  1253. `
  1254. );
  1255. cg = await CodeGraph.init(tempDir, { index: true });
  1256. const svc = cg.getNodesByKind('class').find((n) => n.name === 'OrderService');
  1257. expect(svc).toBeDefined();
  1258. // The class itself must index (it used to vanish under the old grammar).
  1259. const out = cg.getOutgoingEdges(svc!.id).filter((e) => e.kind === 'references');
  1260. const depNames = out.map((e) => cg.getNode(e.target)?.name);
  1261. expect(depNames).toContain('IRepo');
  1262. expect(depNames).toContain('ICache'); // the keyed-DI ([FromKeyedServices]) dependency
  1263. });
  1264. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  1265. fs.writeFileSync(
  1266. path.join(tempDir, 'go.mod'),
  1267. 'module github.com/example/myproject\n\ngo 1.21\n'
  1268. );
  1269. fs.writeFileSync(
  1270. path.join(tempDir, 'main.go'),
  1271. `package main
  1272. import "fmt"
  1273. func main() {
  1274. fmt.Println("hi")
  1275. }
  1276. `
  1277. );
  1278. cg = await CodeGraph.init(tempDir, { index: true });
  1279. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  1280. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  1281. // No spurious in-project edge — fmt.* must stay unresolved/external.
  1282. expect(calls).toHaveLength(0);
  1283. });
  1284. });
  1285. describe('Same-name method disambiguation (#1079)', () => {
  1286. // resolveMethodOnType picks among several methods that share a
  1287. // `Type::method` qualifiedName. The precedence is:
  1288. // 1. preferredFqn (Java/Kotlin import — target is intentionally in
  1289. // ANOTHER file, #314),
  1290. // 2. the call site's OWN file (language-agnostic, #1079),
  1291. // 3. matches[0] (first-indexed) as a last resort.
  1292. const methodNode = (
  1293. id: string,
  1294. filePath: string,
  1295. language: Node['language'] = 'cpp',
  1296. qualifiedName = 'Logger::log',
  1297. name = 'log',
  1298. ): Node => ({
  1299. id, kind: 'method', name, qualifiedName, filePath, language,
  1300. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  1301. });
  1302. const callRef = (filePath: string, language: Node['language'] = 'cpp'): UnresolvedRef => ({
  1303. fromNodeId: 'caller', referenceName: 'lg.log', referenceKind: 'calls',
  1304. line: 2, column: 0, filePath, language,
  1305. });
  1306. const ctxFor = (candidates: Node[]): ResolutionContext => ({
  1307. getNodesInFile: () => [],
  1308. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1309. getNodesByQualifiedName: () => [],
  1310. getNodesByKind: () => [],
  1311. fileExists: () => false,
  1312. readFile: () => null,
  1313. getProjectRoot: () => '',
  1314. getAllFiles: () => [],
  1315. });
  1316. it('prefers the definition in the call site\'s own file (#1079)', () => {
  1317. // matches[0] is the a/ definition; the call comes from b/, so it must
  1318. // resolve to b/ — not collapse onto the first-indexed match.
  1319. const logA = methodNode('m:a', 'a/svc.cpp');
  1320. const logB = methodNode('m:b', 'b/svc.cpp');
  1321. const result = resolveMethodOnType(
  1322. 'Logger', 'log', callRef('b/svc.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1323. );
  1324. expect(result?.targetNodeId).toBe('m:b');
  1325. });
  1326. it('lets an import FQN pin a cross-file target over the same-file preference (#314)', () => {
  1327. // Java: two `Bar::doIt` in different packages. The import FQN pins the
  1328. // alpha package; even though the call site lives in beta's file, the FQN
  1329. // must win — the same-file preference runs only AFTER preferredFqn.
  1330. const alpha = methodNode('m:alpha', 'com/example/alpha/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1331. const beta = methodNode('m:beta', 'com/example/beta/Bar.java', 'java', 'Bar::doIt', 'doIt');
  1332. const result = resolveMethodOnType(
  1333. 'Bar', 'doIt', callRef('com/example/beta/Bar.java', 'java'),
  1334. ctxFor([alpha, beta]), 0.9, 'instance-method', 'com.example.alpha.Bar',
  1335. );
  1336. expect(result?.targetNodeId).toBe('m:alpha');
  1337. });
  1338. it('falls back to the first match when nothing disambiguates', () => {
  1339. // Call site is a third file: no FQN, no same-file candidate → matches[0].
  1340. const logA = methodNode('m:a', 'a/svc.cpp');
  1341. const logB = methodNode('m:b', 'b/svc.cpp');
  1342. const result = resolveMethodOnType(
  1343. 'Logger', 'log', callRef('c/other.cpp'), ctxFor([logA, logB]), 0.9, 'instance-method',
  1344. );
  1345. expect(result?.targetNodeId).toBe('m:a');
  1346. });
  1347. it('resolves C++ calls end-to-end to same-named classes in different files (#1079)', async () => {
  1348. // The exact repro from the issue: two files, each with its own
  1349. // `Logger::log`. Before the fix both callers pointed at the first def.
  1350. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1351. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1352. fs.writeFileSync(
  1353. path.join(tempDir, 'a', 'svc.cpp'),
  1354. `class Logger { public: void log() { int a = 1; } };\nvoid useA() { Logger lg; lg.log(); }\n`,
  1355. );
  1356. fs.writeFileSync(
  1357. path.join(tempDir, 'b', 'svc.cpp'),
  1358. `class Logger { public: void log() { int b = 2; } };\nvoid useB() { Logger lg; lg.log(); }\n`,
  1359. );
  1360. cg = await CodeGraph.init(tempDir, { index: true });
  1361. cg.resolveReferences();
  1362. const logInDir = (dir: string) =>
  1363. cg.getNodesByKind('method').find(
  1364. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1365. )!;
  1366. const callTargets = (fnName: string) =>
  1367. cg
  1368. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1369. .filter((e) => e.kind === 'calls')
  1370. .map((e) => e.target);
  1371. const logA = logInDir('a');
  1372. const logB = logInDir('b');
  1373. expect(logA).toBeDefined();
  1374. expect(logB).toBeDefined();
  1375. expect(logA.id).not.toBe(logB.id);
  1376. // Each caller resolves to the Logger::log in its OWN file.
  1377. expect(callTargets('useA')).toContain(logA.id);
  1378. expect(callTargets('useB')).toContain(logB.id);
  1379. });
  1380. it('preferCallSiteFile puts same-file candidates first and is otherwise a no-op', () => {
  1381. const a = methodNode('m:a', 'a/svc.cpp');
  1382. const b = methodNode('m:b', 'b/svc.cpp');
  1383. // Same-file first; the rest keep their original order (stable).
  1384. expect(preferCallSiteFile([a, b], 'b/svc.cpp').map((n) => n.id)).toEqual(['m:b', 'm:a']);
  1385. expect(preferCallSiteFile([a, b], 'a/svc.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1386. // No same-file match → unchanged; <2 candidates → returned as-is.
  1387. expect(preferCallSiteFile([a, b], 'c/other.cpp').map((n) => n.id)).toEqual(['m:a', 'm:b']);
  1388. expect(preferCallSiteFile([a], 'z/none.cpp')).toHaveLength(1);
  1389. });
  1390. it('matchByQualifiedName prefers the same-file target when a qualified name is ambiguous (#1079)', () => {
  1391. // Two `Logger::log` definitions; an explicit `Logger::log()` call from b/
  1392. // must resolve to b/'s definition, not the first-indexed one.
  1393. const a = methodNode('m:a', 'a/svc.cpp');
  1394. const b = methodNode('m:b', 'b/svc.cpp');
  1395. const ctx: ResolutionContext = {
  1396. getNodesInFile: () => [],
  1397. getNodesByName: (name) => [a, b].filter((n) => n.name === name),
  1398. getNodesByQualifiedName: (q) => (q === 'Logger::log' ? [a, b] : []),
  1399. getNodesByKind: () => [],
  1400. fileExists: () => false,
  1401. readFile: () => null,
  1402. getProjectRoot: () => '',
  1403. getAllFiles: () => [],
  1404. };
  1405. const ref: UnresolvedRef = {
  1406. fromNodeId: 'caller', referenceName: 'Logger::log', referenceKind: 'calls',
  1407. line: 2, column: 0, filePath: 'b/svc.cpp', language: 'cpp',
  1408. };
  1409. expect(matchByQualifiedName(ref, ctx)?.targetNodeId).toBe('m:b');
  1410. });
  1411. it('resolves a static/class-receiver call to the class in the caller\'s file (#1079)', async () => {
  1412. // `Logger.log()` — the receiver is the class NAME, so this routes through
  1413. // the class-name-receiver strategy (not the C++ instance path). It was
  1414. // file-blind across languages; verified here on TypeScript.
  1415. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1416. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1417. fs.writeFileSync(
  1418. path.join(tempDir, 'a', 'svc.ts'),
  1419. `class Logger { static log() { return 1; } }\nexport function useA() { return Logger.log(); }\n`,
  1420. );
  1421. fs.writeFileSync(
  1422. path.join(tempDir, 'b', 'svc.ts'),
  1423. `class Logger { static log() { return 2; } }\nexport function useB() { return Logger.log(); }\n`,
  1424. );
  1425. cg = await CodeGraph.init(tempDir, { index: true });
  1426. cg.resolveReferences();
  1427. const logInDir = (dir: string) =>
  1428. cg.getNodesByKind('method').find(
  1429. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.ts`),
  1430. )!;
  1431. const callTargets = (fnName: string) =>
  1432. cg
  1433. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1434. .filter((e) => e.kind === 'calls')
  1435. .map((e) => e.target);
  1436. const logA = logInDir('a');
  1437. const logB = logInDir('b');
  1438. expect(logA?.id).not.toBe(logB?.id);
  1439. expect(callTargets('useA')).toContain(logA.id);
  1440. expect(callTargets('useB')).toContain(logB.id);
  1441. });
  1442. it('resolves an explicitly-qualified call to the definition in the caller\'s file (#1079)', async () => {
  1443. // `Logger::log()` with two `Logger::log` definitions routes through the
  1444. // qualified-name strategy, whose partial match previously picked the first.
  1445. fs.mkdirSync(path.join(tempDir, 'a'), { recursive: true });
  1446. fs.mkdirSync(path.join(tempDir, 'b'), { recursive: true });
  1447. fs.writeFileSync(
  1448. path.join(tempDir, 'a', 'svc.cpp'),
  1449. `class Logger { public: static void log() { int a = 1; } };\nvoid useA() { Logger::log(); }\n`,
  1450. );
  1451. fs.writeFileSync(
  1452. path.join(tempDir, 'b', 'svc.cpp'),
  1453. `class Logger { public: static void log() { int b = 2; } };\nvoid useB() { Logger::log(); }\n`,
  1454. );
  1455. cg = await CodeGraph.init(tempDir, { index: true });
  1456. cg.resolveReferences();
  1457. const logInDir = (dir: string) =>
  1458. cg.getNodesByKind('method').find(
  1459. (n) => n.name === 'log' && n.filePath.replace(/\\/g, '/').endsWith(`${dir}/svc.cpp`),
  1460. )!;
  1461. const callTargets = (fnName: string) =>
  1462. cg
  1463. .getOutgoingEdges(cg.getNodesByKind('function').find((n) => n.name === fnName)!.id)
  1464. .filter((e) => e.kind === 'calls')
  1465. .map((e) => e.target);
  1466. const logA = logInDir('a');
  1467. const logB = logInDir('b');
  1468. expect(logA?.id).not.toBe(logB?.id);
  1469. expect(callTargets('useA')).toContain(logA.id);
  1470. expect(callTargets('useB')).toContain(logB.id);
  1471. });
  1472. });
  1473. describe('Local-variable receiver-type inference (#1108)', () => {
  1474. // `lg.log()` where `lg` is a local whose type is inferred from its
  1475. // declaration/initializer. Before this, only C++ resolved these; every
  1476. // other language produced no method edge. Each case is one file with a
  1477. // single Logger + a caller using a local-variable receiver — a correct
  1478. // resolution makes the caller a caller of `log`.
  1479. const cases: Array<{ lang: string; file: string; src: string }> = [
  1480. { lang: 'TypeScript (= new T)', file: 'svc.ts',
  1481. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1482. { lang: 'JavaScript (= new T)', file: 'svc.js',
  1483. src: `class Logger { log() { return 1; } }\nexport function use() { const lg = new Logger(); return lg.log(); }\n` },
  1484. { lang: 'Python (= T())', file: 'svc.py',
  1485. src: `class Logger:\n def log(self):\n return 1\ndef use():\n lg = Logger()\n return lg.log()\n` },
  1486. { lang: 'Java (T x = new T)', file: 'Svc.java',
  1487. src: `class Logger { void log() { int a = 1; } }\nclass Use { void run() { Logger lg = new Logger(); lg.log(); } }\n` },
  1488. { lang: 'C# (var x = new T)', file: 'Svc.cs',
  1489. src: `class Logger { void Log() { int a = 1; } }\nclass Use { void Run() { var lg = new Logger(); lg.Log(); } }\n` },
  1490. { lang: 'Kotlin (val x = T())', file: 'Svc.kt',
  1491. src: `class Logger { fun log(): Int { return 1 } }\nfun use(): Int { val lg = Logger(); return lg.log() }\n` },
  1492. { lang: 'Swift (let x = T())', file: 'svc.swift',
  1493. src: `class Logger { func log() -> Int { return 1 } }\nfunc use() -> Int { let lg = Logger(); return lg.log() }\n` },
  1494. { lang: 'Go (x := T{})', file: 'svc.go',
  1495. src: `package a\ntype Logger struct{}\nfunc (l Logger) Log() int { return 1 }\nfunc Use() int { lg := Logger{}; return lg.Log() }\n` },
  1496. { lang: 'Rust (let x = T{})', file: 'svc.rs',
  1497. 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` },
  1498. { lang: 'Dart (var x = T())', file: 'svc.dart',
  1499. src: `class Logger { int log() { return 1; } }\nint use() { var lg = Logger(); return lg.log(); }\n` },
  1500. { lang: 'PHP ($x = new T)', file: 'svc.php',
  1501. src: `<?php\nclass Logger { function log() { return 1; } }\nfunction useIt() { $lg = new Logger(); return $lg->log(); }\n` },
  1502. { lang: 'Scala (val x = new T)', file: 'Svc.scala',
  1503. src: `class Logger { def log(): Int = 1 }\nobject A { def use(): Int = { val lg = new Logger(); lg.log() } }\n` },
  1504. { lang: 'Ruby (x = T.new)', file: 'svc.rb',
  1505. src: `class Logger\n def log\n 1\n end\nend\ndef use\n lg = Logger.new\n lg.log\nend\n` },
  1506. { lang: 'Lua (x = T.new(); x:log())', file: 'svc.lua',
  1507. 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` },
  1508. { lang: 'Luau (x = T.new(); x:log())', file: 'svc.luau',
  1509. 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` },
  1510. { lang: 'R (x <- T$new(); x$log())', file: 'svc.R',
  1511. src: `Logger <- R6::R6Class("Logger", public = list(log = function() 1))\nuse <- function() { lg <- Logger$new(); lg$log() }\n` },
  1512. { lang: 'Pascal (var x: T; x.Method)', file: 'svc.pas',
  1513. 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` },
  1514. ];
  1515. for (const c of cases) {
  1516. it(`resolves a local-variable method call — ${c.lang}`, async () => {
  1517. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1518. cg = await CodeGraph.init(tempDir, { index: true });
  1519. cg.resolveReferences();
  1520. const logMethod = cg
  1521. .getNodesByKind('method')
  1522. .find((n) => n.name.toLowerCase() === 'log');
  1523. expect(logMethod, `${c.lang}: log method should be indexed`).toBeDefined();
  1524. // The enclosing caller resolves through the local variable to `log`.
  1525. const callers = cg.getCallers(logMethod!.id).map((x) => x.node.name);
  1526. expect(
  1527. callers.length,
  1528. `${c.lang}: log should have a caller (got [${callers.join(', ')}])`,
  1529. ).toBeGreaterThan(0);
  1530. });
  1531. }
  1532. it('Ruby: builds receiver.method and keeps Foo.new as an instantiation', async () => {
  1533. // The Ruby extractor previously took the receiver as the callee and
  1534. // dropped the method name (`lg.log()` -> a call to `lg`). Now it builds
  1535. // `lg.log`, while `Logger.new` must still record an instantiation.
  1536. fs.writeFileSync(
  1537. path.join(tempDir, 'svc.rb'),
  1538. `class Logger\n def log\n 1\n end\nend\ndef run\n lg = Logger.new\n lg.log\nend\n`,
  1539. );
  1540. cg = await CodeGraph.init(tempDir, { index: true });
  1541. cg.resolveReferences();
  1542. const run = cg.getNodesByKind('function').find((n) => n.name === 'run')!;
  1543. const logMethod = cg.getNodesByKind('method').find((n) => n.name === 'log')!;
  1544. const logger = cg.getNodesByKind('class').find((n) => n.name === 'Logger')!;
  1545. const out = cg.getOutgoingEdges(run.id);
  1546. // lg.log resolved to the method (the receiver-type inference kicked in).
  1547. expect(out.some((e) => e.kind === 'calls' && e.target === logMethod.id)).toBe(true);
  1548. // Logger.new is still an instantiation of the class.
  1549. expect(out.some((e) => e.kind === 'instantiates' && e.target === logger.id)).toBe(true);
  1550. });
  1551. it('TypeScript: infers a typed-parameter receiver, disambiguating same-named methods (#1125)', async () => {
  1552. // A typed function parameter used as a receiver — `function use(lg: Logger)`
  1553. // — never matched the old TS/JS pattern (it required a const|let|var
  1554. // prefix), so `lg.log()` fell through to no edge once a second class shared
  1555. // the method name. Two ambiguous classes are load-bearing here: a
  1556. // single-class version resolves via a same-name fallback even without
  1557. // inference, so only the collision proves type inference actually fired.
  1558. fs.writeFileSync(
  1559. path.join(tempDir, 'svc.ts'),
  1560. `class Logger { log() { return 1; } }\n` +
  1561. `class Other { log() { return 2; } }\n` +
  1562. `export function use(lg: Logger) { return lg.log(); }\n` +
  1563. `export function useOther(o: Other) { return o.log(); }\n`,
  1564. );
  1565. cg = await CodeGraph.init(tempDir, { index: true });
  1566. cg.resolveReferences();
  1567. const classes = cg.getNodesByKind('class');
  1568. const logger = classes.find((n) => n.name === 'Logger')!;
  1569. const other = classes.find((n) => n.name === 'Other')!;
  1570. const logs = cg.getNodesByKind('method').filter((n) => n.name === 'log');
  1571. expect(logs.length, 'both log methods should be indexed').toBe(2);
  1572. // Associate each same-named `log` with its class by line containment.
  1573. const inClass = (m: (typeof logs)[number], c: typeof logger) =>
  1574. m.startLine >= c.startLine && m.startLine <= (c.endLine ?? c.startLine);
  1575. const loggerLog = logs.find((m) => inClass(m, logger))!;
  1576. const otherLog = logs.find((m) => inClass(m, other))!;
  1577. expect(loggerLog, "Logger's log").toBeDefined();
  1578. expect(otherLog, "Other's log").toBeDefined();
  1579. const loggerCallers = cg.getCallers(loggerLog.id).map((x) => x.node.name);
  1580. const otherCallers = cg.getCallers(otherLog.id).map((x) => x.node.name);
  1581. // Each typed-param call routes to its OWN class's method, not the other's.
  1582. expect(loggerCallers).toContain('use');
  1583. expect(loggerCallers).not.toContain('useOther');
  1584. expect(otherCallers).toContain('useOther');
  1585. expect(otherCallers).not.toContain('use');
  1586. });
  1587. // The same typed-parameter gap existed in every language whose pattern set
  1588. // only matched keyword-anchored locals (let/var/:=/= new), not the bare
  1589. // parameter form — Rust, Go, Dart, PHP (#1125). Each case: two classes
  1590. // sharing a method name + two functions taking one as a typed param; a
  1591. // correct fix routes each call to its OWN type's method (the collision is
  1592. // load-bearing — a single class resolves via the same-name fallback either
  1593. // way). Method↔type association is by qualifiedName, robust where the method
  1594. // lives outside the type's line range (Rust `impl`, Go method decl).
  1595. const typedParamCases: Array<{
  1596. lang: string; file: string; method: string; callerA: string; callerB: string; src: string;
  1597. }> = [
  1598. { lang: 'Rust (fn f(x: &T))', file: 'svc.rs', method: 'log', callerA: 'use_it', callerB: 'use_other',
  1599. 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` },
  1600. { lang: 'Go (func f(x T))', file: 'svc.go', method: 'Log', callerA: 'UseIt', callerB: 'UseOther',
  1601. 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` },
  1602. { lang: 'Dart (T f(U x))', file: 'svc.dart', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1603. 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` },
  1604. { lang: 'PHP (f(T $x))', file: 'svc.php', method: 'log', callerA: 'useIt', callerB: 'useOther',
  1605. 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` },
  1606. ];
  1607. for (const c of typedParamCases) {
  1608. it(`infers a typed-parameter receiver, disambiguating same-named methods — ${c.lang} (#1125)`, async () => {
  1609. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1610. cg = await CodeGraph.init(tempDir, { index: true });
  1611. cg.resolveReferences();
  1612. const methods = cg.getNodesByKind('method').filter((n) => n.name === c.method);
  1613. expect(methods.length, `${c.lang}: both ${c.method} methods indexed`).toBe(2);
  1614. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1615. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1616. expect(loggerLog, `${c.lang}: Logger's ${c.method}`).toBeDefined();
  1617. expect(otherLog, `${c.lang}: Other's ${c.method}`).toBeDefined();
  1618. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1619. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1620. expect(loggerCallers, `${c.lang}: Logger callers`).toContain(c.callerA);
  1621. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain(c.callerB);
  1622. expect(otherCallers, `${c.lang}: Other callers`).toContain(c.callerB);
  1623. expect(otherCallers, `${c.lang}: Other callers`).not.toContain(c.callerA);
  1624. });
  1625. }
  1626. // Lua/Luau: a PascalCase method call (`lg:Log()`, the Roblox convention)
  1627. // is the identical `receiver:Name` shape as a Luau type annotation, so it
  1628. // self-matched the annotation pattern on the call's own line and inferred
  1629. // "type = Log" (#1124). Two things are load-bearing in these fixtures:
  1630. // the declaration sits on an EARLIER line than the call (on one line,
  1631. // pattern order resolves it — the `.new` pattern wins first), and TWO
  1632. // classes share the method name (a single class resolves via the
  1633. // same-name fallback even when inference misfires). Luau's `useLogger`
  1634. // takes a typed param instead of calling `.new()`, pinning that the
  1635. // gated pattern still matches a genuine annotation.
  1636. const pascalMethodCases: Array<{ lang: string; file: string; src: string }> = [
  1637. { lang: 'Lua', file: 'svc.lua',
  1638. 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` },
  1639. { lang: 'Luau', file: 'svc.luau',
  1640. 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` },
  1641. ];
  1642. for (const c of pascalMethodCases) {
  1643. it(`resolves a PascalCase method call without self-matching the annotation pattern — ${c.lang} (#1124)`, async () => {
  1644. fs.writeFileSync(path.join(tempDir, c.file), c.src);
  1645. cg = await CodeGraph.init(tempDir, { index: true });
  1646. cg.resolveReferences();
  1647. const methods = cg.getNodesByKind('method').filter((n) => n.name === 'Log');
  1648. expect(methods.length, `${c.lang}: both Log methods indexed`).toBe(2);
  1649. const loggerLog = methods.find((m) => /Logger/.test(m.qualifiedName ?? ''));
  1650. const otherLog = methods.find((m) => /Other/.test(m.qualifiedName ?? ''));
  1651. expect(loggerLog, `${c.lang}: Logger's Log`).toBeDefined();
  1652. expect(otherLog, `${c.lang}: Other's Log`).toBeDefined();
  1653. const loggerCallers = cg.getCallers(loggerLog!.id).map((x) => x.node.name);
  1654. const otherCallers = cg.getCallers(otherLog!.id).map((x) => x.node.name);
  1655. expect(loggerCallers, `${c.lang}: Logger callers`).toContain('useLogger');
  1656. expect(loggerCallers, `${c.lang}: Logger callers`).not.toContain('useOther');
  1657. expect(otherCallers, `${c.lang}: Other callers`).toContain('useOther');
  1658. expect(otherCallers, `${c.lang}: Other callers`).not.toContain('useLogger');
  1659. });
  1660. }
  1661. });
  1662. describe('Name Matcher: kind bias for new ref kinds', () => {
  1663. const baseContext = (candidates: Node[]): ResolutionContext => ({
  1664. getNodesInFile: () => [],
  1665. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1666. getNodesByQualifiedName: () => [],
  1667. getNodesByKind: () => [],
  1668. fileExists: () => true,
  1669. readFile: () => null,
  1670. getProjectRoot: () => '/test',
  1671. getAllFiles: () => [],
  1672. getNodesByLowerName: () => [],
  1673. getImportMappings: () => [],
  1674. });
  1675. it('prefers a class candidate over a function for `instantiates` refs', () => {
  1676. // A class and a function share a name across the codebase.
  1677. // Without the kind bias, the function (which gets the +25 `calls`
  1678. // bonus historically applied to all candidates of that kind) would
  1679. // win. Now the instantiates branch reverses it.
  1680. const fn: Node = {
  1681. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  1682. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  1683. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1684. };
  1685. const cls: Node = {
  1686. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  1687. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  1688. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1689. };
  1690. const ref = {
  1691. fromNodeId: 'func:main.ts:bootstrap:1',
  1692. referenceName: 'Logger',
  1693. referenceKind: 'instantiates' as const,
  1694. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  1695. };
  1696. const result = matchReference(ref, baseContext([fn, cls]));
  1697. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  1698. });
  1699. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  1700. const variable: Node = {
  1701. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  1702. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  1703. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1704. };
  1705. const decorator: Node = {
  1706. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  1707. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  1708. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1709. };
  1710. const ref = {
  1711. fromNodeId: 'class:svc.ts:UserService:1',
  1712. referenceName: 'Inject',
  1713. referenceKind: 'decorates' as const,
  1714. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  1715. };
  1716. const result = matchReference(ref, baseContext([variable, decorator]));
  1717. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  1718. });
  1719. });
  1720. describe('tsconfig path aliases', () => {
  1721. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  1722. // Two same-named exports in different directories. Without alias
  1723. // resolution, name-matcher would pick whichever it finds first;
  1724. // with alias resolution, the import path uniquely picks one.
  1725. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1726. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  1727. fs.writeFileSync(
  1728. path.join(tempDir, 'src/utils/format.ts'),
  1729. `export function pickMe(): number { return 1; }\n`
  1730. );
  1731. fs.writeFileSync(
  1732. path.join(tempDir, 'src/legacy/format.ts'),
  1733. `export function pickMe(): number { return 99; }\n`
  1734. );
  1735. fs.writeFileSync(
  1736. path.join(tempDir, 'src/main.ts'),
  1737. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  1738. );
  1739. fs.writeFileSync(
  1740. path.join(tempDir, 'tsconfig.json'),
  1741. JSON.stringify({
  1742. compilerOptions: {
  1743. baseUrl: './src',
  1744. paths: { '@utils/*': ['utils/*'] },
  1745. },
  1746. })
  1747. );
  1748. cg = await CodeGraph.init(tempDir, { index: true });
  1749. cg.resolveReferences();
  1750. // The two pickMe nodes live in different files. The aliased
  1751. // import should attach the call edge to the @utils-mapped one,
  1752. // not the legacy duplicate.
  1753. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  1754. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  1755. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  1756. expect(utilsNode).toBeDefined();
  1757. expect(legacyNode).toBeDefined();
  1758. const utilsCallers = cg.getCallers(utilsNode!.id);
  1759. const legacyCallers = cg.getCallers(legacyNode!.id);
  1760. expect(utilsCallers.length).toBeGreaterThan(0);
  1761. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1762. // The legacy node should NOT have a caller from src/main.ts —
  1763. // the alias correctly picked the utils version.
  1764. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  1765. });
  1766. it('falls back gracefully when tsconfig is absent', async () => {
  1767. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1768. fs.writeFileSync(
  1769. path.join(tempDir, 'src/a.ts'),
  1770. `export function aFn(): void {}\n`
  1771. );
  1772. fs.writeFileSync(
  1773. path.join(tempDir, 'src/b.ts'),
  1774. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  1775. );
  1776. cg = await CodeGraph.init(tempDir, { index: true });
  1777. // No tsconfig present — index should still complete and the
  1778. // relative-import-based call edge should be created.
  1779. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  1780. expect(aFn).toBeDefined();
  1781. const callers = cg.getCallers(aFn!.id);
  1782. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  1783. });
  1784. });
  1785. describe('re-export chain following', () => {
  1786. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  1787. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  1788. // Without chain following, `signIn` resolves to nothing because
  1789. // none of the barrel files declare it directly.
  1790. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  1791. fs.writeFileSync(
  1792. path.join(tempDir, 'src/services/auth.ts'),
  1793. `export function signIn(): void {}\n`
  1794. );
  1795. fs.writeFileSync(
  1796. path.join(tempDir, 'src/services/index.ts'),
  1797. `export { signIn } from './auth';\n`
  1798. );
  1799. fs.writeFileSync(
  1800. path.join(tempDir, 'src/all.ts'),
  1801. `export * from './services/index';\n`
  1802. );
  1803. fs.writeFileSync(
  1804. path.join(tempDir, 'src/main.ts'),
  1805. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  1806. );
  1807. cg = await CodeGraph.init(tempDir, { index: true });
  1808. cg.resolveReferences();
  1809. const signInNode = cg
  1810. .getNodesByKind('function')
  1811. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  1812. expect(signInNode).toBeDefined();
  1813. const callers = cg.getCallers(signInNode!.id);
  1814. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1815. });
  1816. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  1817. // The chase has to look up `foo` in the upstream module even
  1818. // though the importer asked for `bar` — exercises the rename
  1819. // branch of findExportedSymbol.
  1820. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1821. fs.writeFileSync(
  1822. path.join(tempDir, 'src/auth.ts'),
  1823. `export function signIn(): void {}\n`
  1824. );
  1825. fs.writeFileSync(
  1826. path.join(tempDir, 'src/index.ts'),
  1827. `export { signIn as login } from './auth';\n`
  1828. );
  1829. fs.writeFileSync(
  1830. path.join(tempDir, 'src/main.ts'),
  1831. `import { login } from './index';\nexport function go(): void { login(); }\n`
  1832. );
  1833. cg = await CodeGraph.init(tempDir, { index: true });
  1834. cg.resolveReferences();
  1835. const signInNode = cg
  1836. .getNodesByKind('function')
  1837. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  1838. expect(signInNode).toBeDefined();
  1839. const callers = cg.getCallers(signInNode!.id);
  1840. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1841. });
  1842. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  1843. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  1844. // .svelte component (extracted as kind 'component', the default
  1845. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  1846. // component's real name (`RealButton`) so the name-matcher fallback
  1847. // can't coincidentally connect them — the only path to the edge is
  1848. // the import-chase, which must match a `component` (not just
  1849. // function/class) for the default export. Otherwise the
  1850. // consumer↔component edge is never created and `callers` returns a
  1851. // false 0.
  1852. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  1853. fs.writeFileSync(
  1854. path.join(tempDir, 'src/lib/RealButton.svelte'),
  1855. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1856. );
  1857. fs.writeFileSync(
  1858. path.join(tempDir, 'src/lib/index.ts'),
  1859. `export { default as Foo } from './RealButton.svelte';\n`
  1860. );
  1861. fs.writeFileSync(
  1862. path.join(tempDir, 'src/Bar.svelte'),
  1863. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  1864. );
  1865. cg = await CodeGraph.init(tempDir, { index: true });
  1866. cg.resolveReferences();
  1867. const fooNode = cg
  1868. .getNodesByKind('component')
  1869. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  1870. expect(fooNode).toBeDefined();
  1871. const callers = cg.getCallers(fooNode!.id);
  1872. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  1873. });
  1874. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  1875. // The canonical Astro shape: a page imports a layout/component in
  1876. // frontmatter and uses it as a template tag; the component's template
  1877. // calls an imported .ts util. Both hops must produce graph edges or
  1878. // an Astro project is invisible to callers/impact.
  1879. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  1880. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1881. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  1882. fs.writeFileSync(
  1883. path.join(tempDir, 'src/utils/format.ts'),
  1884. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  1885. );
  1886. fs.writeFileSync(
  1887. path.join(tempDir, 'src/components/PostCard.astro'),
  1888. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  1889. );
  1890. fs.writeFileSync(
  1891. path.join(tempDir, 'src/pages/index.astro'),
  1892. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  1893. );
  1894. cg = await CodeGraph.init(tempDir, { index: true });
  1895. cg.resolveReferences();
  1896. // Hop 1: page → component (template tag through the frontmatter import)
  1897. const cardNode = cg
  1898. .getNodesByKind('component')
  1899. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  1900. expect(cardNode).toBeDefined();
  1901. const cardCallers = cg.getCallers(cardNode!.id);
  1902. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  1903. // Hop 2: component template call → .ts util
  1904. const fmtNode = cg
  1905. .getNodesByKind('function')
  1906. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  1907. expect(fmtNode).toBeDefined();
  1908. const fmtCallers = cg.getCallers(fmtNode!.id);
  1909. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  1910. });
  1911. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  1912. // `import { helper } from '.'` (or './') must map to the
  1913. // directory's index.ts before the re-export chase can run. The
  1914. // barrel renames `realHelper` → `helper` so the name-matcher can't
  1915. // mask a path-resolution failure: only the bare-dir resolution +
  1916. // rename chase can connect the edge.
  1917. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1918. fs.writeFileSync(
  1919. path.join(tempDir, 'src/util.ts'),
  1920. `export function realHelper(): void {}\n`
  1921. );
  1922. fs.writeFileSync(
  1923. path.join(tempDir, 'src/index.ts'),
  1924. `export { realHelper as helper } from './util';\n`
  1925. );
  1926. fs.writeFileSync(
  1927. path.join(tempDir, 'src/main.ts'),
  1928. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  1929. );
  1930. fs.writeFileSync(
  1931. path.join(tempDir, 'src/main2.ts'),
  1932. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  1933. );
  1934. cg = await CodeGraph.init(tempDir, { index: true });
  1935. cg.resolveReferences();
  1936. const helperNode = cg
  1937. .getNodesByKind('function')
  1938. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  1939. expect(helperNode).toBeDefined();
  1940. const callers = cg.getCallers(helperNode!.id);
  1941. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1942. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  1943. });
  1944. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  1945. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  1946. // `widgets/` subdir index, which re-exports a .svelte component.
  1947. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  1948. // only workspace-package resolution can connect the edge.
  1949. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  1950. fs.writeFileSync(
  1951. path.join(tempDir, 'package.json'),
  1952. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  1953. );
  1954. fs.writeFileSync(
  1955. path.join(tempDir, 'packages/ui/package.json'),
  1956. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  1957. );
  1958. fs.writeFileSync(
  1959. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  1960. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1961. );
  1962. fs.writeFileSync(
  1963. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  1964. `export { default as Thing } from './Widget.svelte';\n`
  1965. );
  1966. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  1967. fs.writeFileSync(
  1968. path.join(tempDir, 'app/App.svelte'),
  1969. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  1970. );
  1971. cg = await CodeGraph.init(tempDir, { index: true });
  1972. cg.resolveReferences();
  1973. const buttonNode = cg
  1974. .getNodesByKind('component')
  1975. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  1976. expect(buttonNode).toBeDefined();
  1977. const callers = cg.getCallers(buttonNode!.id);
  1978. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  1979. });
  1980. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  1981. // The same import-resolution gaps (no SFC import mappings, no SFC
  1982. // extension list, barrel parsed in the consumer's language) broke
  1983. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  1984. // The barrel renames `realRun` → `run` so only the import-chase (not
  1985. // the name-matcher) can connect the call.
  1986. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1987. fs.writeFileSync(
  1988. path.join(tempDir, 'src/util.ts'),
  1989. `export function realRun(): void {}\n`
  1990. );
  1991. fs.writeFileSync(
  1992. path.join(tempDir, 'src/index.ts'),
  1993. `export { realRun as run } from './util';\n`
  1994. );
  1995. fs.writeFileSync(
  1996. path.join(tempDir, 'src/App.vue'),
  1997. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  1998. );
  1999. cg = await CodeGraph.init(tempDir, { index: true });
  2000. cg.resolveReferences();
  2001. const runNode = cg
  2002. .getNodesByKind('function')
  2003. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  2004. expect(runNode).toBeDefined();
  2005. const callers = cg.getCallers(runNode!.id);
  2006. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2007. });
  2008. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  2009. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  2010. // component re-exported under an alias (`Thing`) that differs from its
  2011. // real name (`Widget`), and the consumer uses it ONLY in markup
  2012. // (`<Thing />`). Requires both the new template-tag extraction AND the
  2013. // barrel default-export chase to connect the edge.
  2014. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  2015. fs.writeFileSync(
  2016. path.join(tempDir, 'src/lib/Widget.vue'),
  2017. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  2018. );
  2019. fs.writeFileSync(
  2020. path.join(tempDir, 'src/lib/index.ts'),
  2021. `export { default as Thing } from './Widget.vue';\n`
  2022. );
  2023. fs.writeFileSync(
  2024. path.join(tempDir, 'src/App.vue'),
  2025. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  2026. );
  2027. cg = await CodeGraph.init(tempDir, { index: true });
  2028. cg.resolveReferences();
  2029. const widgetNode = cg
  2030. .getNodesByKind('component')
  2031. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  2032. expect(widgetNode).toBeDefined();
  2033. const callers = cg.getCallers(widgetNode!.id);
  2034. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  2035. });
  2036. });
  2037. describe('C/C++ Import Resolution', () => {
  2038. afterEach(() => {
  2039. clearCppIncludeDirCache();
  2040. });
  2041. it('should resolve C include to header in same directory', () => {
  2042. const context: ResolutionContext = {
  2043. getNodesInFile: () => [],
  2044. getNodesByName: () => [],
  2045. getNodesByQualifiedName: () => [],
  2046. getNodesByKind: () => [],
  2047. fileExists: (p) => p === 'utils.h',
  2048. readFile: () => null,
  2049. getProjectRoot: () => '',
  2050. getAllFiles: () => ['utils.h', 'main.c'],
  2051. };
  2052. const result = resolveImportPath(
  2053. 'utils.h',
  2054. 'main.c',
  2055. 'c',
  2056. context
  2057. );
  2058. expect(result).toBe('utils.h');
  2059. });
  2060. it('should resolve C++ include with .hpp extension', () => {
  2061. const context: ResolutionContext = {
  2062. getNodesInFile: () => [],
  2063. getNodesByName: () => [],
  2064. getNodesByQualifiedName: () => [],
  2065. getNodesByKind: () => [],
  2066. fileExists: (p) => p === 'include/myclass.hpp',
  2067. readFile: () => null,
  2068. getProjectRoot: () => '',
  2069. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2070. getCppIncludeDirs: () => ['include'],
  2071. };
  2072. const result = resolveImportPath(
  2073. 'myclass.hpp',
  2074. 'src/main.cpp',
  2075. 'cpp',
  2076. context
  2077. );
  2078. expect(result).toBe('include/myclass.hpp');
  2079. });
  2080. it('should resolve include with subdirectory path', () => {
  2081. const context: ResolutionContext = {
  2082. getNodesInFile: () => [],
  2083. getNodesByName: () => [],
  2084. getNodesByQualifiedName: () => [],
  2085. getNodesByKind: () => [],
  2086. fileExists: (p) => p === 'utils/helpers.h',
  2087. readFile: () => null,
  2088. getProjectRoot: () => '',
  2089. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  2090. };
  2091. const result = resolveImportPath(
  2092. 'utils/helpers.h',
  2093. 'main.c',
  2094. 'c',
  2095. context
  2096. );
  2097. expect(result).toBe('utils/helpers.h');
  2098. });
  2099. it('should resolve include via include directories', () => {
  2100. const context: ResolutionContext = {
  2101. getNodesInFile: () => [],
  2102. getNodesByName: () => [],
  2103. getNodesByQualifiedName: () => [],
  2104. getNodesByKind: () => [],
  2105. fileExists: (p) => p === 'include/myheader.h',
  2106. readFile: () => null,
  2107. getProjectRoot: () => '',
  2108. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  2109. getCppIncludeDirs: () => ['include'],
  2110. };
  2111. const result = resolveImportPath(
  2112. 'myheader.h',
  2113. 'src/main.cpp',
  2114. 'cpp',
  2115. context
  2116. );
  2117. expect(result).toBe('include/myheader.h');
  2118. });
  2119. it('should resolve include trying multiple extensions', () => {
  2120. const context: ResolutionContext = {
  2121. getNodesInFile: () => [],
  2122. getNodesByName: () => [],
  2123. getNodesByQualifiedName: () => [],
  2124. getNodesByKind: () => [],
  2125. // myclass.h does not exist, but myclass.hpp does
  2126. fileExists: (p) => p === 'include/myclass.hpp',
  2127. readFile: () => null,
  2128. getProjectRoot: () => '',
  2129. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2130. getCppIncludeDirs: () => ['include'],
  2131. };
  2132. const result = resolveImportPath(
  2133. 'myclass',
  2134. 'src/main.cpp',
  2135. 'cpp',
  2136. context
  2137. );
  2138. expect(result).toBe('include/myclass.hpp');
  2139. });
  2140. it('should return null for system headers', () => {
  2141. const context: ResolutionContext = {
  2142. getNodesInFile: () => [],
  2143. getNodesByName: () => [],
  2144. getNodesByQualifiedName: () => [],
  2145. getNodesByKind: () => [],
  2146. fileExists: () => true,
  2147. readFile: () => null,
  2148. getProjectRoot: () => '',
  2149. getAllFiles: () => [],
  2150. };
  2151. // C standard library header
  2152. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  2153. // C++ standard library header
  2154. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  2155. // C++ C-wrapper header
  2156. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  2157. });
  2158. it('should return null for single-component third-party paths that cannot be resolved', () => {
  2159. const context: ResolutionContext = {
  2160. getNodesInFile: () => [],
  2161. getNodesByName: () => [],
  2162. getNodesByQualifiedName: () => [],
  2163. getNodesByKind: () => [],
  2164. fileExists: () => false,
  2165. readFile: () => null,
  2166. getProjectRoot: () => '',
  2167. getAllFiles: () => [],
  2168. getCppIncludeDirs: () => [],
  2169. };
  2170. // Third-party bare header without path — not resolvable, returns null
  2171. const result = resolveImportPath(
  2172. 'openssl/ssl.h',
  2173. 'main.cpp',
  2174. 'cpp',
  2175. context
  2176. );
  2177. expect(result).toBeNull();
  2178. });
  2179. it('should not filter project headers with path separators', () => {
  2180. const context: ResolutionContext = {
  2181. getNodesInFile: () => [],
  2182. getNodesByName: () => [],
  2183. getNodesByQualifiedName: () => [],
  2184. getNodesByKind: () => [],
  2185. fileExists: (p) => p === 'mylib/utils.h',
  2186. readFile: () => null,
  2187. getProjectRoot: () => '',
  2188. getAllFiles: () => ['mylib/utils.h'],
  2189. };
  2190. // Path with separator should NOT be filtered as external
  2191. const result = resolveImportPath(
  2192. 'mylib/utils.h',
  2193. 'main.c',
  2194. 'c',
  2195. context
  2196. );
  2197. expect(result).toBe('mylib/utils.h');
  2198. });
  2199. it('should extract C/C++ import mappings from #include directives', () => {
  2200. const code = `#include <iostream>
  2201. #include "myheader.h"
  2202. #include "utils/helpers.hpp"`;
  2203. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  2204. expect(mappings.length).toBe(3);
  2205. expect(mappings[0]).toEqual({
  2206. localName: 'iostream',
  2207. exportedName: '*',
  2208. source: 'iostream',
  2209. isDefault: false,
  2210. isNamespace: true,
  2211. });
  2212. expect(mappings[1]).toEqual({
  2213. localName: 'myheader',
  2214. exportedName: '*',
  2215. source: 'myheader.h',
  2216. isDefault: false,
  2217. isNamespace: true,
  2218. });
  2219. expect(mappings[2]).toEqual({
  2220. localName: 'helpers',
  2221. exportedName: '*',
  2222. source: 'utils/helpers.hpp',
  2223. isDefault: false,
  2224. isNamespace: true,
  2225. });
  2226. });
  2227. it('should discover include directories from compile_commands.json', () => {
  2228. // Create a temp project with compile_commands.json
  2229. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2230. try {
  2231. const compileDb = [
  2232. {
  2233. directory: tempProject,
  2234. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  2235. file: 'src/main.cpp',
  2236. },
  2237. ];
  2238. fs.writeFileSync(
  2239. path.join(tempProject, 'compile_commands.json'),
  2240. JSON.stringify(compileDb)
  2241. );
  2242. // Create the include dirs so they exist
  2243. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2244. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  2245. clearCppIncludeDirCache();
  2246. const dirs = loadCppIncludeDirs(tempProject);
  2247. // Should find include and src/lib (relative to project root)
  2248. // /usr/include is absolute and outside project, should be excluded
  2249. expect(dirs).toContain('include');
  2250. expect(dirs).toContain('src/lib');
  2251. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  2252. } finally {
  2253. fs.rmSync(tempProject, { recursive: true });
  2254. }
  2255. });
  2256. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  2257. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2258. try {
  2259. // Create include/ and src/ directories with headers
  2260. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2261. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  2262. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2263. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  2264. // Create a directory without headers — should not be included
  2265. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  2266. clearCppIncludeDirCache();
  2267. const dirs = loadCppIncludeDirs(tempProject);
  2268. expect(dirs).toContain('include');
  2269. expect(dirs).toContain('src');
  2270. expect(dirs).not.toContain('docs');
  2271. } finally {
  2272. fs.rmSync(tempProject, { recursive: true });
  2273. }
  2274. });
  2275. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  2276. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  2277. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  2278. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  2279. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  2280. // than missing real resolutions. The test pins this so a later
  2281. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  2282. // trade-off explicitly.
  2283. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  2284. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2285. try {
  2286. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  2287. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  2288. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  2289. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  2290. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  2291. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  2292. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  2293. clearCppIncludeDirCache();
  2294. const dirs = loadCppIncludeDirs(tempProject);
  2295. // Both included — Obj-C dirs are intentionally allowed.
  2296. expect(dirs).toContain('cppmod');
  2297. expect(dirs).toContain('iosmod');
  2298. } finally {
  2299. fs.rmSync(tempProject, { recursive: true });
  2300. }
  2301. });
  2302. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  2303. // in the actual indexing pipeline (not just a phantom file→import-node
  2304. // edge). This pins the include-dir resolution path so the headline PR
  2305. // feature can't silently regress to a no-op in the indexing flow.
  2306. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  2307. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  2308. try {
  2309. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2310. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2311. fs.writeFileSync(
  2312. path.join(tempProject, 'include', 'utils.h'),
  2313. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  2314. );
  2315. fs.writeFileSync(
  2316. path.join(tempProject, 'src', 'main.cpp'),
  2317. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  2318. );
  2319. clearCppIncludeDirCache();
  2320. cg = await CodeGraph.init(tempProject, { index: true });
  2321. // Sanity: file nodes exist for the header and the cpp.
  2322. const allFiles = cg.getStats();
  2323. expect(allFiles.fileCount).toBe(2);
  2324. // The `#include "utils.h"` edge should target the real
  2325. // `include/utils.h` file node — not a floating `import` node
  2326. // living inside main.cpp.
  2327. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2328. const rows = db.getDb().prepare(`
  2329. select dst.kind as dstKind, dst.file_path as dstPath
  2330. from edges e
  2331. join nodes src on e.source = src.id
  2332. join nodes dst on e.target = dst.id
  2333. where e.kind = 'imports'
  2334. and src.kind = 'file'
  2335. and src.file_path = 'src/main.cpp'
  2336. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2337. const resolvedToHeader = rows.find(
  2338. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  2339. );
  2340. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  2341. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  2342. const stdlibFile = rows.find(
  2343. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  2344. );
  2345. expect(stdlibFile).toBeUndefined();
  2346. } finally {
  2347. fs.rmSync(tempProject, { recursive: true, force: true });
  2348. }
  2349. });
  2350. });
  2351. describe('C++ templated base-class inheritance (#1043)', () => {
  2352. // A class deriving from a TEMPLATE — `class D : public Base<int>` (or a CRTP
  2353. // `class W : public CRTPBase<W>`, or a qualified `class Q : public ns::Tpl<int>`)
  2354. // recorded its base as the full instantiation text (`Base<int>`), which never
  2355. // name-matched the template, indexed as the bare node `Base`. The `<…>` args
  2356. // are now stripped so the `extends` edge resolves end-to-end.
  2357. it('resolves an extends edge to a templated base (plain, CRTP, struct, multi-base)', async () => {
  2358. fs.writeFileSync(
  2359. path.join(tempDir, 'lib.hpp'),
  2360. `#pragma once
  2361. template<typename T> class Base { public: void foo(); };
  2362. template<typename Derived> class CRTPBase {};
  2363. class Plain {};
  2364. class Widget : public Base<int> {}; // plain template base
  2365. class App : public CRTPBase<App> {}; // CRTP (curiously-recurring)
  2366. struct Node : public Base<double> {}; // struct inheriting a template
  2367. class Both : public Base<char>, public Plain {}; // templated + plain in one clause
  2368. `
  2369. );
  2370. cg = await CodeGraph.init(tempDir, { index: true });
  2371. const db = DatabaseConnection.open(path.join(tempDir, '.codegraph', 'codegraph.db'));
  2372. const edges = db
  2373. .getDb()
  2374. .prepare(
  2375. `select src.name as fromName, dst.name as toName
  2376. from edges e
  2377. join nodes src on e.source = src.id
  2378. join nodes dst on e.target = dst.id
  2379. where e.kind = 'extends'`
  2380. )
  2381. .all() as Array<{ fromName: string; toName: string }>;
  2382. const has = (from: string, to: string) =>
  2383. edges.some((r) => r.fromName === from && r.toName === to);
  2384. // Every templated base now resolves to the bare template node.
  2385. expect(has('Widget', 'Base'), 'Widget : Base<int>').toBe(true);
  2386. expect(has('App', 'CRTPBase'), 'App : CRTPBase<App> (CRTP)').toBe(true);
  2387. expect(has('Node', 'Base'), 'struct Node : Base<double>').toBe(true);
  2388. // A mixed clause resolves BOTH the templated and the plain base.
  2389. expect(has('Both', 'Base'), 'Both : Base<char>').toBe(true);
  2390. expect(has('Both', 'Plain'), 'Both : Plain (non-templated, regression guard)').toBe(true);
  2391. });
  2392. });
  2393. describe('PHP Include Resolution', () => {
  2394. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  2395. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  2396. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  2397. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  2398. });
  2399. // include paths: contain a slash or a file extension
  2400. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  2401. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  2402. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  2403. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  2404. // so they must NOT be treated as includes (would mis-connect to a
  2405. // same-named Closure.php / Bar.php file).
  2406. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  2407. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  2408. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  2409. // scoped to PHP imports only
  2410. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  2411. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  2412. });
  2413. it('resolves require_once to a file→file imports edge (#660)', async () => {
  2414. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  2415. try {
  2416. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2417. fs.writeFileSync(
  2418. path.join(tempProject, 'src', 'lib.php'),
  2419. `<?php\nfunction greet() { return "hi"; }\n`
  2420. );
  2421. fs.writeFileSync(
  2422. path.join(tempProject, 'src', 'page.php'),
  2423. `<?php\nrequire_once("lib.php");\necho greet();\n`
  2424. );
  2425. cg = await CodeGraph.init(tempProject, { index: true });
  2426. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  2427. // to the real src/lib.php file node — a file→file `imports` edge, so
  2428. // callers(lib.php) now includes page.php.
  2429. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2430. const rows = db.getDb().prepare(`
  2431. select dst.kind as dstKind, dst.file_path as dstPath
  2432. from edges e
  2433. join nodes src on e.source = src.id
  2434. join nodes dst on e.target = dst.id
  2435. where e.kind = 'imports'
  2436. and src.kind = 'file'
  2437. and src.file_path = 'src/page.php'
  2438. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2439. const resolved = rows.find(
  2440. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  2441. );
  2442. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  2443. } finally {
  2444. fs.rmSync(tempProject, { recursive: true, force: true });
  2445. }
  2446. });
  2447. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  2448. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  2449. try {
  2450. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  2451. fs.writeFileSync(
  2452. path.join(tempProject, 'inc', 'db.php'),
  2453. `<?php\nfunction query() { return 1; }\n`
  2454. );
  2455. fs.writeFileSync(
  2456. path.join(tempProject, 'index.php'),
  2457. `<?php\nrequire "inc/db.php";\nquery();\n`
  2458. );
  2459. cg = await CodeGraph.init(tempProject, { index: true });
  2460. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2461. const rows = db.getDb().prepare(`
  2462. select dst.kind as dstKind, dst.file_path as dstPath
  2463. from edges e
  2464. join nodes src on e.source = src.id
  2465. join nodes dst on e.target = dst.id
  2466. where e.kind = 'imports'
  2467. and src.kind = 'file'
  2468. and src.file_path = 'index.php'
  2469. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2470. expect(
  2471. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  2472. 'index.php → inc/db.php imports edge missing'
  2473. ).toBeDefined();
  2474. } finally {
  2475. fs.rmSync(tempProject, { recursive: true, force: true });
  2476. }
  2477. });
  2478. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  2479. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  2480. try {
  2481. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  2482. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  2483. // but is unrelated — no edge should be created (a wrong edge is worse
  2484. // than a missing one).
  2485. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  2486. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  2487. fs.writeFileSync(
  2488. path.join(tempProject, 'lib', 'inc', 'db.php'),
  2489. `<?php\nfunction unrelated() {}\n`
  2490. );
  2491. fs.writeFileSync(
  2492. path.join(tempProject, 'app', 'page.php'),
  2493. `<?php\nrequire "inc/db.php";\n`
  2494. );
  2495. cg = await CodeGraph.init(tempProject, { index: true });
  2496. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2497. const rows = db.getDb().prepare(`
  2498. select dst.kind as dstKind, dst.file_path as dstPath
  2499. from edges e
  2500. join nodes src on e.source = src.id
  2501. join nodes dst on e.target = dst.id
  2502. where e.kind = 'imports'
  2503. and src.kind = 'file'
  2504. and src.file_path = 'app/page.php'
  2505. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2506. expect(
  2507. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  2508. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  2509. ).toBeUndefined();
  2510. } finally {
  2511. fs.rmSync(tempProject, { recursive: true, force: true });
  2512. }
  2513. });
  2514. });
  2515. describe('C++ chained-call receiver resolution (#645)', () => {
  2516. async function indexCpp(files: Record<string, string>): Promise<void> {
  2517. for (const [name, content] of Object.entries(files)) {
  2518. fs.writeFileSync(path.join(tempDir, name), content);
  2519. }
  2520. cg = await CodeGraph.init(tempDir, { index: true });
  2521. }
  2522. function callerNamesOf(qualifiedName: string): string[] {
  2523. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2524. if (!target) return [];
  2525. const names = cg
  2526. .getIncomingEdges(target.id)
  2527. .filter((e) => e.kind === 'calls')
  2528. .map((e) => cg.getNode(e.source)?.name)
  2529. .filter((n): n is string => !!n);
  2530. return [...new Set(names)].sort();
  2531. }
  2532. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  2533. // Two classes share writeLog; Logger sorts first so it wins any name-only
  2534. // tie. All three call forms target Metrics.
  2535. await indexCpp({
  2536. 'logger.hpp': `#pragma once
  2537. #include <string>
  2538. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  2539. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  2540. `,
  2541. 'impl.cpp': `#include "logger.hpp"
  2542. Logger& Logger::instance() { static Logger l; return l; }
  2543. Metrics& Metrics::instance() { static Metrics m; return m; }
  2544. void Logger::writeLog(const std::string&) {}
  2545. void Metrics::writeLog(const std::string&) {}
  2546. `,
  2547. 'app.cpp': `#include "logger.hpp"
  2548. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  2549. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  2550. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  2551. `,
  2552. });
  2553. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  2554. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  2555. });
  2556. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  2557. await indexCpp({
  2558. 'types.hpp': `#pragma once
  2559. #include <memory>
  2560. struct Widget { void draw(); };
  2561. struct Session { void run(); };
  2562. struct View { void render(); };
  2563. class WidgetFactory { public: static Widget create(); };
  2564. class Manager { public: View view(); };
  2565. Session* openSession();
  2566. // Decoy that sorts first and has all three methods — must never win.
  2567. struct Aaa { void draw(); void run(); void render(); };
  2568. `,
  2569. 'impl.cpp': `#include "types.hpp"
  2570. void Widget::draw() {}
  2571. void Session::run() {}
  2572. void View::render() {}
  2573. void Aaa::draw() {}
  2574. void Aaa::run() {}
  2575. void Aaa::render() {}
  2576. Widget WidgetFactory::create() { return Widget(); }
  2577. View Manager::view() { return View(); }
  2578. Session* openSession() { return nullptr; }
  2579. `,
  2580. 'app.cpp': `#include "types.hpp"
  2581. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  2582. void freefunc() { openSession()->run(); } // -> Session::run
  2583. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  2584. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  2585. `,
  2586. });
  2587. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  2588. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  2589. expect(callerNamesOf('View::render')).toEqual(['member']);
  2590. // The first-sorted decoy never captures any of them.
  2591. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2592. expect(callerNamesOf('Aaa::run')).toEqual([]);
  2593. expect(callerNamesOf('Aaa::render')).toEqual([]);
  2594. });
  2595. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  2596. await indexCpp({
  2597. 'types.hpp': `#pragma once
  2598. struct Widget { void draw(); };
  2599. struct Other { void onlyOther(); };
  2600. class WidgetFactory { public: static Widget create(); };
  2601. `,
  2602. 'impl.cpp': `#include "types.hpp"
  2603. void Widget::draw() {}
  2604. void Other::onlyOther() {}
  2605. Widget WidgetFactory::create() { return Widget(); }
  2606. `,
  2607. 'app.cpp': `#include "types.hpp"
  2608. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  2609. void wrong() { WidgetFactory::create().onlyOther(); }
  2610. `,
  2611. });
  2612. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2613. });
  2614. });
  2615. describe('PHP chained static-factory call resolution (#608)', () => {
  2616. function callerNamesOf(qualifiedName: string): string[] {
  2617. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2618. if (!target) return [];
  2619. const names = cg
  2620. .getIncomingEdges(target.id)
  2621. .filter((e) => e.kind === 'calls')
  2622. .map((e) => cg.getNode(e.source)?.name)
  2623. .filter((n): n is string => !!n);
  2624. return [...new Set(names)].sort();
  2625. }
  2626. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  2627. fs.writeFileSync(
  2628. path.join(tempDir, 'ApiClient.php'),
  2629. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  2630. );
  2631. fs.writeFileSync(
  2632. path.join(tempDir, 'DispatchOrder.php'),
  2633. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  2634. );
  2635. cg = await CodeGraph.init(tempDir, { index: true });
  2636. // The chained call's edge attaches to the factory result's method.
  2637. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  2638. });
  2639. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  2640. fs.writeFileSync(
  2641. path.join(tempDir, 'lib.php'),
  2642. `<?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`
  2643. );
  2644. cg = await CodeGraph.init(tempDir, { index: true });
  2645. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  2646. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2647. });
  2648. });
  2649. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  2650. function callerNamesOf(qualifiedName: string): string[] {
  2651. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2652. if (!target) return [];
  2653. const names = cg
  2654. .getIncomingEdges(target.id)
  2655. .filter((e) => e.kind === 'calls')
  2656. .map((e) => cg.getNode(e.source)?.name)
  2657. .filter((n): n is string => !!n);
  2658. return [...new Set(names)].sort();
  2659. }
  2660. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  2661. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  2662. fs.writeFileSync(
  2663. path.join(tempDir, 'Main.java'),
  2664. `class Aaa { void bar() {} }
  2665. class Foo {
  2666. static Foo getInstance() { return new Foo(); }
  2667. void bar() {}
  2668. }
  2669. class Caller {
  2670. void run() { Foo.getInstance().bar(); }
  2671. }
  2672. `
  2673. );
  2674. cg = await CodeGraph.init(tempDir, { index: true });
  2675. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2676. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2677. });
  2678. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2679. // The factory call carries an argument; the extractor must normalize the
  2680. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  2681. fs.writeFileSync(
  2682. path.join(tempDir, 'Main.java'),
  2683. `class Config {}
  2684. class Foo {
  2685. static Foo create(Config c) { return new Foo(); }
  2686. void build() {}
  2687. }
  2688. class Caller {
  2689. void run() { Foo.create(new Config()).build(); }
  2690. }
  2691. `
  2692. );
  2693. cg = await CodeGraph.init(tempDir, { index: true });
  2694. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2695. });
  2696. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2697. fs.writeFileSync(
  2698. path.join(tempDir, 'Main.java'),
  2699. `class Foo {
  2700. static Foo getInstance() { return new Foo(); }
  2701. }
  2702. class Other { void onlyOther() {} }
  2703. class Caller {
  2704. void run() { Foo.getInstance().onlyOther(); }
  2705. }
  2706. `
  2707. );
  2708. cg = await CodeGraph.init(tempDir, { index: true });
  2709. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2710. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2711. });
  2712. });
  2713. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  2714. function callerNamesOf(qualifiedName: string): string[] {
  2715. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2716. if (!target) return [];
  2717. const names = cg
  2718. .getIncomingEdges(target.id)
  2719. .filter((e) => e.kind === 'calls')
  2720. .map((e) => cg.getNode(e.source)?.name)
  2721. .filter((n): n is string => !!n);
  2722. return [...new Set(names)].sort();
  2723. }
  2724. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  2725. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  2726. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  2727. fs.writeFileSync(
  2728. path.join(tempDir, 'Main.kt'),
  2729. `class Aaa { fun bar() {} }
  2730. class Foo {
  2731. companion object {
  2732. fun getInstance(): Foo = Foo()
  2733. }
  2734. fun bar() {}
  2735. }
  2736. class Caller {
  2737. fun run() { Foo.getInstance().bar() }
  2738. }
  2739. `
  2740. );
  2741. cg = await CodeGraph.init(tempDir, { index: true });
  2742. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2743. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2744. });
  2745. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2746. fs.writeFileSync(
  2747. path.join(tempDir, 'Main.kt'),
  2748. `class Config
  2749. class Foo {
  2750. companion object {
  2751. fun create(c: Config): Foo = Foo()
  2752. }
  2753. fun build() {}
  2754. }
  2755. class Caller {
  2756. fun run() { Foo.create(Config()).build() }
  2757. }
  2758. `
  2759. );
  2760. cg = await CodeGraph.init(tempDir, { index: true });
  2761. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2762. });
  2763. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  2764. fs.writeFileSync(
  2765. path.join(tempDir, 'Main.kt'),
  2766. `class Foo {
  2767. companion object {
  2768. fun getInstance(): Foo = Foo()
  2769. }
  2770. }
  2771. class Other { fun onlyOther() {} }
  2772. class Caller {
  2773. fun run() { Foo.getInstance().onlyOther() }
  2774. }
  2775. `
  2776. );
  2777. cg = await CodeGraph.init(tempDir, { index: true });
  2778. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2779. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2780. });
  2781. });
  2782. describe('C# chained static-factory call resolution (#645/#608 mechanism)', () => {
  2783. function callerNamesOf(qualifiedName: string): string[] {
  2784. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2785. if (!target) return [];
  2786. const names = cg
  2787. .getIncomingEdges(target.id)
  2788. .filter((e) => e.kind === 'calls')
  2789. .map((e) => cg.getNode(e.source)?.name)
  2790. .filter((n): n is string => !!n);
  2791. return [...new Set(names)].sort();
  2792. }
  2793. it('resolves Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  2794. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  2795. fs.writeFileSync(
  2796. path.join(tempDir, 'Main.cs'),
  2797. `class Aaa { void Bar() {} }
  2798. class Foo {
  2799. static Foo Create() { return new Foo(); }
  2800. void Bar() {}
  2801. }
  2802. class Caller {
  2803. void Run() { Foo.Create().Bar(); }
  2804. }
  2805. `
  2806. );
  2807. cg = await CodeGraph.init(tempDir, { index: true });
  2808. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  2809. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  2810. });
  2811. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  2812. fs.writeFileSync(
  2813. path.join(tempDir, 'Main.cs'),
  2814. `class Config {}
  2815. class Foo {
  2816. static Foo Make(Config c) { return new Foo(); }
  2817. void Build() {}
  2818. }
  2819. class Caller {
  2820. void Run() { Foo.Make(new Config()).Build(); }
  2821. }
  2822. `
  2823. );
  2824. cg = await CodeGraph.init(tempDir, { index: true });
  2825. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  2826. });
  2827. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2828. fs.writeFileSync(
  2829. path.join(tempDir, 'Main.cs'),
  2830. `class Foo {
  2831. static Foo Create() { return new Foo(); }
  2832. }
  2833. class Other { void OnlyOther() {} }
  2834. class Caller {
  2835. void Run() { Foo.Create().OnlyOther(); }
  2836. }
  2837. `
  2838. );
  2839. cg = await CodeGraph.init(tempDir, { index: true });
  2840. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  2841. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  2842. });
  2843. });
  2844. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  2845. function callerNamesOf(qualifiedName: string): string[] {
  2846. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2847. if (!target) return [];
  2848. const names = cg
  2849. .getIncomingEdges(target.id)
  2850. .filter((e) => e.kind === 'calls')
  2851. .map((e) => cg.getNode(e.source)?.name)
  2852. .filter((n): n is string => !!n);
  2853. return [...new Set(names)].sort();
  2854. }
  2855. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  2856. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  2857. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  2858. fs.writeFileSync(
  2859. path.join(tempDir, 'Main.swift'),
  2860. `class Aaa { func draw() {} }
  2861. class Foo {
  2862. static func make() -> Foo { return Foo() }
  2863. func draw() {}
  2864. }
  2865. func runCaller() { Foo.make().draw() }
  2866. `
  2867. );
  2868. cg = await CodeGraph.init(tempDir, { index: true });
  2869. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2870. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2871. });
  2872. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  2873. fs.writeFileSync(
  2874. path.join(tempDir, 'Main.swift'),
  2875. `class Config {}
  2876. class Foo {
  2877. static func build(_ c: Config) -> Foo { return Foo() }
  2878. func draw() {}
  2879. func render() {}
  2880. }
  2881. func runCaller() {
  2882. Foo().draw()
  2883. Foo.build(Config()).render()
  2884. }
  2885. `
  2886. );
  2887. cg = await CodeGraph.init(tempDir, { index: true });
  2888. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2889. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  2890. });
  2891. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2892. fs.writeFileSync(
  2893. path.join(tempDir, 'Main.swift'),
  2894. `class Foo {
  2895. static func make() -> Foo { return Foo() }
  2896. }
  2897. class Other { func onlyOther() {} }
  2898. func runCaller() { Foo.make().onlyOther() }
  2899. `
  2900. );
  2901. cg = await CodeGraph.init(tempDir, { index: true });
  2902. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2903. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2904. });
  2905. });
  2906. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  2907. function callerNamesOf(qualifiedName: string): string[] {
  2908. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2909. if (!target) return [];
  2910. const names = cg
  2911. .getIncomingEdges(target.id)
  2912. .filter((e) => e.kind === 'calls')
  2913. .map((e) => cg.getNode(e.source)?.name)
  2914. .filter((n): n is string => !!n);
  2915. return [...new Set(names)].sort();
  2916. }
  2917. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  2918. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  2919. // its own. Decoy.draw must never win. Needs the conformance second pass.
  2920. fs.writeFileSync(
  2921. path.join(tempDir, 'Main.java'),
  2922. `class Base { void draw() {} }
  2923. class Widget extends Base {}
  2924. class Decoy { void draw() {} }
  2925. class Factory { static Widget create() { return new Widget(); } }
  2926. class Caller {
  2927. void run() { Factory.create().draw(); }
  2928. }
  2929. `
  2930. );
  2931. cg = await CodeGraph.init(tempDir, { index: true });
  2932. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  2933. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2934. });
  2935. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  2936. fs.writeFileSync(
  2937. path.join(tempDir, 'Main.java'),
  2938. `interface Drawable { default void draw() {} }
  2939. class Widget implements Drawable {}
  2940. class Decoy { void draw() {} }
  2941. class Factory { static Widget create() { return new Widget(); } }
  2942. class Caller {
  2943. void run() { Factory.create().draw(); }
  2944. }
  2945. `
  2946. );
  2947. cg = await CodeGraph.init(tempDir, { index: true });
  2948. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  2949. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2950. });
  2951. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  2952. fs.writeFileSync(
  2953. path.join(tempDir, 'Main.java'),
  2954. `class Base {}
  2955. class Widget extends Base {}
  2956. class Other { void onlyOther() {} }
  2957. class Factory { static Widget create() { return new Widget(); } }
  2958. class Caller {
  2959. void run() { Factory.create().onlyOther(); }
  2960. }
  2961. `
  2962. );
  2963. cg = await CodeGraph.init(tempDir, { index: true });
  2964. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  2965. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2966. });
  2967. });
  2968. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  2969. function callerNamesOf(qualifiedName: string): string[] {
  2970. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2971. if (!target) return [];
  2972. const names = cg
  2973. .getIncomingEdges(target.id)
  2974. .filter((e) => e.kind === 'calls')
  2975. .map((e) => cg.getNode(e.source)?.name)
  2976. .filter((n): n is string => !!n);
  2977. return [...new Set(names)].sort();
  2978. }
  2979. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  2980. fs.writeFileSync(
  2981. path.join(tempDir, 'main.rs'),
  2982. `struct Aaa { _x: i32 }
  2983. impl Aaa { fn bar(&self) {} }
  2984. struct Foo { _x: i32 }
  2985. impl Foo {
  2986. fn new() -> Foo { Foo { _x: 0 } }
  2987. fn make() -> Self { Foo { _x: 0 } }
  2988. fn bar(&self) {}
  2989. }
  2990. fn caller() {
  2991. Foo::new().bar();
  2992. Foo::make().bar();
  2993. }
  2994. `
  2995. );
  2996. cg = await CodeGraph.init(tempDir, { index: true });
  2997. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  2998. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2999. });
  3000. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  3001. fs.writeFileSync(
  3002. path.join(tempDir, 'main.rs'),
  3003. `struct Config;
  3004. struct Foo { _x: i32 }
  3005. impl Foo {
  3006. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  3007. fn build(&self) {}
  3008. }
  3009. fn caller() { Foo::with(Config).build(); }
  3010. `
  3011. );
  3012. cg = await CodeGraph.init(tempDir, { index: true });
  3013. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  3014. });
  3015. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  3016. fs.writeFileSync(
  3017. path.join(tempDir, 'main.rs'),
  3018. `struct Foo { _x: i32 }
  3019. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3020. struct Decoy { _x: i32 }
  3021. impl Decoy { fn draw(&self) {} }
  3022. trait Drawable { fn draw(&self) {} }
  3023. impl Drawable for Foo {}
  3024. fn caller() { Foo::new().draw(); }
  3025. `
  3026. );
  3027. cg = await CodeGraph.init(tempDir, { index: true });
  3028. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  3029. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  3030. });
  3031. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  3032. fs.writeFileSync(
  3033. path.join(tempDir, 'main.rs'),
  3034. `struct Foo { _x: i32 }
  3035. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  3036. struct Other { _x: i32 }
  3037. impl Other { fn only_other(&self) {} }
  3038. fn caller() { Foo::new().only_other(); }
  3039. `
  3040. );
  3041. cg = await CodeGraph.init(tempDir, { index: true });
  3042. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  3043. expect(callerNamesOf('Other::only_other')).toEqual([]);
  3044. });
  3045. });
  3046. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  3047. function callerNamesOf(qualifiedName: string): string[] {
  3048. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3049. if (!target) return [];
  3050. const names = cg
  3051. .getIncomingEdges(target.id)
  3052. .filter((e) => e.kind === 'calls')
  3053. .map((e) => cg.getNode(e.source)?.name)
  3054. .filter((n): n is string => !!n);
  3055. return [...new Set(names)].sort();
  3056. }
  3057. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  3058. fs.writeFileSync(
  3059. path.join(tempDir, 'main.go'),
  3060. `package main
  3061. type Aaa struct{}
  3062. func (a *Aaa) Bar() {}
  3063. type Foo struct{}
  3064. func New() *Foo { return &Foo{} }
  3065. func (f *Foo) Bar() {}
  3066. func caller() { New().Bar() }
  3067. `
  3068. );
  3069. cg = await CodeGraph.init(tempDir, { index: true });
  3070. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  3071. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  3072. });
  3073. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  3074. fs.writeFileSync(
  3075. path.join(tempDir, 'main.go'),
  3076. `package main
  3077. type Config struct{}
  3078. type Foo struct{}
  3079. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  3080. func (f *Foo) Build() {}
  3081. func caller() { With(Config{}).Build() }
  3082. `
  3083. );
  3084. cg = await CodeGraph.init(tempDir, { index: true });
  3085. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  3086. });
  3087. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  3088. fs.writeFileSync(
  3089. path.join(tempDir, 'main.go'),
  3090. `package main
  3091. type Base struct{}
  3092. func (b *Base) Embedded() {}
  3093. type Decoy struct{}
  3094. func (d *Decoy) Embedded() {}
  3095. type Widget struct{ Base }
  3096. func NewWidget() *Widget { return &Widget{} }
  3097. func caller() { NewWidget().Embedded() }
  3098. `
  3099. );
  3100. cg = await CodeGraph.init(tempDir, { index: true });
  3101. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  3102. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  3103. });
  3104. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  3105. fs.writeFileSync(
  3106. path.join(tempDir, 'main.go'),
  3107. `package main
  3108. type Foo struct{}
  3109. func New() *Foo { return &Foo{} }
  3110. type Other struct{}
  3111. func (o *Other) OnlyOther() {}
  3112. func caller() { New().OnlyOther() }
  3113. `
  3114. );
  3115. cg = await CodeGraph.init(tempDir, { index: true });
  3116. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3117. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3118. });
  3119. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  3120. // `engine` is a package-level VARIABLE holding a func value, not a factory
  3121. // FUNCTION — so its return type can't be recovered and the chain falls back
  3122. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  3123. // Regression for the runaway this fallback originally caused: it resolved
  3124. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  3125. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  3126. // no-oped, the offset-0 batch never drained, and edges inserted forever
  3127. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  3128. // the original ref, and a non-progress guard backstops the loop.
  3129. fs.writeFileSync(
  3130. path.join(tempDir, 'main.go'),
  3131. `package main
  3132. type Server struct{}
  3133. func (s *Server) ServeHTTP() {}
  3134. var engine = func() *Server { return &Server{} }
  3135. func caller() { engine().ServeHTTP() }
  3136. `
  3137. );
  3138. cg = await CodeGraph.init(tempDir, { index: true });
  3139. // Recall: the variable-inner chain still finds the method by bare name.
  3140. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  3141. // No runaway: a single call site yields a single edge, not millions.
  3142. const target = cg
  3143. .getNodesByKind('method')
  3144. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  3145. const rawCalls = cg
  3146. .getIncomingEdges(target.id)
  3147. .filter((e) => e.kind === 'calls');
  3148. expect(rawCalls.length).toBeLessThan(5);
  3149. });
  3150. });
  3151. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  3152. function callerNamesOf(qualifiedName: string): string[] {
  3153. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3154. if (!target) return [];
  3155. const names = cg
  3156. .getIncomingEdges(target.id)
  3157. .filter((e) => e.kind === 'calls')
  3158. .map((e) => cg.getNode(e.source)?.name)
  3159. .filter((n): n is string => !!n);
  3160. return [...new Set(names)].sort();
  3161. }
  3162. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  3163. fs.writeFileSync(
  3164. path.join(tempDir, 'Main.scala'),
  3165. `object Foo {
  3166. def create(): Bar = new Bar()
  3167. }
  3168. class Bar {
  3169. def doIt(): Unit = {}
  3170. }
  3171. class Decoy {
  3172. def doIt(): Unit = {}
  3173. }
  3174. object Main {
  3175. def run(): Unit = { Foo.create().doIt() }
  3176. }
  3177. `
  3178. );
  3179. cg = await CodeGraph.init(tempDir, { index: true });
  3180. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3181. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3182. });
  3183. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  3184. fs.writeFileSync(
  3185. path.join(tempDir, 'Main.scala'),
  3186. `class Point(x: Int) {
  3187. def dist(): Int = x
  3188. }
  3189. class Other {
  3190. def dist(): Int = 0
  3191. }
  3192. object Main {
  3193. def run(): Unit = { Point(3).dist() }
  3194. }
  3195. `
  3196. );
  3197. cg = await CodeGraph.init(tempDir, { index: true });
  3198. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  3199. expect(callerNamesOf('Other::dist')).toEqual([]);
  3200. });
  3201. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  3202. fs.writeFileSync(
  3203. path.join(tempDir, 'Main.scala'),
  3204. `trait Base {
  3205. def shared(): Unit = {}
  3206. }
  3207. class Widget extends Base
  3208. class Decoy {
  3209. def shared(): Unit = {}
  3210. }
  3211. object Factory {
  3212. def make(): Widget = new Widget()
  3213. }
  3214. object Main {
  3215. def run(): Unit = { Factory.make().shared() }
  3216. }
  3217. `
  3218. );
  3219. cg = await CodeGraph.init(tempDir, { index: true });
  3220. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  3221. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  3222. });
  3223. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3224. fs.writeFileSync(
  3225. path.join(tempDir, 'Main.scala'),
  3226. `object Foo {
  3227. def create(): Bar = new Bar()
  3228. }
  3229. class Bar {
  3230. }
  3231. class Other {
  3232. def onlyOther(): Unit = {}
  3233. }
  3234. object Main {
  3235. def run(): Unit = { Foo.create().onlyOther() }
  3236. }
  3237. `
  3238. );
  3239. cg = await CodeGraph.init(tempDir, { index: true });
  3240. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3241. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3242. });
  3243. });
  3244. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  3245. function callerNamesOf(qualifiedName: string): string[] {
  3246. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3247. if (!target) return [];
  3248. const names = cg
  3249. .getIncomingEdges(target.id)
  3250. .filter((e) => e.kind === 'calls')
  3251. .map((e) => cg.getNode(e.source)?.name)
  3252. .filter((n): n is string => !!n);
  3253. return [...new Set(names)].sort();
  3254. }
  3255. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  3256. fs.writeFileSync(
  3257. path.join(tempDir, 'main.dart'),
  3258. `class Foo {
  3259. static Bar makeBar() => Bar();
  3260. }
  3261. class Bar {
  3262. void doIt() {}
  3263. }
  3264. class Decoy {
  3265. void doIt() {}
  3266. }
  3267. void run() {
  3268. Foo.makeBar().doIt();
  3269. }
  3270. `
  3271. );
  3272. cg = await CodeGraph.init(tempDir, { index: true });
  3273. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3274. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3275. });
  3276. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  3277. fs.writeFileSync(
  3278. path.join(tempDir, 'main.dart'),
  3279. `class Foo {
  3280. Foo._();
  3281. factory Foo.create() => Foo._();
  3282. void ship() {}
  3283. }
  3284. class Decoy {
  3285. void ship() {}
  3286. }
  3287. void run() {
  3288. Foo.create().ship();
  3289. }
  3290. `
  3291. );
  3292. cg = await CodeGraph.init(tempDir, { index: true });
  3293. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  3294. // so `ship` resolves on Foo, not the same-named Decoy.
  3295. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  3296. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  3297. });
  3298. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  3299. fs.writeFileSync(
  3300. path.join(tempDir, 'main.dart'),
  3301. `class Bar {
  3302. void doIt() {}
  3303. }
  3304. class Decoy {
  3305. void doIt() {}
  3306. }
  3307. void run() {
  3308. Bar().doIt();
  3309. }
  3310. `
  3311. );
  3312. cg = await CodeGraph.init(tempDir, { index: true });
  3313. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3314. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3315. });
  3316. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  3317. fs.writeFileSync(
  3318. path.join(tempDir, 'main.dart'),
  3319. `class Base {
  3320. void render() {}
  3321. }
  3322. class Widget extends Base {
  3323. static Widget make() => Widget();
  3324. }
  3325. class Decoy {
  3326. void render() {}
  3327. }
  3328. void run() {
  3329. Widget.make().render();
  3330. }
  3331. `
  3332. );
  3333. cg = await CodeGraph.init(tempDir, { index: true });
  3334. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3335. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3336. });
  3337. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3338. fs.writeFileSync(
  3339. path.join(tempDir, 'main.dart'),
  3340. `class Foo {
  3341. static Bar makeBar() => Bar();
  3342. }
  3343. class Bar {
  3344. }
  3345. class Other {
  3346. void onlyOther() {}
  3347. }
  3348. void run() {
  3349. Foo.makeBar().onlyOther();
  3350. }
  3351. `
  3352. );
  3353. cg = await CodeGraph.init(tempDir, { index: true });
  3354. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3355. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3356. });
  3357. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  3358. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  3359. // swallows the record return type, so `reduce()` looks like a single-
  3360. // identifier constructor_signature. It must NOT be skipped as an unnamed
  3361. // ctor (its name doesn't match the class); its body call must attribute to
  3362. // `reduce`, not the class.
  3363. fs.writeFileSync(
  3364. path.join(tempDir, 'main.dart'),
  3365. `class Base {}
  3366. class Action extends Base {
  3367. Action({required int x});
  3368. @override
  3369. (int, String) reduce() {
  3370. return (compute(), "y");
  3371. }
  3372. int compute() => 1;
  3373. }
  3374. `
  3375. );
  3376. cg = await CodeGraph.init(tempDir, { index: true });
  3377. // reduce must be a node and its body call must resolve to Action::compute.
  3378. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  3379. });
  3380. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  3381. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  3382. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  3383. // never hijacked into a call to a phantom constructor method.
  3384. fs.writeFileSync(
  3385. path.join(tempDir, 'main.dart'),
  3386. `class Widget {
  3387. final int x;
  3388. Widget(this.x);
  3389. }
  3390. void run() {
  3391. Widget(3);
  3392. }
  3393. `
  3394. );
  3395. cg = await CodeGraph.init(tempDir, { index: true });
  3396. // No Foo::Foo phantom method node.
  3397. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  3398. // The construction resolves to the class as an `instantiates` edge.
  3399. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  3400. const incoming = cg.getIncomingEdges(widget.id);
  3401. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  3402. });
  3403. });
  3404. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  3405. function callerNamesOf(qualifiedName: string): string[] {
  3406. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3407. if (!target) return [];
  3408. const names = cg
  3409. .getIncomingEdges(target.id)
  3410. .filter((e) => e.kind === 'calls')
  3411. .map((e) => cg.getNode(e.source)?.name)
  3412. .filter((n): n is string => !!n);
  3413. return [...new Set(names)].sort();
  3414. }
  3415. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  3416. fs.writeFileSync(
  3417. path.join(tempDir, 'main.m'),
  3418. `@interface Bar : NSObject
  3419. - (void)doIt;
  3420. @end
  3421. @implementation Bar
  3422. - (void)doIt {}
  3423. @end
  3424. @interface Decoy : NSObject
  3425. - (void)doIt;
  3426. @end
  3427. @implementation Decoy
  3428. - (void)doIt {}
  3429. @end
  3430. @interface Foo : NSObject
  3431. + (Bar *)create;
  3432. @end
  3433. @implementation Foo
  3434. + (Bar *)create { return nil; }
  3435. - (void)run { [[Foo create] doIt]; }
  3436. @end
  3437. `
  3438. );
  3439. cg = await CodeGraph.init(tempDir, { index: true });
  3440. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3441. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3442. });
  3443. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  3444. fs.writeFileSync(
  3445. path.join(tempDir, 'main.m'),
  3446. `@interface Base : NSObject
  3447. - (void)render;
  3448. @end
  3449. @implementation Base
  3450. - (void)render {}
  3451. @end
  3452. @interface Widget : Base
  3453. @end
  3454. @implementation Widget
  3455. @end
  3456. @interface Decoy : NSObject
  3457. - (void)render;
  3458. @end
  3459. @implementation Decoy
  3460. - (void)render {}
  3461. @end
  3462. @interface Factory : NSObject
  3463. + (Widget *)make;
  3464. @end
  3465. @implementation Factory
  3466. + (Widget *)make { return nil; }
  3467. - (void)run { [[Factory make] render]; }
  3468. @end
  3469. `
  3470. );
  3471. cg = await CodeGraph.init(tempDir, { index: true });
  3472. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3473. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3474. });
  3475. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3476. fs.writeFileSync(
  3477. path.join(tempDir, 'main.m'),
  3478. `@interface Bar : NSObject
  3479. @end
  3480. @implementation Bar
  3481. @end
  3482. @interface Other : NSObject
  3483. - (void)onlyOther;
  3484. @end
  3485. @implementation Other
  3486. - (void)onlyOther {}
  3487. @end
  3488. @interface Foo : NSObject
  3489. + (Bar *)create;
  3490. @end
  3491. @implementation Foo
  3492. + (Bar *)create { return nil; }
  3493. - (void)run { [[Foo create] onlyOther]; }
  3494. @end
  3495. `
  3496. );
  3497. cg = await CodeGraph.init(tempDir, { index: true });
  3498. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3499. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3500. });
  3501. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  3502. // The factory returns `nonnull instancetype` — the nullability qualifier must
  3503. // be skipped (not captured AS the type), and an instancetype class-message
  3504. // factory returns the receiver class, so clearAll resolves on Cache, never a
  3505. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  3506. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  3507. fs.writeFileSync(
  3508. path.join(tempDir, 'main.m'),
  3509. `@interface Cache : NSObject
  3510. + (nonnull instancetype)shared;
  3511. - (void)clearAll;
  3512. @end
  3513. @implementation Cache
  3514. + (nonnull instancetype)shared { return nil; }
  3515. - (void)clearAll {}
  3516. @end
  3517. @interface Decoy : NSObject
  3518. - (void)clearAll;
  3519. @end
  3520. @implementation Decoy
  3521. - (void)clearAll {}
  3522. @end
  3523. @interface Caller : NSObject
  3524. - (void)run;
  3525. @end
  3526. @implementation Caller
  3527. - (void)run { [[Cache shared] clearAll]; }
  3528. @end
  3529. `
  3530. );
  3531. cg = await CodeGraph.init(tempDir, { index: true });
  3532. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  3533. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  3534. });
  3535. });
  3536. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  3537. function callerNamesOf(qualifiedName: string): string[] {
  3538. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3539. if (!target) return [];
  3540. const names = cg
  3541. .getIncomingEdges(target.id)
  3542. .filter((e) => e.kind === 'calls')
  3543. .map((e) => cg.getNode(e.source)?.name)
  3544. .filter((n): n is string => !!n);
  3545. return [...new Set(names)].sort();
  3546. }
  3547. function isCalled(qn: string): boolean {
  3548. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  3549. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  3550. }
  3551. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  3552. fs.writeFileSync(
  3553. path.join(tempDir, 'main.pas'),
  3554. `unit Main;
  3555. interface
  3556. type
  3557. TBar = class
  3558. procedure DoIt;
  3559. end;
  3560. TDecoy = class
  3561. procedure DoIt;
  3562. end;
  3563. TFoo = class
  3564. class function GetInstance: TBar;
  3565. end;
  3566. implementation
  3567. procedure TBar.DoIt; begin end;
  3568. procedure TDecoy.DoIt; begin end;
  3569. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3570. procedure Run;
  3571. begin
  3572. TFoo.GetInstance().DoIt();
  3573. end;
  3574. end.
  3575. `
  3576. );
  3577. cg = await CodeGraph.init(tempDir, { index: true });
  3578. expect(isCalled('TBar::DoIt')).toBe(true);
  3579. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3580. });
  3581. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  3582. fs.writeFileSync(
  3583. path.join(tempDir, 'main.pas'),
  3584. `unit Main;
  3585. interface
  3586. type
  3587. TFoo = class
  3588. constructor Create;
  3589. procedure Configure;
  3590. end;
  3591. TDecoy = class
  3592. procedure Configure;
  3593. end;
  3594. implementation
  3595. constructor TFoo.Create; begin end;
  3596. procedure TFoo.Configure; begin end;
  3597. procedure TDecoy.Configure; begin end;
  3598. procedure Run;
  3599. begin
  3600. TFoo.Create().Configure();
  3601. end;
  3602. end.
  3603. `
  3604. );
  3605. cg = await CodeGraph.init(tempDir, { index: true });
  3606. // A constructor returns its own class (no `: TBar` annotation), so Configure
  3607. // resolves on TFoo, not the same-named decoy.
  3608. expect(isCalled('TFoo::Configure')).toBe(true);
  3609. expect(isCalled('TDecoy::Configure')).toBe(false);
  3610. });
  3611. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  3612. fs.writeFileSync(
  3613. path.join(tempDir, 'main.pas'),
  3614. `unit Main;
  3615. interface
  3616. type
  3617. TFoo = class
  3618. procedure DoIt;
  3619. end;
  3620. TDecoy = class
  3621. procedure DoIt;
  3622. end;
  3623. implementation
  3624. procedure TFoo.DoIt; begin end;
  3625. procedure TDecoy.DoIt; begin end;
  3626. procedure Run(obj: TObject);
  3627. begin
  3628. TFoo(obj).DoIt();
  3629. end;
  3630. end.
  3631. `
  3632. );
  3633. cg = await CodeGraph.init(tempDir, { index: true });
  3634. expect(isCalled('TFoo::DoIt')).toBe(true);
  3635. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3636. });
  3637. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3638. fs.writeFileSync(
  3639. path.join(tempDir, 'main.pas'),
  3640. `unit Main;
  3641. interface
  3642. type
  3643. TBar = class
  3644. end;
  3645. TOther = class
  3646. procedure OnlyOther;
  3647. end;
  3648. TFoo = class
  3649. class function GetInstance: TBar;
  3650. end;
  3651. implementation
  3652. procedure TOther.OnlyOther; begin end;
  3653. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3654. procedure Run;
  3655. begin
  3656. TFoo.GetInstance().OnlyOther();
  3657. end;
  3658. end.
  3659. `
  3660. );
  3661. cg = await CodeGraph.init(tempDir, { index: true });
  3662. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  3663. expect(isCalled('TOther::OnlyOther')).toBe(false);
  3664. });
  3665. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  3666. fs.writeFileSync(
  3667. path.join(tempDir, 'main.pas'),
  3668. `unit Main;
  3669. interface
  3670. type
  3671. TFoo = class
  3672. procedure DoThing;
  3673. procedure Reset;
  3674. end;
  3675. implementation
  3676. procedure TFoo.DoThing; begin end;
  3677. procedure TFoo.Reset; begin end;
  3678. procedure Run(f: TFoo);
  3679. begin
  3680. f.DoThing;
  3681. f.Reset;
  3682. end;
  3683. end.
  3684. `
  3685. );
  3686. cg = await CodeGraph.init(tempDir, { index: true });
  3687. expect(isCalled('TFoo::DoThing')).toBe(true);
  3688. expect(isCalled('TFoo::Reset')).toBe(true);
  3689. });
  3690. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  3691. fs.writeFileSync(
  3692. path.join(tempDir, 'main.pas'),
  3693. `unit Main;
  3694. interface
  3695. type
  3696. TBar = class
  3697. procedure DoIt;
  3698. end;
  3699. TDecoy = class
  3700. procedure DoIt;
  3701. end;
  3702. TFoo = class
  3703. class function GetInstance: TBar;
  3704. end;
  3705. implementation
  3706. procedure TBar.DoIt; begin end;
  3707. procedure TDecoy.DoIt; begin end;
  3708. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3709. procedure Run;
  3710. begin
  3711. TFoo.GetInstance.DoIt;
  3712. end;
  3713. end.
  3714. `
  3715. );
  3716. cg = await CodeGraph.init(tempDir, { index: true });
  3717. expect(isCalled('TBar::DoIt')).toBe(true);
  3718. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3719. });
  3720. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  3721. fs.writeFileSync(
  3722. path.join(tempDir, 'main.pas'),
  3723. `unit Main;
  3724. interface
  3725. type
  3726. TFoo = class
  3727. function GetValue: Integer;
  3728. procedure SetValue(v: Integer);
  3729. property Value: Integer read GetValue write SetValue;
  3730. end;
  3731. implementation
  3732. function TFoo.GetValue: Integer; begin Result := 0; end;
  3733. procedure TFoo.SetValue(v: Integer); begin end;
  3734. procedure Run(f: TFoo);
  3735. var x: Integer;
  3736. begin
  3737. f.Value := 5;
  3738. x := f.Value;
  3739. end;
  3740. end.
  3741. `
  3742. );
  3743. cg = await CodeGraph.init(tempDir, { index: true });
  3744. // A property read/write is a bare dot in assignment position, not a statement,
  3745. // so it must not be mis-extracted as a call to the property's getter/setter.
  3746. expect(isCalled('TFoo::GetValue')).toBe(false);
  3747. expect(isCalled('TFoo::SetValue')).toBe(false);
  3748. });
  3749. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  3750. fs.writeFileSync(
  3751. path.join(tempDir, 'main.pas'),
  3752. `unit Main;
  3753. interface
  3754. type
  3755. TTgt = class
  3756. procedure Hit;
  3757. end;
  3758. TFoo = class
  3759. procedure DoStuff;
  3760. end;
  3761. implementation
  3762. procedure TTgt.Hit; begin end;
  3763. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  3764. procedure Helper; var t: TTgt; begin t.Hit; end;
  3765. `
  3766. );
  3767. cg = await CodeGraph.init(tempDir, { index: true });
  3768. // `Helper` is implementation-only (no interface decl, not a method), but its
  3769. // body's call must attribute to `Helper`, not the file/module — alongside the
  3770. // method `DoStuff`.
  3771. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  3772. });
  3773. });
  3774. });