resolution.test.ts 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010
  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. });
  1552. describe('Name Matcher: kind bias for new ref kinds', () => {
  1553. const baseContext = (candidates: Node[]): ResolutionContext => ({
  1554. getNodesInFile: () => [],
  1555. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1556. getNodesByQualifiedName: () => [],
  1557. getNodesByKind: () => [],
  1558. fileExists: () => true,
  1559. readFile: () => null,
  1560. getProjectRoot: () => '/test',
  1561. getAllFiles: () => [],
  1562. getNodesByLowerName: () => [],
  1563. getImportMappings: () => [],
  1564. });
  1565. it('prefers a class candidate over a function for `instantiates` refs', () => {
  1566. // A class and a function share a name across the codebase.
  1567. // Without the kind bias, the function (which gets the +25 `calls`
  1568. // bonus historically applied to all candidates of that kind) would
  1569. // win. Now the instantiates branch reverses it.
  1570. const fn: Node = {
  1571. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  1572. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  1573. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1574. };
  1575. const cls: Node = {
  1576. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  1577. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  1578. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1579. };
  1580. const ref = {
  1581. fromNodeId: 'func:main.ts:bootstrap:1',
  1582. referenceName: 'Logger',
  1583. referenceKind: 'instantiates' as const,
  1584. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  1585. };
  1586. const result = matchReference(ref, baseContext([fn, cls]));
  1587. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  1588. });
  1589. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  1590. const variable: Node = {
  1591. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  1592. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  1593. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1594. };
  1595. const decorator: Node = {
  1596. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  1597. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  1598. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1599. };
  1600. const ref = {
  1601. fromNodeId: 'class:svc.ts:UserService:1',
  1602. referenceName: 'Inject',
  1603. referenceKind: 'decorates' as const,
  1604. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  1605. };
  1606. const result = matchReference(ref, baseContext([variable, decorator]));
  1607. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  1608. });
  1609. });
  1610. describe('tsconfig path aliases', () => {
  1611. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  1612. // Two same-named exports in different directories. Without alias
  1613. // resolution, name-matcher would pick whichever it finds first;
  1614. // with alias resolution, the import path uniquely picks one.
  1615. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1616. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  1617. fs.writeFileSync(
  1618. path.join(tempDir, 'src/utils/format.ts'),
  1619. `export function pickMe(): number { return 1; }\n`
  1620. );
  1621. fs.writeFileSync(
  1622. path.join(tempDir, 'src/legacy/format.ts'),
  1623. `export function pickMe(): number { return 99; }\n`
  1624. );
  1625. fs.writeFileSync(
  1626. path.join(tempDir, 'src/main.ts'),
  1627. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  1628. );
  1629. fs.writeFileSync(
  1630. path.join(tempDir, 'tsconfig.json'),
  1631. JSON.stringify({
  1632. compilerOptions: {
  1633. baseUrl: './src',
  1634. paths: { '@utils/*': ['utils/*'] },
  1635. },
  1636. })
  1637. );
  1638. cg = await CodeGraph.init(tempDir, { index: true });
  1639. cg.resolveReferences();
  1640. // The two pickMe nodes live in different files. The aliased
  1641. // import should attach the call edge to the @utils-mapped one,
  1642. // not the legacy duplicate.
  1643. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  1644. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  1645. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  1646. expect(utilsNode).toBeDefined();
  1647. expect(legacyNode).toBeDefined();
  1648. const utilsCallers = cg.getCallers(utilsNode!.id);
  1649. const legacyCallers = cg.getCallers(legacyNode!.id);
  1650. expect(utilsCallers.length).toBeGreaterThan(0);
  1651. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1652. // The legacy node should NOT have a caller from src/main.ts —
  1653. // the alias correctly picked the utils version.
  1654. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  1655. });
  1656. it('falls back gracefully when tsconfig is absent', async () => {
  1657. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1658. fs.writeFileSync(
  1659. path.join(tempDir, 'src/a.ts'),
  1660. `export function aFn(): void {}\n`
  1661. );
  1662. fs.writeFileSync(
  1663. path.join(tempDir, 'src/b.ts'),
  1664. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  1665. );
  1666. cg = await CodeGraph.init(tempDir, { index: true });
  1667. // No tsconfig present — index should still complete and the
  1668. // relative-import-based call edge should be created.
  1669. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  1670. expect(aFn).toBeDefined();
  1671. const callers = cg.getCallers(aFn!.id);
  1672. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  1673. });
  1674. });
  1675. describe('re-export chain following', () => {
  1676. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  1677. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  1678. // Without chain following, `signIn` resolves to nothing because
  1679. // none of the barrel files declare it directly.
  1680. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  1681. fs.writeFileSync(
  1682. path.join(tempDir, 'src/services/auth.ts'),
  1683. `export function signIn(): void {}\n`
  1684. );
  1685. fs.writeFileSync(
  1686. path.join(tempDir, 'src/services/index.ts'),
  1687. `export { signIn } from './auth';\n`
  1688. );
  1689. fs.writeFileSync(
  1690. path.join(tempDir, 'src/all.ts'),
  1691. `export * from './services/index';\n`
  1692. );
  1693. fs.writeFileSync(
  1694. path.join(tempDir, 'src/main.ts'),
  1695. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  1696. );
  1697. cg = await CodeGraph.init(tempDir, { index: true });
  1698. cg.resolveReferences();
  1699. const signInNode = cg
  1700. .getNodesByKind('function')
  1701. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  1702. expect(signInNode).toBeDefined();
  1703. const callers = cg.getCallers(signInNode!.id);
  1704. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1705. });
  1706. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  1707. // The chase has to look up `foo` in the upstream module even
  1708. // though the importer asked for `bar` — exercises the rename
  1709. // branch of findExportedSymbol.
  1710. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1711. fs.writeFileSync(
  1712. path.join(tempDir, 'src/auth.ts'),
  1713. `export function signIn(): void {}\n`
  1714. );
  1715. fs.writeFileSync(
  1716. path.join(tempDir, 'src/index.ts'),
  1717. `export { signIn as login } from './auth';\n`
  1718. );
  1719. fs.writeFileSync(
  1720. path.join(tempDir, 'src/main.ts'),
  1721. `import { login } from './index';\nexport function go(): void { login(); }\n`
  1722. );
  1723. cg = await CodeGraph.init(tempDir, { index: true });
  1724. cg.resolveReferences();
  1725. const signInNode = cg
  1726. .getNodesByKind('function')
  1727. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  1728. expect(signInNode).toBeDefined();
  1729. const callers = cg.getCallers(signInNode!.id);
  1730. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1731. });
  1732. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  1733. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  1734. // .svelte component (extracted as kind 'component', the default
  1735. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  1736. // component's real name (`RealButton`) so the name-matcher fallback
  1737. // can't coincidentally connect them — the only path to the edge is
  1738. // the import-chase, which must match a `component` (not just
  1739. // function/class) for the default export. Otherwise the
  1740. // consumer↔component edge is never created and `callers` returns a
  1741. // false 0.
  1742. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  1743. fs.writeFileSync(
  1744. path.join(tempDir, 'src/lib/RealButton.svelte'),
  1745. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1746. );
  1747. fs.writeFileSync(
  1748. path.join(tempDir, 'src/lib/index.ts'),
  1749. `export { default as Foo } from './RealButton.svelte';\n`
  1750. );
  1751. fs.writeFileSync(
  1752. path.join(tempDir, 'src/Bar.svelte'),
  1753. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  1754. );
  1755. cg = await CodeGraph.init(tempDir, { index: true });
  1756. cg.resolveReferences();
  1757. const fooNode = cg
  1758. .getNodesByKind('component')
  1759. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  1760. expect(fooNode).toBeDefined();
  1761. const callers = cg.getCallers(fooNode!.id);
  1762. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  1763. });
  1764. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  1765. // The canonical Astro shape: a page imports a layout/component in
  1766. // frontmatter and uses it as a template tag; the component's template
  1767. // calls an imported .ts util. Both hops must produce graph edges or
  1768. // an Astro project is invisible to callers/impact.
  1769. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  1770. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1771. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  1772. fs.writeFileSync(
  1773. path.join(tempDir, 'src/utils/format.ts'),
  1774. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  1775. );
  1776. fs.writeFileSync(
  1777. path.join(tempDir, 'src/components/PostCard.astro'),
  1778. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  1779. );
  1780. fs.writeFileSync(
  1781. path.join(tempDir, 'src/pages/index.astro'),
  1782. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  1783. );
  1784. cg = await CodeGraph.init(tempDir, { index: true });
  1785. cg.resolveReferences();
  1786. // Hop 1: page → component (template tag through the frontmatter import)
  1787. const cardNode = cg
  1788. .getNodesByKind('component')
  1789. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  1790. expect(cardNode).toBeDefined();
  1791. const cardCallers = cg.getCallers(cardNode!.id);
  1792. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  1793. // Hop 2: component template call → .ts util
  1794. const fmtNode = cg
  1795. .getNodesByKind('function')
  1796. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  1797. expect(fmtNode).toBeDefined();
  1798. const fmtCallers = cg.getCallers(fmtNode!.id);
  1799. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  1800. });
  1801. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  1802. // `import { helper } from '.'` (or './') must map to the
  1803. // directory's index.ts before the re-export chase can run. The
  1804. // barrel renames `realHelper` → `helper` so the name-matcher can't
  1805. // mask a path-resolution failure: only the bare-dir resolution +
  1806. // rename chase can connect the edge.
  1807. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1808. fs.writeFileSync(
  1809. path.join(tempDir, 'src/util.ts'),
  1810. `export function realHelper(): void {}\n`
  1811. );
  1812. fs.writeFileSync(
  1813. path.join(tempDir, 'src/index.ts'),
  1814. `export { realHelper as helper } from './util';\n`
  1815. );
  1816. fs.writeFileSync(
  1817. path.join(tempDir, 'src/main.ts'),
  1818. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  1819. );
  1820. fs.writeFileSync(
  1821. path.join(tempDir, 'src/main2.ts'),
  1822. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  1823. );
  1824. cg = await CodeGraph.init(tempDir, { index: true });
  1825. cg.resolveReferences();
  1826. const helperNode = cg
  1827. .getNodesByKind('function')
  1828. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  1829. expect(helperNode).toBeDefined();
  1830. const callers = cg.getCallers(helperNode!.id);
  1831. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1832. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  1833. });
  1834. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  1835. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  1836. // `widgets/` subdir index, which re-exports a .svelte component.
  1837. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  1838. // only workspace-package resolution can connect the edge.
  1839. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  1840. fs.writeFileSync(
  1841. path.join(tempDir, 'package.json'),
  1842. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  1843. );
  1844. fs.writeFileSync(
  1845. path.join(tempDir, 'packages/ui/package.json'),
  1846. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  1847. );
  1848. fs.writeFileSync(
  1849. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  1850. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1851. );
  1852. fs.writeFileSync(
  1853. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  1854. `export { default as Thing } from './Widget.svelte';\n`
  1855. );
  1856. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  1857. fs.writeFileSync(
  1858. path.join(tempDir, 'app/App.svelte'),
  1859. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  1860. );
  1861. cg = await CodeGraph.init(tempDir, { index: true });
  1862. cg.resolveReferences();
  1863. const buttonNode = cg
  1864. .getNodesByKind('component')
  1865. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  1866. expect(buttonNode).toBeDefined();
  1867. const callers = cg.getCallers(buttonNode!.id);
  1868. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  1869. });
  1870. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  1871. // The same import-resolution gaps (no SFC import mappings, no SFC
  1872. // extension list, barrel parsed in the consumer's language) broke
  1873. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  1874. // The barrel renames `realRun` → `run` so only the import-chase (not
  1875. // the name-matcher) can connect the call.
  1876. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1877. fs.writeFileSync(
  1878. path.join(tempDir, 'src/util.ts'),
  1879. `export function realRun(): void {}\n`
  1880. );
  1881. fs.writeFileSync(
  1882. path.join(tempDir, 'src/index.ts'),
  1883. `export { realRun as run } from './util';\n`
  1884. );
  1885. fs.writeFileSync(
  1886. path.join(tempDir, 'src/App.vue'),
  1887. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  1888. );
  1889. cg = await CodeGraph.init(tempDir, { index: true });
  1890. cg.resolveReferences();
  1891. const runNode = cg
  1892. .getNodesByKind('function')
  1893. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  1894. expect(runNode).toBeDefined();
  1895. const callers = cg.getCallers(runNode!.id);
  1896. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  1897. });
  1898. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  1899. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  1900. // component re-exported under an alias (`Thing`) that differs from its
  1901. // real name (`Widget`), and the consumer uses it ONLY in markup
  1902. // (`<Thing />`). Requires both the new template-tag extraction AND the
  1903. // barrel default-export chase to connect the edge.
  1904. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  1905. fs.writeFileSync(
  1906. path.join(tempDir, 'src/lib/Widget.vue'),
  1907. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  1908. );
  1909. fs.writeFileSync(
  1910. path.join(tempDir, 'src/lib/index.ts'),
  1911. `export { default as Thing } from './Widget.vue';\n`
  1912. );
  1913. fs.writeFileSync(
  1914. path.join(tempDir, 'src/App.vue'),
  1915. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  1916. );
  1917. cg = await CodeGraph.init(tempDir, { index: true });
  1918. cg.resolveReferences();
  1919. const widgetNode = cg
  1920. .getNodesByKind('component')
  1921. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  1922. expect(widgetNode).toBeDefined();
  1923. const callers = cg.getCallers(widgetNode!.id);
  1924. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  1925. });
  1926. });
  1927. describe('C/C++ Import Resolution', () => {
  1928. afterEach(() => {
  1929. clearCppIncludeDirCache();
  1930. });
  1931. it('should resolve C include to header in same directory', () => {
  1932. const context: ResolutionContext = {
  1933. getNodesInFile: () => [],
  1934. getNodesByName: () => [],
  1935. getNodesByQualifiedName: () => [],
  1936. getNodesByKind: () => [],
  1937. fileExists: (p) => p === 'utils.h',
  1938. readFile: () => null,
  1939. getProjectRoot: () => '',
  1940. getAllFiles: () => ['utils.h', 'main.c'],
  1941. };
  1942. const result = resolveImportPath(
  1943. 'utils.h',
  1944. 'main.c',
  1945. 'c',
  1946. context
  1947. );
  1948. expect(result).toBe('utils.h');
  1949. });
  1950. it('should resolve C++ include with .hpp extension', () => {
  1951. const context: ResolutionContext = {
  1952. getNodesInFile: () => [],
  1953. getNodesByName: () => [],
  1954. getNodesByQualifiedName: () => [],
  1955. getNodesByKind: () => [],
  1956. fileExists: (p) => p === 'include/myclass.hpp',
  1957. readFile: () => null,
  1958. getProjectRoot: () => '',
  1959. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  1960. getCppIncludeDirs: () => ['include'],
  1961. };
  1962. const result = resolveImportPath(
  1963. 'myclass.hpp',
  1964. 'src/main.cpp',
  1965. 'cpp',
  1966. context
  1967. );
  1968. expect(result).toBe('include/myclass.hpp');
  1969. });
  1970. it('should resolve include with subdirectory path', () => {
  1971. const context: ResolutionContext = {
  1972. getNodesInFile: () => [],
  1973. getNodesByName: () => [],
  1974. getNodesByQualifiedName: () => [],
  1975. getNodesByKind: () => [],
  1976. fileExists: (p) => p === 'utils/helpers.h',
  1977. readFile: () => null,
  1978. getProjectRoot: () => '',
  1979. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  1980. };
  1981. const result = resolveImportPath(
  1982. 'utils/helpers.h',
  1983. 'main.c',
  1984. 'c',
  1985. context
  1986. );
  1987. expect(result).toBe('utils/helpers.h');
  1988. });
  1989. it('should resolve include via include directories', () => {
  1990. const context: ResolutionContext = {
  1991. getNodesInFile: () => [],
  1992. getNodesByName: () => [],
  1993. getNodesByQualifiedName: () => [],
  1994. getNodesByKind: () => [],
  1995. fileExists: (p) => p === 'include/myheader.h',
  1996. readFile: () => null,
  1997. getProjectRoot: () => '',
  1998. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  1999. getCppIncludeDirs: () => ['include'],
  2000. };
  2001. const result = resolveImportPath(
  2002. 'myheader.h',
  2003. 'src/main.cpp',
  2004. 'cpp',
  2005. context
  2006. );
  2007. expect(result).toBe('include/myheader.h');
  2008. });
  2009. it('should resolve include trying multiple extensions', () => {
  2010. const context: ResolutionContext = {
  2011. getNodesInFile: () => [],
  2012. getNodesByName: () => [],
  2013. getNodesByQualifiedName: () => [],
  2014. getNodesByKind: () => [],
  2015. // myclass.h does not exist, but myclass.hpp does
  2016. fileExists: (p) => p === 'include/myclass.hpp',
  2017. readFile: () => null,
  2018. getProjectRoot: () => '',
  2019. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  2020. getCppIncludeDirs: () => ['include'],
  2021. };
  2022. const result = resolveImportPath(
  2023. 'myclass',
  2024. 'src/main.cpp',
  2025. 'cpp',
  2026. context
  2027. );
  2028. expect(result).toBe('include/myclass.hpp');
  2029. });
  2030. it('should return null for system headers', () => {
  2031. const context: ResolutionContext = {
  2032. getNodesInFile: () => [],
  2033. getNodesByName: () => [],
  2034. getNodesByQualifiedName: () => [],
  2035. getNodesByKind: () => [],
  2036. fileExists: () => true,
  2037. readFile: () => null,
  2038. getProjectRoot: () => '',
  2039. getAllFiles: () => [],
  2040. };
  2041. // C standard library header
  2042. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  2043. // C++ standard library header
  2044. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  2045. // C++ C-wrapper header
  2046. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  2047. });
  2048. it('should return null for single-component third-party paths that cannot be resolved', () => {
  2049. const context: ResolutionContext = {
  2050. getNodesInFile: () => [],
  2051. getNodesByName: () => [],
  2052. getNodesByQualifiedName: () => [],
  2053. getNodesByKind: () => [],
  2054. fileExists: () => false,
  2055. readFile: () => null,
  2056. getProjectRoot: () => '',
  2057. getAllFiles: () => [],
  2058. getCppIncludeDirs: () => [],
  2059. };
  2060. // Third-party bare header without path — not resolvable, returns null
  2061. const result = resolveImportPath(
  2062. 'openssl/ssl.h',
  2063. 'main.cpp',
  2064. 'cpp',
  2065. context
  2066. );
  2067. expect(result).toBeNull();
  2068. });
  2069. it('should not filter project headers with path separators', () => {
  2070. const context: ResolutionContext = {
  2071. getNodesInFile: () => [],
  2072. getNodesByName: () => [],
  2073. getNodesByQualifiedName: () => [],
  2074. getNodesByKind: () => [],
  2075. fileExists: (p) => p === 'mylib/utils.h',
  2076. readFile: () => null,
  2077. getProjectRoot: () => '',
  2078. getAllFiles: () => ['mylib/utils.h'],
  2079. };
  2080. // Path with separator should NOT be filtered as external
  2081. const result = resolveImportPath(
  2082. 'mylib/utils.h',
  2083. 'main.c',
  2084. 'c',
  2085. context
  2086. );
  2087. expect(result).toBe('mylib/utils.h');
  2088. });
  2089. it('should extract C/C++ import mappings from #include directives', () => {
  2090. const code = `#include <iostream>
  2091. #include "myheader.h"
  2092. #include "utils/helpers.hpp"`;
  2093. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  2094. expect(mappings.length).toBe(3);
  2095. expect(mappings[0]).toEqual({
  2096. localName: 'iostream',
  2097. exportedName: '*',
  2098. source: 'iostream',
  2099. isDefault: false,
  2100. isNamespace: true,
  2101. });
  2102. expect(mappings[1]).toEqual({
  2103. localName: 'myheader',
  2104. exportedName: '*',
  2105. source: 'myheader.h',
  2106. isDefault: false,
  2107. isNamespace: true,
  2108. });
  2109. expect(mappings[2]).toEqual({
  2110. localName: 'helpers',
  2111. exportedName: '*',
  2112. source: 'utils/helpers.hpp',
  2113. isDefault: false,
  2114. isNamespace: true,
  2115. });
  2116. });
  2117. it('should discover include directories from compile_commands.json', () => {
  2118. // Create a temp project with compile_commands.json
  2119. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2120. try {
  2121. const compileDb = [
  2122. {
  2123. directory: tempProject,
  2124. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  2125. file: 'src/main.cpp',
  2126. },
  2127. ];
  2128. fs.writeFileSync(
  2129. path.join(tempProject, 'compile_commands.json'),
  2130. JSON.stringify(compileDb)
  2131. );
  2132. // Create the include dirs so they exist
  2133. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2134. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  2135. clearCppIncludeDirCache();
  2136. const dirs = loadCppIncludeDirs(tempProject);
  2137. // Should find include and src/lib (relative to project root)
  2138. // /usr/include is absolute and outside project, should be excluded
  2139. expect(dirs).toContain('include');
  2140. expect(dirs).toContain('src/lib');
  2141. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  2142. } finally {
  2143. fs.rmSync(tempProject, { recursive: true });
  2144. }
  2145. });
  2146. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  2147. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2148. try {
  2149. // Create include/ and src/ directories with headers
  2150. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2151. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  2152. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2153. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  2154. // Create a directory without headers — should not be included
  2155. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  2156. clearCppIncludeDirCache();
  2157. const dirs = loadCppIncludeDirs(tempProject);
  2158. expect(dirs).toContain('include');
  2159. expect(dirs).toContain('src');
  2160. expect(dirs).not.toContain('docs');
  2161. } finally {
  2162. fs.rmSync(tempProject, { recursive: true });
  2163. }
  2164. });
  2165. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  2166. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  2167. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  2168. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  2169. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  2170. // than missing real resolutions. The test pins this so a later
  2171. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  2172. // trade-off explicitly.
  2173. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  2174. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  2175. try {
  2176. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  2177. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  2178. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  2179. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  2180. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  2181. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  2182. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  2183. clearCppIncludeDirCache();
  2184. const dirs = loadCppIncludeDirs(tempProject);
  2185. // Both included — Obj-C dirs are intentionally allowed.
  2186. expect(dirs).toContain('cppmod');
  2187. expect(dirs).toContain('iosmod');
  2188. } finally {
  2189. fs.rmSync(tempProject, { recursive: true });
  2190. }
  2191. });
  2192. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  2193. // in the actual indexing pipeline (not just a phantom file→import-node
  2194. // edge). This pins the include-dir resolution path so the headline PR
  2195. // feature can't silently regress to a no-op in the indexing flow.
  2196. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  2197. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  2198. try {
  2199. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  2200. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2201. fs.writeFileSync(
  2202. path.join(tempProject, 'include', 'utils.h'),
  2203. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  2204. );
  2205. fs.writeFileSync(
  2206. path.join(tempProject, 'src', 'main.cpp'),
  2207. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  2208. );
  2209. clearCppIncludeDirCache();
  2210. cg = await CodeGraph.init(tempProject, { index: true });
  2211. // Sanity: file nodes exist for the header and the cpp.
  2212. const allFiles = cg.getStats();
  2213. expect(allFiles.fileCount).toBe(2);
  2214. // The `#include "utils.h"` edge should target the real
  2215. // `include/utils.h` file node — not a floating `import` node
  2216. // living inside main.cpp.
  2217. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2218. const rows = db.getDb().prepare(`
  2219. select dst.kind as dstKind, dst.file_path as dstPath
  2220. from edges e
  2221. join nodes src on e.source = src.id
  2222. join nodes dst on e.target = dst.id
  2223. where e.kind = 'imports'
  2224. and src.kind = 'file'
  2225. and src.file_path = 'src/main.cpp'
  2226. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2227. const resolvedToHeader = rows.find(
  2228. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  2229. );
  2230. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  2231. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  2232. const stdlibFile = rows.find(
  2233. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  2234. );
  2235. expect(stdlibFile).toBeUndefined();
  2236. } finally {
  2237. fs.rmSync(tempProject, { recursive: true, force: true });
  2238. }
  2239. });
  2240. });
  2241. describe('C++ templated base-class inheritance (#1043)', () => {
  2242. // A class deriving from a TEMPLATE — `class D : public Base<int>` (or a CRTP
  2243. // `class W : public CRTPBase<W>`, or a qualified `class Q : public ns::Tpl<int>`)
  2244. // recorded its base as the full instantiation text (`Base<int>`), which never
  2245. // name-matched the template, indexed as the bare node `Base`. The `<…>` args
  2246. // are now stripped so the `extends` edge resolves end-to-end.
  2247. it('resolves an extends edge to a templated base (plain, CRTP, struct, multi-base)', async () => {
  2248. fs.writeFileSync(
  2249. path.join(tempDir, 'lib.hpp'),
  2250. `#pragma once
  2251. template<typename T> class Base { public: void foo(); };
  2252. template<typename Derived> class CRTPBase {};
  2253. class Plain {};
  2254. class Widget : public Base<int> {}; // plain template base
  2255. class App : public CRTPBase<App> {}; // CRTP (curiously-recurring)
  2256. struct Node : public Base<double> {}; // struct inheriting a template
  2257. class Both : public Base<char>, public Plain {}; // templated + plain in one clause
  2258. `
  2259. );
  2260. cg = await CodeGraph.init(tempDir, { index: true });
  2261. const db = DatabaseConnection.open(path.join(tempDir, '.codegraph', 'codegraph.db'));
  2262. const edges = db
  2263. .getDb()
  2264. .prepare(
  2265. `select src.name as fromName, dst.name as toName
  2266. from edges e
  2267. join nodes src on e.source = src.id
  2268. join nodes dst on e.target = dst.id
  2269. where e.kind = 'extends'`
  2270. )
  2271. .all() as Array<{ fromName: string; toName: string }>;
  2272. const has = (from: string, to: string) =>
  2273. edges.some((r) => r.fromName === from && r.toName === to);
  2274. // Every templated base now resolves to the bare template node.
  2275. expect(has('Widget', 'Base'), 'Widget : Base<int>').toBe(true);
  2276. expect(has('App', 'CRTPBase'), 'App : CRTPBase<App> (CRTP)').toBe(true);
  2277. expect(has('Node', 'Base'), 'struct Node : Base<double>').toBe(true);
  2278. // A mixed clause resolves BOTH the templated and the plain base.
  2279. expect(has('Both', 'Base'), 'Both : Base<char>').toBe(true);
  2280. expect(has('Both', 'Plain'), 'Both : Plain (non-templated, regression guard)').toBe(true);
  2281. });
  2282. });
  2283. describe('PHP Include Resolution', () => {
  2284. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  2285. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  2286. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  2287. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  2288. });
  2289. // include paths: contain a slash or a file extension
  2290. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  2291. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  2292. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  2293. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  2294. // so they must NOT be treated as includes (would mis-connect to a
  2295. // same-named Closure.php / Bar.php file).
  2296. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  2297. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  2298. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  2299. // scoped to PHP imports only
  2300. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  2301. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  2302. });
  2303. it('resolves require_once to a file→file imports edge (#660)', async () => {
  2304. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  2305. try {
  2306. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  2307. fs.writeFileSync(
  2308. path.join(tempProject, 'src', 'lib.php'),
  2309. `<?php\nfunction greet() { return "hi"; }\n`
  2310. );
  2311. fs.writeFileSync(
  2312. path.join(tempProject, 'src', 'page.php'),
  2313. `<?php\nrequire_once("lib.php");\necho greet();\n`
  2314. );
  2315. cg = await CodeGraph.init(tempProject, { index: true });
  2316. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  2317. // to the real src/lib.php file node — a file→file `imports` edge, so
  2318. // callers(lib.php) now includes page.php.
  2319. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2320. const rows = db.getDb().prepare(`
  2321. select dst.kind as dstKind, dst.file_path as dstPath
  2322. from edges e
  2323. join nodes src on e.source = src.id
  2324. join nodes dst on e.target = dst.id
  2325. where e.kind = 'imports'
  2326. and src.kind = 'file'
  2327. and src.file_path = 'src/page.php'
  2328. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2329. const resolved = rows.find(
  2330. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  2331. );
  2332. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  2333. } finally {
  2334. fs.rmSync(tempProject, { recursive: true, force: true });
  2335. }
  2336. });
  2337. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  2338. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  2339. try {
  2340. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  2341. fs.writeFileSync(
  2342. path.join(tempProject, 'inc', 'db.php'),
  2343. `<?php\nfunction query() { return 1; }\n`
  2344. );
  2345. fs.writeFileSync(
  2346. path.join(tempProject, 'index.php'),
  2347. `<?php\nrequire "inc/db.php";\nquery();\n`
  2348. );
  2349. cg = await CodeGraph.init(tempProject, { index: true });
  2350. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2351. const rows = db.getDb().prepare(`
  2352. select dst.kind as dstKind, dst.file_path as dstPath
  2353. from edges e
  2354. join nodes src on e.source = src.id
  2355. join nodes dst on e.target = dst.id
  2356. where e.kind = 'imports'
  2357. and src.kind = 'file'
  2358. and src.file_path = 'index.php'
  2359. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2360. expect(
  2361. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  2362. 'index.php → inc/db.php imports edge missing'
  2363. ).toBeDefined();
  2364. } finally {
  2365. fs.rmSync(tempProject, { recursive: true, force: true });
  2366. }
  2367. });
  2368. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  2369. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  2370. try {
  2371. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  2372. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  2373. // but is unrelated — no edge should be created (a wrong edge is worse
  2374. // than a missing one).
  2375. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  2376. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  2377. fs.writeFileSync(
  2378. path.join(tempProject, 'lib', 'inc', 'db.php'),
  2379. `<?php\nfunction unrelated() {}\n`
  2380. );
  2381. fs.writeFileSync(
  2382. path.join(tempProject, 'app', 'page.php'),
  2383. `<?php\nrequire "inc/db.php";\n`
  2384. );
  2385. cg = await CodeGraph.init(tempProject, { index: true });
  2386. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2387. const rows = db.getDb().prepare(`
  2388. select dst.kind as dstKind, dst.file_path as dstPath
  2389. from edges e
  2390. join nodes src on e.source = src.id
  2391. join nodes dst on e.target = dst.id
  2392. where e.kind = 'imports'
  2393. and src.kind = 'file'
  2394. and src.file_path = 'app/page.php'
  2395. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2396. expect(
  2397. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  2398. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  2399. ).toBeUndefined();
  2400. } finally {
  2401. fs.rmSync(tempProject, { recursive: true, force: true });
  2402. }
  2403. });
  2404. });
  2405. describe('C++ chained-call receiver resolution (#645)', () => {
  2406. async function indexCpp(files: Record<string, string>): Promise<void> {
  2407. for (const [name, content] of Object.entries(files)) {
  2408. fs.writeFileSync(path.join(tempDir, name), content);
  2409. }
  2410. cg = await CodeGraph.init(tempDir, { index: true });
  2411. }
  2412. function callerNamesOf(qualifiedName: string): string[] {
  2413. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2414. if (!target) return [];
  2415. const names = cg
  2416. .getIncomingEdges(target.id)
  2417. .filter((e) => e.kind === 'calls')
  2418. .map((e) => cg.getNode(e.source)?.name)
  2419. .filter((n): n is string => !!n);
  2420. return [...new Set(names)].sort();
  2421. }
  2422. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  2423. // Two classes share writeLog; Logger sorts first so it wins any name-only
  2424. // tie. All three call forms target Metrics.
  2425. await indexCpp({
  2426. 'logger.hpp': `#pragma once
  2427. #include <string>
  2428. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  2429. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  2430. `,
  2431. 'impl.cpp': `#include "logger.hpp"
  2432. Logger& Logger::instance() { static Logger l; return l; }
  2433. Metrics& Metrics::instance() { static Metrics m; return m; }
  2434. void Logger::writeLog(const std::string&) {}
  2435. void Metrics::writeLog(const std::string&) {}
  2436. `,
  2437. 'app.cpp': `#include "logger.hpp"
  2438. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  2439. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  2440. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  2441. `,
  2442. });
  2443. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  2444. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  2445. });
  2446. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  2447. await indexCpp({
  2448. 'types.hpp': `#pragma once
  2449. #include <memory>
  2450. struct Widget { void draw(); };
  2451. struct Session { void run(); };
  2452. struct View { void render(); };
  2453. class WidgetFactory { public: static Widget create(); };
  2454. class Manager { public: View view(); };
  2455. Session* openSession();
  2456. // Decoy that sorts first and has all three methods — must never win.
  2457. struct Aaa { void draw(); void run(); void render(); };
  2458. `,
  2459. 'impl.cpp': `#include "types.hpp"
  2460. void Widget::draw() {}
  2461. void Session::run() {}
  2462. void View::render() {}
  2463. void Aaa::draw() {}
  2464. void Aaa::run() {}
  2465. void Aaa::render() {}
  2466. Widget WidgetFactory::create() { return Widget(); }
  2467. View Manager::view() { return View(); }
  2468. Session* openSession() { return nullptr; }
  2469. `,
  2470. 'app.cpp': `#include "types.hpp"
  2471. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  2472. void freefunc() { openSession()->run(); } // -> Session::run
  2473. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  2474. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  2475. `,
  2476. });
  2477. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  2478. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  2479. expect(callerNamesOf('View::render')).toEqual(['member']);
  2480. // The first-sorted decoy never captures any of them.
  2481. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2482. expect(callerNamesOf('Aaa::run')).toEqual([]);
  2483. expect(callerNamesOf('Aaa::render')).toEqual([]);
  2484. });
  2485. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  2486. await indexCpp({
  2487. 'types.hpp': `#pragma once
  2488. struct Widget { void draw(); };
  2489. struct Other { void onlyOther(); };
  2490. class WidgetFactory { public: static Widget create(); };
  2491. `,
  2492. 'impl.cpp': `#include "types.hpp"
  2493. void Widget::draw() {}
  2494. void Other::onlyOther() {}
  2495. Widget WidgetFactory::create() { return Widget(); }
  2496. `,
  2497. 'app.cpp': `#include "types.hpp"
  2498. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  2499. void wrong() { WidgetFactory::create().onlyOther(); }
  2500. `,
  2501. });
  2502. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2503. });
  2504. });
  2505. describe('PHP chained static-factory call resolution (#608)', () => {
  2506. function callerNamesOf(qualifiedName: string): string[] {
  2507. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2508. if (!target) return [];
  2509. const names = cg
  2510. .getIncomingEdges(target.id)
  2511. .filter((e) => e.kind === 'calls')
  2512. .map((e) => cg.getNode(e.source)?.name)
  2513. .filter((n): n is string => !!n);
  2514. return [...new Set(names)].sort();
  2515. }
  2516. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  2517. fs.writeFileSync(
  2518. path.join(tempDir, 'ApiClient.php'),
  2519. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  2520. );
  2521. fs.writeFileSync(
  2522. path.join(tempDir, 'DispatchOrder.php'),
  2523. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  2524. );
  2525. cg = await CodeGraph.init(tempDir, { index: true });
  2526. // The chained call's edge attaches to the factory result's method.
  2527. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  2528. });
  2529. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  2530. fs.writeFileSync(
  2531. path.join(tempDir, 'lib.php'),
  2532. `<?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`
  2533. );
  2534. cg = await CodeGraph.init(tempDir, { index: true });
  2535. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  2536. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2537. });
  2538. });
  2539. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  2540. function callerNamesOf(qualifiedName: string): string[] {
  2541. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2542. if (!target) return [];
  2543. const names = cg
  2544. .getIncomingEdges(target.id)
  2545. .filter((e) => e.kind === 'calls')
  2546. .map((e) => cg.getNode(e.source)?.name)
  2547. .filter((n): n is string => !!n);
  2548. return [...new Set(names)].sort();
  2549. }
  2550. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  2551. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  2552. fs.writeFileSync(
  2553. path.join(tempDir, 'Main.java'),
  2554. `class Aaa { void bar() {} }
  2555. class Foo {
  2556. static Foo getInstance() { return new Foo(); }
  2557. void bar() {}
  2558. }
  2559. class Caller {
  2560. void run() { Foo.getInstance().bar(); }
  2561. }
  2562. `
  2563. );
  2564. cg = await CodeGraph.init(tempDir, { index: true });
  2565. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2566. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2567. });
  2568. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2569. // The factory call carries an argument; the extractor must normalize the
  2570. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  2571. fs.writeFileSync(
  2572. path.join(tempDir, 'Main.java'),
  2573. `class Config {}
  2574. class Foo {
  2575. static Foo create(Config c) { return new Foo(); }
  2576. void build() {}
  2577. }
  2578. class Caller {
  2579. void run() { Foo.create(new Config()).build(); }
  2580. }
  2581. `
  2582. );
  2583. cg = await CodeGraph.init(tempDir, { index: true });
  2584. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2585. });
  2586. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2587. fs.writeFileSync(
  2588. path.join(tempDir, 'Main.java'),
  2589. `class Foo {
  2590. static Foo getInstance() { return new Foo(); }
  2591. }
  2592. class Other { void onlyOther() {} }
  2593. class Caller {
  2594. void run() { Foo.getInstance().onlyOther(); }
  2595. }
  2596. `
  2597. );
  2598. cg = await CodeGraph.init(tempDir, { index: true });
  2599. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2600. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2601. });
  2602. });
  2603. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  2604. function callerNamesOf(qualifiedName: string): string[] {
  2605. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2606. if (!target) return [];
  2607. const names = cg
  2608. .getIncomingEdges(target.id)
  2609. .filter((e) => e.kind === 'calls')
  2610. .map((e) => cg.getNode(e.source)?.name)
  2611. .filter((n): n is string => !!n);
  2612. return [...new Set(names)].sort();
  2613. }
  2614. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  2615. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  2616. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  2617. fs.writeFileSync(
  2618. path.join(tempDir, 'Main.kt'),
  2619. `class Aaa { fun bar() {} }
  2620. class Foo {
  2621. companion object {
  2622. fun getInstance(): Foo = Foo()
  2623. }
  2624. fun bar() {}
  2625. }
  2626. class Caller {
  2627. fun run() { Foo.getInstance().bar() }
  2628. }
  2629. `
  2630. );
  2631. cg = await CodeGraph.init(tempDir, { index: true });
  2632. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2633. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2634. });
  2635. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2636. fs.writeFileSync(
  2637. path.join(tempDir, 'Main.kt'),
  2638. `class Config
  2639. class Foo {
  2640. companion object {
  2641. fun create(c: Config): Foo = Foo()
  2642. }
  2643. fun build() {}
  2644. }
  2645. class Caller {
  2646. fun run() { Foo.create(Config()).build() }
  2647. }
  2648. `
  2649. );
  2650. cg = await CodeGraph.init(tempDir, { index: true });
  2651. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2652. });
  2653. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  2654. fs.writeFileSync(
  2655. path.join(tempDir, 'Main.kt'),
  2656. `class Foo {
  2657. companion object {
  2658. fun getInstance(): Foo = Foo()
  2659. }
  2660. }
  2661. class Other { fun onlyOther() {} }
  2662. class Caller {
  2663. fun run() { Foo.getInstance().onlyOther() }
  2664. }
  2665. `
  2666. );
  2667. cg = await CodeGraph.init(tempDir, { index: true });
  2668. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2669. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2670. });
  2671. });
  2672. describe('C# chained static-factory call resolution (#645/#608 mechanism)', () => {
  2673. function callerNamesOf(qualifiedName: string): string[] {
  2674. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2675. if (!target) return [];
  2676. const names = cg
  2677. .getIncomingEdges(target.id)
  2678. .filter((e) => e.kind === 'calls')
  2679. .map((e) => cg.getNode(e.source)?.name)
  2680. .filter((n): n is string => !!n);
  2681. return [...new Set(names)].sort();
  2682. }
  2683. it('resolves Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  2684. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  2685. fs.writeFileSync(
  2686. path.join(tempDir, 'Main.cs'),
  2687. `class Aaa { void Bar() {} }
  2688. class Foo {
  2689. static Foo Create() { return new Foo(); }
  2690. void Bar() {}
  2691. }
  2692. class Caller {
  2693. void Run() { Foo.Create().Bar(); }
  2694. }
  2695. `
  2696. );
  2697. cg = await CodeGraph.init(tempDir, { index: true });
  2698. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  2699. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  2700. });
  2701. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  2702. fs.writeFileSync(
  2703. path.join(tempDir, 'Main.cs'),
  2704. `class Config {}
  2705. class Foo {
  2706. static Foo Make(Config c) { return new Foo(); }
  2707. void Build() {}
  2708. }
  2709. class Caller {
  2710. void Run() { Foo.Make(new Config()).Build(); }
  2711. }
  2712. `
  2713. );
  2714. cg = await CodeGraph.init(tempDir, { index: true });
  2715. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  2716. });
  2717. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2718. fs.writeFileSync(
  2719. path.join(tempDir, 'Main.cs'),
  2720. `class Foo {
  2721. static Foo Create() { return new Foo(); }
  2722. }
  2723. class Other { void OnlyOther() {} }
  2724. class Caller {
  2725. void Run() { Foo.Create().OnlyOther(); }
  2726. }
  2727. `
  2728. );
  2729. cg = await CodeGraph.init(tempDir, { index: true });
  2730. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  2731. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  2732. });
  2733. });
  2734. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  2735. function callerNamesOf(qualifiedName: string): string[] {
  2736. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2737. if (!target) return [];
  2738. const names = cg
  2739. .getIncomingEdges(target.id)
  2740. .filter((e) => e.kind === 'calls')
  2741. .map((e) => cg.getNode(e.source)?.name)
  2742. .filter((n): n is string => !!n);
  2743. return [...new Set(names)].sort();
  2744. }
  2745. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  2746. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  2747. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  2748. fs.writeFileSync(
  2749. path.join(tempDir, 'Main.swift'),
  2750. `class Aaa { func draw() {} }
  2751. class Foo {
  2752. static func make() -> Foo { return Foo() }
  2753. func draw() {}
  2754. }
  2755. func runCaller() { Foo.make().draw() }
  2756. `
  2757. );
  2758. cg = await CodeGraph.init(tempDir, { index: true });
  2759. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2760. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2761. });
  2762. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  2763. fs.writeFileSync(
  2764. path.join(tempDir, 'Main.swift'),
  2765. `class Config {}
  2766. class Foo {
  2767. static func build(_ c: Config) -> Foo { return Foo() }
  2768. func draw() {}
  2769. func render() {}
  2770. }
  2771. func runCaller() {
  2772. Foo().draw()
  2773. Foo.build(Config()).render()
  2774. }
  2775. `
  2776. );
  2777. cg = await CodeGraph.init(tempDir, { index: true });
  2778. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2779. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  2780. });
  2781. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2782. fs.writeFileSync(
  2783. path.join(tempDir, 'Main.swift'),
  2784. `class Foo {
  2785. static func make() -> Foo { return Foo() }
  2786. }
  2787. class Other { func onlyOther() {} }
  2788. func runCaller() { Foo.make().onlyOther() }
  2789. `
  2790. );
  2791. cg = await CodeGraph.init(tempDir, { index: true });
  2792. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2793. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2794. });
  2795. });
  2796. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  2797. function callerNamesOf(qualifiedName: string): string[] {
  2798. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2799. if (!target) return [];
  2800. const names = cg
  2801. .getIncomingEdges(target.id)
  2802. .filter((e) => e.kind === 'calls')
  2803. .map((e) => cg.getNode(e.source)?.name)
  2804. .filter((n): n is string => !!n);
  2805. return [...new Set(names)].sort();
  2806. }
  2807. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  2808. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  2809. // its own. Decoy.draw must never win. Needs the conformance second pass.
  2810. fs.writeFileSync(
  2811. path.join(tempDir, 'Main.java'),
  2812. `class Base { void draw() {} }
  2813. class Widget extends Base {}
  2814. class Decoy { void draw() {} }
  2815. class Factory { static Widget create() { return new Widget(); } }
  2816. class Caller {
  2817. void run() { Factory.create().draw(); }
  2818. }
  2819. `
  2820. );
  2821. cg = await CodeGraph.init(tempDir, { index: true });
  2822. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  2823. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2824. });
  2825. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  2826. fs.writeFileSync(
  2827. path.join(tempDir, 'Main.java'),
  2828. `interface Drawable { default void draw() {} }
  2829. class Widget implements Drawable {}
  2830. class Decoy { void draw() {} }
  2831. class Factory { static Widget create() { return new Widget(); } }
  2832. class Caller {
  2833. void run() { Factory.create().draw(); }
  2834. }
  2835. `
  2836. );
  2837. cg = await CodeGraph.init(tempDir, { index: true });
  2838. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  2839. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2840. });
  2841. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  2842. fs.writeFileSync(
  2843. path.join(tempDir, 'Main.java'),
  2844. `class Base {}
  2845. class Widget extends Base {}
  2846. class Other { void onlyOther() {} }
  2847. class Factory { static Widget create() { return new Widget(); } }
  2848. class Caller {
  2849. void run() { Factory.create().onlyOther(); }
  2850. }
  2851. `
  2852. );
  2853. cg = await CodeGraph.init(tempDir, { index: true });
  2854. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  2855. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2856. });
  2857. });
  2858. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  2859. function callerNamesOf(qualifiedName: string): string[] {
  2860. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2861. if (!target) return [];
  2862. const names = cg
  2863. .getIncomingEdges(target.id)
  2864. .filter((e) => e.kind === 'calls')
  2865. .map((e) => cg.getNode(e.source)?.name)
  2866. .filter((n): n is string => !!n);
  2867. return [...new Set(names)].sort();
  2868. }
  2869. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  2870. fs.writeFileSync(
  2871. path.join(tempDir, 'main.rs'),
  2872. `struct Aaa { _x: i32 }
  2873. impl Aaa { fn bar(&self) {} }
  2874. struct Foo { _x: i32 }
  2875. impl Foo {
  2876. fn new() -> Foo { Foo { _x: 0 } }
  2877. fn make() -> Self { Foo { _x: 0 } }
  2878. fn bar(&self) {}
  2879. }
  2880. fn caller() {
  2881. Foo::new().bar();
  2882. Foo::make().bar();
  2883. }
  2884. `
  2885. );
  2886. cg = await CodeGraph.init(tempDir, { index: true });
  2887. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  2888. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2889. });
  2890. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  2891. fs.writeFileSync(
  2892. path.join(tempDir, 'main.rs'),
  2893. `struct Config;
  2894. struct Foo { _x: i32 }
  2895. impl Foo {
  2896. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  2897. fn build(&self) {}
  2898. }
  2899. fn caller() { Foo::with(Config).build(); }
  2900. `
  2901. );
  2902. cg = await CodeGraph.init(tempDir, { index: true });
  2903. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  2904. });
  2905. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  2906. fs.writeFileSync(
  2907. path.join(tempDir, 'main.rs'),
  2908. `struct Foo { _x: i32 }
  2909. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  2910. struct Decoy { _x: i32 }
  2911. impl Decoy { fn draw(&self) {} }
  2912. trait Drawable { fn draw(&self) {} }
  2913. impl Drawable for Foo {}
  2914. fn caller() { Foo::new().draw(); }
  2915. `
  2916. );
  2917. cg = await CodeGraph.init(tempDir, { index: true });
  2918. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  2919. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2920. });
  2921. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  2922. fs.writeFileSync(
  2923. path.join(tempDir, 'main.rs'),
  2924. `struct Foo { _x: i32 }
  2925. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  2926. struct Other { _x: i32 }
  2927. impl Other { fn only_other(&self) {} }
  2928. fn caller() { Foo::new().only_other(); }
  2929. `
  2930. );
  2931. cg = await CodeGraph.init(tempDir, { index: true });
  2932. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  2933. expect(callerNamesOf('Other::only_other')).toEqual([]);
  2934. });
  2935. });
  2936. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  2937. function callerNamesOf(qualifiedName: string): string[] {
  2938. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2939. if (!target) return [];
  2940. const names = cg
  2941. .getIncomingEdges(target.id)
  2942. .filter((e) => e.kind === 'calls')
  2943. .map((e) => cg.getNode(e.source)?.name)
  2944. .filter((n): n is string => !!n);
  2945. return [...new Set(names)].sort();
  2946. }
  2947. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  2948. fs.writeFileSync(
  2949. path.join(tempDir, 'main.go'),
  2950. `package main
  2951. type Aaa struct{}
  2952. func (a *Aaa) Bar() {}
  2953. type Foo struct{}
  2954. func New() *Foo { return &Foo{} }
  2955. func (f *Foo) Bar() {}
  2956. func caller() { New().Bar() }
  2957. `
  2958. );
  2959. cg = await CodeGraph.init(tempDir, { index: true });
  2960. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  2961. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  2962. });
  2963. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  2964. fs.writeFileSync(
  2965. path.join(tempDir, 'main.go'),
  2966. `package main
  2967. type Config struct{}
  2968. type Foo struct{}
  2969. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  2970. func (f *Foo) Build() {}
  2971. func caller() { With(Config{}).Build() }
  2972. `
  2973. );
  2974. cg = await CodeGraph.init(tempDir, { index: true });
  2975. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  2976. });
  2977. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  2978. fs.writeFileSync(
  2979. path.join(tempDir, 'main.go'),
  2980. `package main
  2981. type Base struct{}
  2982. func (b *Base) Embedded() {}
  2983. type Decoy struct{}
  2984. func (d *Decoy) Embedded() {}
  2985. type Widget struct{ Base }
  2986. func NewWidget() *Widget { return &Widget{} }
  2987. func caller() { NewWidget().Embedded() }
  2988. `
  2989. );
  2990. cg = await CodeGraph.init(tempDir, { index: true });
  2991. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  2992. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  2993. });
  2994. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  2995. fs.writeFileSync(
  2996. path.join(tempDir, 'main.go'),
  2997. `package main
  2998. type Foo struct{}
  2999. func New() *Foo { return &Foo{} }
  3000. type Other struct{}
  3001. func (o *Other) OnlyOther() {}
  3002. func caller() { New().OnlyOther() }
  3003. `
  3004. );
  3005. cg = await CodeGraph.init(tempDir, { index: true });
  3006. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  3007. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  3008. });
  3009. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  3010. // `engine` is a package-level VARIABLE holding a func value, not a factory
  3011. // FUNCTION — so its return type can't be recovered and the chain falls back
  3012. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  3013. // Regression for the runaway this fallback originally caused: it resolved
  3014. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  3015. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  3016. // no-oped, the offset-0 batch never drained, and edges inserted forever
  3017. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  3018. // the original ref, and a non-progress guard backstops the loop.
  3019. fs.writeFileSync(
  3020. path.join(tempDir, 'main.go'),
  3021. `package main
  3022. type Server struct{}
  3023. func (s *Server) ServeHTTP() {}
  3024. var engine = func() *Server { return &Server{} }
  3025. func caller() { engine().ServeHTTP() }
  3026. `
  3027. );
  3028. cg = await CodeGraph.init(tempDir, { index: true });
  3029. // Recall: the variable-inner chain still finds the method by bare name.
  3030. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  3031. // No runaway: a single call site yields a single edge, not millions.
  3032. const target = cg
  3033. .getNodesByKind('method')
  3034. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  3035. const rawCalls = cg
  3036. .getIncomingEdges(target.id)
  3037. .filter((e) => e.kind === 'calls');
  3038. expect(rawCalls.length).toBeLessThan(5);
  3039. });
  3040. });
  3041. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  3042. function callerNamesOf(qualifiedName: string): string[] {
  3043. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3044. if (!target) return [];
  3045. const names = cg
  3046. .getIncomingEdges(target.id)
  3047. .filter((e) => e.kind === 'calls')
  3048. .map((e) => cg.getNode(e.source)?.name)
  3049. .filter((n): n is string => !!n);
  3050. return [...new Set(names)].sort();
  3051. }
  3052. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  3053. fs.writeFileSync(
  3054. path.join(tempDir, 'Main.scala'),
  3055. `object Foo {
  3056. def create(): Bar = new Bar()
  3057. }
  3058. class Bar {
  3059. def doIt(): Unit = {}
  3060. }
  3061. class Decoy {
  3062. def doIt(): Unit = {}
  3063. }
  3064. object Main {
  3065. def run(): Unit = { Foo.create().doIt() }
  3066. }
  3067. `
  3068. );
  3069. cg = await CodeGraph.init(tempDir, { index: true });
  3070. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3071. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3072. });
  3073. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  3074. fs.writeFileSync(
  3075. path.join(tempDir, 'Main.scala'),
  3076. `class Point(x: Int) {
  3077. def dist(): Int = x
  3078. }
  3079. class Other {
  3080. def dist(): Int = 0
  3081. }
  3082. object Main {
  3083. def run(): Unit = { Point(3).dist() }
  3084. }
  3085. `
  3086. );
  3087. cg = await CodeGraph.init(tempDir, { index: true });
  3088. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  3089. expect(callerNamesOf('Other::dist')).toEqual([]);
  3090. });
  3091. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  3092. fs.writeFileSync(
  3093. path.join(tempDir, 'Main.scala'),
  3094. `trait Base {
  3095. def shared(): Unit = {}
  3096. }
  3097. class Widget extends Base
  3098. class Decoy {
  3099. def shared(): Unit = {}
  3100. }
  3101. object Factory {
  3102. def make(): Widget = new Widget()
  3103. }
  3104. object Main {
  3105. def run(): Unit = { Factory.make().shared() }
  3106. }
  3107. `
  3108. );
  3109. cg = await CodeGraph.init(tempDir, { index: true });
  3110. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  3111. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  3112. });
  3113. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3114. fs.writeFileSync(
  3115. path.join(tempDir, 'Main.scala'),
  3116. `object Foo {
  3117. def create(): Bar = new Bar()
  3118. }
  3119. class Bar {
  3120. }
  3121. class Other {
  3122. def onlyOther(): Unit = {}
  3123. }
  3124. object Main {
  3125. def run(): Unit = { Foo.create().onlyOther() }
  3126. }
  3127. `
  3128. );
  3129. cg = await CodeGraph.init(tempDir, { index: true });
  3130. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3131. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3132. });
  3133. });
  3134. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  3135. function callerNamesOf(qualifiedName: string): string[] {
  3136. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3137. if (!target) return [];
  3138. const names = cg
  3139. .getIncomingEdges(target.id)
  3140. .filter((e) => e.kind === 'calls')
  3141. .map((e) => cg.getNode(e.source)?.name)
  3142. .filter((n): n is string => !!n);
  3143. return [...new Set(names)].sort();
  3144. }
  3145. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  3146. fs.writeFileSync(
  3147. path.join(tempDir, 'main.dart'),
  3148. `class Foo {
  3149. static Bar makeBar() => Bar();
  3150. }
  3151. class Bar {
  3152. void doIt() {}
  3153. }
  3154. class Decoy {
  3155. void doIt() {}
  3156. }
  3157. void run() {
  3158. Foo.makeBar().doIt();
  3159. }
  3160. `
  3161. );
  3162. cg = await CodeGraph.init(tempDir, { index: true });
  3163. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3164. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3165. });
  3166. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  3167. fs.writeFileSync(
  3168. path.join(tempDir, 'main.dart'),
  3169. `class Foo {
  3170. Foo._();
  3171. factory Foo.create() => Foo._();
  3172. void ship() {}
  3173. }
  3174. class Decoy {
  3175. void ship() {}
  3176. }
  3177. void run() {
  3178. Foo.create().ship();
  3179. }
  3180. `
  3181. );
  3182. cg = await CodeGraph.init(tempDir, { index: true });
  3183. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  3184. // so `ship` resolves on Foo, not the same-named Decoy.
  3185. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  3186. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  3187. });
  3188. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  3189. fs.writeFileSync(
  3190. path.join(tempDir, 'main.dart'),
  3191. `class Bar {
  3192. void doIt() {}
  3193. }
  3194. class Decoy {
  3195. void doIt() {}
  3196. }
  3197. void run() {
  3198. Bar().doIt();
  3199. }
  3200. `
  3201. );
  3202. cg = await CodeGraph.init(tempDir, { index: true });
  3203. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3204. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3205. });
  3206. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  3207. fs.writeFileSync(
  3208. path.join(tempDir, 'main.dart'),
  3209. `class Base {
  3210. void render() {}
  3211. }
  3212. class Widget extends Base {
  3213. static Widget make() => Widget();
  3214. }
  3215. class Decoy {
  3216. void render() {}
  3217. }
  3218. void run() {
  3219. Widget.make().render();
  3220. }
  3221. `
  3222. );
  3223. cg = await CodeGraph.init(tempDir, { index: true });
  3224. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3225. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3226. });
  3227. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  3228. fs.writeFileSync(
  3229. path.join(tempDir, 'main.dart'),
  3230. `class Foo {
  3231. static Bar makeBar() => Bar();
  3232. }
  3233. class Bar {
  3234. }
  3235. class Other {
  3236. void onlyOther() {}
  3237. }
  3238. void run() {
  3239. Foo.makeBar().onlyOther();
  3240. }
  3241. `
  3242. );
  3243. cg = await CodeGraph.init(tempDir, { index: true });
  3244. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  3245. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3246. });
  3247. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  3248. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  3249. // swallows the record return type, so `reduce()` looks like a single-
  3250. // identifier constructor_signature. It must NOT be skipped as an unnamed
  3251. // ctor (its name doesn't match the class); its body call must attribute to
  3252. // `reduce`, not the class.
  3253. fs.writeFileSync(
  3254. path.join(tempDir, 'main.dart'),
  3255. `class Base {}
  3256. class Action extends Base {
  3257. Action({required int x});
  3258. @override
  3259. (int, String) reduce() {
  3260. return (compute(), "y");
  3261. }
  3262. int compute() => 1;
  3263. }
  3264. `
  3265. );
  3266. cg = await CodeGraph.init(tempDir, { index: true });
  3267. // reduce must be a node and its body call must resolve to Action::compute.
  3268. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  3269. });
  3270. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  3271. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  3272. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  3273. // never hijacked into a call to a phantom constructor method.
  3274. fs.writeFileSync(
  3275. path.join(tempDir, 'main.dart'),
  3276. `class Widget {
  3277. final int x;
  3278. Widget(this.x);
  3279. }
  3280. void run() {
  3281. Widget(3);
  3282. }
  3283. `
  3284. );
  3285. cg = await CodeGraph.init(tempDir, { index: true });
  3286. // No Foo::Foo phantom method node.
  3287. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  3288. // The construction resolves to the class as an `instantiates` edge.
  3289. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  3290. const incoming = cg.getIncomingEdges(widget.id);
  3291. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  3292. });
  3293. });
  3294. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  3295. function callerNamesOf(qualifiedName: string): string[] {
  3296. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3297. if (!target) return [];
  3298. const names = cg
  3299. .getIncomingEdges(target.id)
  3300. .filter((e) => e.kind === 'calls')
  3301. .map((e) => cg.getNode(e.source)?.name)
  3302. .filter((n): n is string => !!n);
  3303. return [...new Set(names)].sort();
  3304. }
  3305. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  3306. fs.writeFileSync(
  3307. path.join(tempDir, 'main.m'),
  3308. `@interface Bar : NSObject
  3309. - (void)doIt;
  3310. @end
  3311. @implementation Bar
  3312. - (void)doIt {}
  3313. @end
  3314. @interface Decoy : NSObject
  3315. - (void)doIt;
  3316. @end
  3317. @implementation Decoy
  3318. - (void)doIt {}
  3319. @end
  3320. @interface Foo : NSObject
  3321. + (Bar *)create;
  3322. @end
  3323. @implementation Foo
  3324. + (Bar *)create { return nil; }
  3325. - (void)run { [[Foo create] doIt]; }
  3326. @end
  3327. `
  3328. );
  3329. cg = await CodeGraph.init(tempDir, { index: true });
  3330. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  3331. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  3332. });
  3333. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  3334. fs.writeFileSync(
  3335. path.join(tempDir, 'main.m'),
  3336. `@interface Base : NSObject
  3337. - (void)render;
  3338. @end
  3339. @implementation Base
  3340. - (void)render {}
  3341. @end
  3342. @interface Widget : Base
  3343. @end
  3344. @implementation Widget
  3345. @end
  3346. @interface Decoy : NSObject
  3347. - (void)render;
  3348. @end
  3349. @implementation Decoy
  3350. - (void)render {}
  3351. @end
  3352. @interface Factory : NSObject
  3353. + (Widget *)make;
  3354. @end
  3355. @implementation Factory
  3356. + (Widget *)make { return nil; }
  3357. - (void)run { [[Factory make] render]; }
  3358. @end
  3359. `
  3360. );
  3361. cg = await CodeGraph.init(tempDir, { index: true });
  3362. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3363. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3364. });
  3365. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3366. fs.writeFileSync(
  3367. path.join(tempDir, 'main.m'),
  3368. `@interface Bar : NSObject
  3369. @end
  3370. @implementation Bar
  3371. @end
  3372. @interface Other : NSObject
  3373. - (void)onlyOther;
  3374. @end
  3375. @implementation Other
  3376. - (void)onlyOther {}
  3377. @end
  3378. @interface Foo : NSObject
  3379. + (Bar *)create;
  3380. @end
  3381. @implementation Foo
  3382. + (Bar *)create { return nil; }
  3383. - (void)run { [[Foo create] onlyOther]; }
  3384. @end
  3385. `
  3386. );
  3387. cg = await CodeGraph.init(tempDir, { index: true });
  3388. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3389. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3390. });
  3391. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  3392. // The factory returns `nonnull instancetype` — the nullability qualifier must
  3393. // be skipped (not captured AS the type), and an instancetype class-message
  3394. // factory returns the receiver class, so clearAll resolves on Cache, never a
  3395. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  3396. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  3397. fs.writeFileSync(
  3398. path.join(tempDir, 'main.m'),
  3399. `@interface Cache : NSObject
  3400. + (nonnull instancetype)shared;
  3401. - (void)clearAll;
  3402. @end
  3403. @implementation Cache
  3404. + (nonnull instancetype)shared { return nil; }
  3405. - (void)clearAll {}
  3406. @end
  3407. @interface Decoy : NSObject
  3408. - (void)clearAll;
  3409. @end
  3410. @implementation Decoy
  3411. - (void)clearAll {}
  3412. @end
  3413. @interface Caller : NSObject
  3414. - (void)run;
  3415. @end
  3416. @implementation Caller
  3417. - (void)run { [[Cache shared] clearAll]; }
  3418. @end
  3419. `
  3420. );
  3421. cg = await CodeGraph.init(tempDir, { index: true });
  3422. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  3423. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  3424. });
  3425. });
  3426. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  3427. function callerNamesOf(qualifiedName: string): string[] {
  3428. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3429. if (!target) return [];
  3430. const names = cg
  3431. .getIncomingEdges(target.id)
  3432. .filter((e) => e.kind === 'calls')
  3433. .map((e) => cg.getNode(e.source)?.name)
  3434. .filter((n): n is string => !!n);
  3435. return [...new Set(names)].sort();
  3436. }
  3437. function isCalled(qn: string): boolean {
  3438. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  3439. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  3440. }
  3441. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  3442. fs.writeFileSync(
  3443. path.join(tempDir, 'main.pas'),
  3444. `unit Main;
  3445. interface
  3446. type
  3447. TBar = class
  3448. procedure DoIt;
  3449. end;
  3450. TDecoy = class
  3451. procedure DoIt;
  3452. end;
  3453. TFoo = class
  3454. class function GetInstance: TBar;
  3455. end;
  3456. implementation
  3457. procedure TBar.DoIt; begin end;
  3458. procedure TDecoy.DoIt; begin end;
  3459. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3460. procedure Run;
  3461. begin
  3462. TFoo.GetInstance().DoIt();
  3463. end;
  3464. end.
  3465. `
  3466. );
  3467. cg = await CodeGraph.init(tempDir, { index: true });
  3468. expect(isCalled('TBar::DoIt')).toBe(true);
  3469. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3470. });
  3471. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  3472. fs.writeFileSync(
  3473. path.join(tempDir, 'main.pas'),
  3474. `unit Main;
  3475. interface
  3476. type
  3477. TFoo = class
  3478. constructor Create;
  3479. procedure Configure;
  3480. end;
  3481. TDecoy = class
  3482. procedure Configure;
  3483. end;
  3484. implementation
  3485. constructor TFoo.Create; begin end;
  3486. procedure TFoo.Configure; begin end;
  3487. procedure TDecoy.Configure; begin end;
  3488. procedure Run;
  3489. begin
  3490. TFoo.Create().Configure();
  3491. end;
  3492. end.
  3493. `
  3494. );
  3495. cg = await CodeGraph.init(tempDir, { index: true });
  3496. // A constructor returns its own class (no `: TBar` annotation), so Configure
  3497. // resolves on TFoo, not the same-named decoy.
  3498. expect(isCalled('TFoo::Configure')).toBe(true);
  3499. expect(isCalled('TDecoy::Configure')).toBe(false);
  3500. });
  3501. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  3502. fs.writeFileSync(
  3503. path.join(tempDir, 'main.pas'),
  3504. `unit Main;
  3505. interface
  3506. type
  3507. TFoo = class
  3508. procedure DoIt;
  3509. end;
  3510. TDecoy = class
  3511. procedure DoIt;
  3512. end;
  3513. implementation
  3514. procedure TFoo.DoIt; begin end;
  3515. procedure TDecoy.DoIt; begin end;
  3516. procedure Run(obj: TObject);
  3517. begin
  3518. TFoo(obj).DoIt();
  3519. end;
  3520. end.
  3521. `
  3522. );
  3523. cg = await CodeGraph.init(tempDir, { index: true });
  3524. expect(isCalled('TFoo::DoIt')).toBe(true);
  3525. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3526. });
  3527. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3528. fs.writeFileSync(
  3529. path.join(tempDir, 'main.pas'),
  3530. `unit Main;
  3531. interface
  3532. type
  3533. TBar = class
  3534. end;
  3535. TOther = class
  3536. procedure OnlyOther;
  3537. end;
  3538. TFoo = class
  3539. class function GetInstance: TBar;
  3540. end;
  3541. implementation
  3542. procedure TOther.OnlyOther; begin end;
  3543. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3544. procedure Run;
  3545. begin
  3546. TFoo.GetInstance().OnlyOther();
  3547. end;
  3548. end.
  3549. `
  3550. );
  3551. cg = await CodeGraph.init(tempDir, { index: true });
  3552. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  3553. expect(isCalled('TOther::OnlyOther')).toBe(false);
  3554. });
  3555. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  3556. fs.writeFileSync(
  3557. path.join(tempDir, 'main.pas'),
  3558. `unit Main;
  3559. interface
  3560. type
  3561. TFoo = class
  3562. procedure DoThing;
  3563. procedure Reset;
  3564. end;
  3565. implementation
  3566. procedure TFoo.DoThing; begin end;
  3567. procedure TFoo.Reset; begin end;
  3568. procedure Run(f: TFoo);
  3569. begin
  3570. f.DoThing;
  3571. f.Reset;
  3572. end;
  3573. end.
  3574. `
  3575. );
  3576. cg = await CodeGraph.init(tempDir, { index: true });
  3577. expect(isCalled('TFoo::DoThing')).toBe(true);
  3578. expect(isCalled('TFoo::Reset')).toBe(true);
  3579. });
  3580. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  3581. fs.writeFileSync(
  3582. path.join(tempDir, 'main.pas'),
  3583. `unit Main;
  3584. interface
  3585. type
  3586. TBar = class
  3587. procedure DoIt;
  3588. end;
  3589. TDecoy = class
  3590. procedure DoIt;
  3591. end;
  3592. TFoo = class
  3593. class function GetInstance: TBar;
  3594. end;
  3595. implementation
  3596. procedure TBar.DoIt; begin end;
  3597. procedure TDecoy.DoIt; begin end;
  3598. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3599. procedure Run;
  3600. begin
  3601. TFoo.GetInstance.DoIt;
  3602. end;
  3603. end.
  3604. `
  3605. );
  3606. cg = await CodeGraph.init(tempDir, { index: true });
  3607. expect(isCalled('TBar::DoIt')).toBe(true);
  3608. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3609. });
  3610. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  3611. fs.writeFileSync(
  3612. path.join(tempDir, 'main.pas'),
  3613. `unit Main;
  3614. interface
  3615. type
  3616. TFoo = class
  3617. function GetValue: Integer;
  3618. procedure SetValue(v: Integer);
  3619. property Value: Integer read GetValue write SetValue;
  3620. end;
  3621. implementation
  3622. function TFoo.GetValue: Integer; begin Result := 0; end;
  3623. procedure TFoo.SetValue(v: Integer); begin end;
  3624. procedure Run(f: TFoo);
  3625. var x: Integer;
  3626. begin
  3627. f.Value := 5;
  3628. x := f.Value;
  3629. end;
  3630. end.
  3631. `
  3632. );
  3633. cg = await CodeGraph.init(tempDir, { index: true });
  3634. // A property read/write is a bare dot in assignment position, not a statement,
  3635. // so it must not be mis-extracted as a call to the property's getter/setter.
  3636. expect(isCalled('TFoo::GetValue')).toBe(false);
  3637. expect(isCalled('TFoo::SetValue')).toBe(false);
  3638. });
  3639. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  3640. fs.writeFileSync(
  3641. path.join(tempDir, 'main.pas'),
  3642. `unit Main;
  3643. interface
  3644. type
  3645. TTgt = class
  3646. procedure Hit;
  3647. end;
  3648. TFoo = class
  3649. procedure DoStuff;
  3650. end;
  3651. implementation
  3652. procedure TTgt.Hit; begin end;
  3653. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  3654. procedure Helper; var t: TTgt; begin t.Hit; end;
  3655. `
  3656. );
  3657. cg = await CodeGraph.init(tempDir, { index: true });
  3658. // `Helper` is implementation-only (no interface decl, not a method), but its
  3659. // body's call must attribute to `Helper`, not the file/module — alongside the
  3660. // method `DoStuff`.
  3661. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  3662. });
  3663. });
  3664. });