resolution.test.ts 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635
  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 } 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('resolves a cross-file static method call to the method, not the class (#825)', async () => {
  837. // `Foo.bar()` where `Foo` is an imported class must link to the static
  838. // method `Foo::bar`, NOT to the class `Foo`. Previously the import
  839. // resolver dropped the `.bar` member and resolved to `Foo`, which the
  840. // calls→instantiates promotion then turned into `run instantiates Foo`,
  841. // leaving the static method with zero callers and a hollow impact radius.
  842. fs.writeFileSync(
  843. path.join(tempDir, 'helpers.ts'),
  844. `export class Foo {\n static bar(x: number) { return x + 1; }\n}\n`
  845. );
  846. fs.writeFileSync(
  847. path.join(tempDir, 'caller.ts'),
  848. `import { Foo } from './helpers';\nexport function run() { return Foo.bar(41); }\n`
  849. );
  850. cg = await CodeGraph.init(tempDir, { index: true });
  851. cg.resolveReferences();
  852. const bar = cg.getNodesByKind('method').find((n) => n.name === 'bar');
  853. const foo = cg.getNodesByKind('class').find((n) => n.name === 'Foo');
  854. const run = cg.getNodesByKind('function').find((n) => n.name === 'run');
  855. expect(bar).toBeDefined();
  856. expect(foo).toBeDefined();
  857. expect(run).toBeDefined();
  858. // `run` is reported as a caller of the static method `Foo.bar`.
  859. const barCallers = cg.getCallers(bar!.id).map((c) => c.node.name);
  860. expect(barCallers).toContain('run');
  861. // And the call is NOT mis-promoted to `run instantiates Foo`.
  862. const outgoing = cg.getOutgoingEdges(run!.id);
  863. expect(
  864. outgoing.filter((e) => e.kind === 'instantiates' && e.target === foo!.id)
  865. ).toHaveLength(0);
  866. // The real edge is a `calls` edge to the method.
  867. expect(
  868. outgoing.some((e) => e.kind === 'calls' && e.target === bar!.id)
  869. ).toBe(true);
  870. });
  871. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  872. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  873. // external (isExternalImport returned true for any non-`/internal/`
  874. // import without `.`-prefix) and resolution fell through to name-match
  875. // with path proximity — recall on cross-package callers was ~<1%.
  876. fs.writeFileSync(
  877. path.join(tempDir, 'go.mod'),
  878. 'module github.com/example/myproject\n\ngo 1.21\n'
  879. );
  880. const pkgaDir = path.join(tempDir, 'pkga');
  881. const pkgbDir = path.join(tempDir, 'pkgb');
  882. const pkgcDir = path.join(tempDir, 'pkgc');
  883. fs.mkdirSync(pkgaDir);
  884. fs.mkdirSync(pkgbDir);
  885. fs.mkdirSync(pkgcDir);
  886. // Same-name exported function in two packages — only the imported one
  887. // should resolve. Exercises disambiguation, not just connectivity.
  888. fs.writeFileSync(
  889. path.join(pkgaDir, 'conv.go'),
  890. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  891. );
  892. fs.writeFileSync(
  893. path.join(pkgbDir, 'conv.go'),
  894. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  895. );
  896. fs.writeFileSync(
  897. path.join(pkgcDir, 'use.go'),
  898. `package pkgc
  899. import "github.com/example/myproject/pkga"
  900. func UsePkga() {
  901. pkga.Convert(5)
  902. }
  903. `
  904. );
  905. cg = await CodeGraph.init(tempDir, { index: true });
  906. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  907. expect(usePkga).toBeDefined();
  908. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  909. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  910. expect(callEdges).toHaveLength(1);
  911. const target = cg.getNode(callEdges[0]!.target);
  912. expect(target?.name).toBe('Convert');
  913. // Critical: the resolver must pick the imported pkga's Convert,
  914. // not pkgb's. With the broken (pre-fix) resolver this lands on
  915. // whichever Convert happens to be cheaper under path proximity.
  916. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  917. });
  918. it('resolves Go aliased imports across packages (#388)', async () => {
  919. fs.writeFileSync(
  920. path.join(tempDir, 'go.mod'),
  921. 'module github.com/example/myproject\n\ngo 1.21\n'
  922. );
  923. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  924. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  925. fs.writeFileSync(
  926. path.join(tempDir, 'pkgb', 'lib.go'),
  927. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  928. );
  929. fs.writeFileSync(
  930. path.join(tempDir, 'pkgd', 'use.go'),
  931. `package pkgd
  932. import (
  933. "fmt"
  934. alias "github.com/example/myproject/pkgb"
  935. )
  936. func UseAliased() {
  937. fmt.Println("hi")
  938. alias.Compute(3)
  939. }
  940. `
  941. );
  942. cg = await CodeGraph.init(tempDir, { index: true });
  943. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  944. expect(useAliased).toBeDefined();
  945. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  946. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  947. expect(calls).toHaveLength(1);
  948. const target = cg.getNode(calls[0]!.target);
  949. expect(target?.name).toBe('Compute');
  950. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  951. });
  952. it('resolves Python module-attribute calls after `from pkg import module` (#578)', async () => {
  953. // Pre-#578, a `module.func()` call where `module` was bound via
  954. // `from pkg import module` dropped its `calls` edge. The file→file import
  955. // edge resolved (resolveModuleImportToFile falls back to a dotted-module
  956. // file lookup for absolute package paths), but resolvePythonModuleMember
  957. // had no such fallback — resolveImportPath returns null for an absolute
  958. // package path like `pkg.module`, so the member never resolved and
  959. // callers/callees/impact on the target came back empty. Same root-cause
  960. // class as the Go cross-package qualified call (#388).
  961. fs.mkdirSync(path.join(tempDir, 'pkg'));
  962. fs.writeFileSync(path.join(tempDir, 'pkg', '__init__.py'), '');
  963. fs.writeFileSync(
  964. path.join(tempDir, 'pkg', 'module.py'),
  965. 'def func():\n return 1\n'
  966. );
  967. fs.writeFileSync(
  968. path.join(tempDir, 'main.py'),
  969. `from pkg import module
  970. import os
  971. def caller():
  972. return module.func()
  973. def external_caller():
  974. return os.getcwd()
  975. `
  976. );
  977. cg = await CodeGraph.init(tempDir, { index: true });
  978. const caller = cg.getNodesByKind('function').filter((n) => n.name === 'caller')[0];
  979. expect(caller).toBeDefined();
  980. const calls = cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls');
  981. // module.func() must resolve to the real function in the submodule file.
  982. expect(calls).toHaveLength(1);
  983. const target = cg.getNode(calls[0]!.target);
  984. expect(target?.name).toBe('func');
  985. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkg/module.py');
  986. // The flip side of the fix: an attribute call through a *stdlib* module
  987. // (`os.getcwd()`) must still create no edge — the fallback only matches
  988. // real in-repo module files.
  989. const externalCaller = cg.getNodesByKind('function').filter((n) => n.name === 'external_caller')[0];
  990. expect(externalCaller).toBeDefined();
  991. const externalCalls = cg.getOutgoingEdges(externalCaller!.id).filter((e) => e.kind === 'calls');
  992. expect(externalCalls).toHaveLength(0);
  993. });
  994. it('attaches Go methods to their receiver type across files (#583, cross-file half)', async () => {
  995. // In Go a type's methods are commonly declared in a different file from the
  996. // `type` declaration (`type Box` in box.go, `func (b *Box) Get()` in
  997. // box_methods.go). Extraction only attaches the struct→method `contains`
  998. // edge when the type is in the SAME file (the owner lookup is file-scoped),
  999. // so a cross-file method was orphaned from its struct — breaking member
  1000. // outlines and any callers/callees/impact traversal through `contains`. A
  1001. // resolution-phase pass now links them within the package (= directory).
  1002. fs.writeFileSync(
  1003. path.join(tempDir, 'box.go'),
  1004. 'package main\n\ntype Box struct{ v int }\n'
  1005. );
  1006. fs.writeFileSync(
  1007. path.join(tempDir, 'box_methods.go'),
  1008. 'package main\n\nfunc (b *Box) Get() int { return b.v }\nfunc (b *Box) Set(x int) { b.v = x }\n'
  1009. );
  1010. // Generic receiver declared cross-file too — exercises #583 half A
  1011. // (generic `*Stack[T]` receiver parsing) and half B (cross-file) together.
  1012. fs.writeFileSync(
  1013. path.join(tempDir, 'stack.go'),
  1014. 'package main\n\ntype Stack[T any] struct {\n\titems []T\n}\n'
  1015. );
  1016. fs.writeFileSync(
  1017. path.join(tempDir, 'stack_push.go'),
  1018. 'package main\n\nfunc (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }\n'
  1019. );
  1020. // A same-named type in another package must NOT capture this package's
  1021. // methods — the link is scoped to the receiver type's own directory.
  1022. fs.mkdirSync(path.join(tempDir, 'other'));
  1023. fs.writeFileSync(
  1024. path.join(tempDir, 'other', 'box.go'),
  1025. 'package other\n\ntype Box struct{ w int }\n'
  1026. );
  1027. cg = await CodeGraph.init(tempDir, { index: true });
  1028. const methodsOf = (typeName: string, file: string): string[] => {
  1029. const node = cg
  1030. .getNodesByKind('struct')
  1031. .find((n) => n.name === typeName && n.filePath.replace(/\\/g, '/') === file);
  1032. expect(node, `${typeName} @ ${file}`).toBeDefined();
  1033. return cg
  1034. .getOutgoingEdges(node!.id)
  1035. .filter((e) => e.kind === 'contains')
  1036. .map((e) => cg.getNode(e.target))
  1037. .filter((n) => !!n && n.kind === 'method')
  1038. .map((n) => n!.name)
  1039. .sort();
  1040. };
  1041. // Cross-file (non-generic) methods now attach to their struct.
  1042. expect(methodsOf('Box', 'box.go')).toEqual(['Get', 'Set']);
  1043. // Generic + cross-file.
  1044. expect(methodsOf('Stack', 'stack.go')).toEqual(['Push']);
  1045. // Cross-package isolation: other/Box defines no methods of its own.
  1046. expect(methodsOf('Box', 'other/box.go')).toEqual([]);
  1047. });
  1048. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  1049. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  1050. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  1051. // because the type_alias had no `stop` node — only the unrelated
  1052. // class did. Now type_alias produces member nodes (property/method),
  1053. // so the camelCase receiver↔type word overlap pulls the call to
  1054. // `RecorderHandle::stop` instead of the look-alike class.
  1055. fs.mkdirSync(path.join(tempDir, 'voice'));
  1056. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  1057. fs.writeFileSync(
  1058. path.join(tempDir, 'voice', 'recorder.ts'),
  1059. `export type RecorderHandle = {
  1060. wavPath: string;
  1061. stop: () => Promise<{ ok: true }>;
  1062. };
  1063. `
  1064. );
  1065. fs.writeFileSync(
  1066. path.join(tempDir, 'voice', 'controller.ts'),
  1067. `import type { RecorderHandle } from "./recorder";
  1068. export async function finaliseRecording(recorder: RecorderHandle) {
  1069. return await recorder.stop();
  1070. }
  1071. `
  1072. );
  1073. fs.writeFileSync(
  1074. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  1075. `export class StdioMcpClient {
  1076. private stopped = false;
  1077. async stop(): Promise<void> { this.stopped = true; }
  1078. }
  1079. `
  1080. );
  1081. cg = await CodeGraph.init(tempDir, { index: true });
  1082. const handleStop = cg
  1083. .getNodesByKind('method')
  1084. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  1085. expect(handleStop).toBeDefined();
  1086. const clientStop = cg
  1087. .getNodesByKind('method')
  1088. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  1089. expect(clientStop).toBeDefined();
  1090. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  1091. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  1092. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  1093. // The class method must have NO callers — voice/'s call must NOT
  1094. // mis-attribute. A non-empty list would mean the false-positive
  1095. // path is still firing.
  1096. expect(clientCallers).toHaveLength(0);
  1097. // Function-typed property surfaces as a `method` node, not `property`,
  1098. // because `stop()` semantics at the call site are method semantics.
  1099. expect(handleStop!.kind).toBe('method');
  1100. });
  1101. it('Java import disambiguates same-name classes across modules (#314)', async () => {
  1102. // Pre-#314 the import resolver had no Java branch at all, so a
  1103. // multi-module Maven repo where `dao/converter/FooConverter` and
  1104. // `service/converter/FooConverter` both export a `convert` method
  1105. // resolved by file-path proximity — picking whichever class was
  1106. // closer to the caller, which is wrong any time the caller lives
  1107. // in an equidistant cross-cutting module.
  1108. const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
  1109. const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
  1110. const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
  1111. fs.mkdirSync(daoDir, { recursive: true });
  1112. fs.mkdirSync(serviceDir, { recursive: true });
  1113. fs.mkdirSync(webDir, { recursive: true });
  1114. fs.writeFileSync(
  1115. path.join(daoDir, 'FooConverter.java'),
  1116. `package com.example.dao.converter;
  1117. public class FooConverter { public String convert(String x) { return "dao:" + x; } }
  1118. `
  1119. );
  1120. fs.writeFileSync(
  1121. path.join(serviceDir, 'FooConverter.java'),
  1122. `package com.example.service.converter;
  1123. public class FooConverter { public String convert(String x) { return "svc:" + x; } }
  1124. `
  1125. );
  1126. // The caller imports the SERVICE version — even though dao is
  1127. // alphabetically/lexically first in the candidate list, the
  1128. // import must trump that order.
  1129. fs.writeFileSync(
  1130. path.join(webDir, 'Handler.java'),
  1131. `package com.example.web;
  1132. import com.example.service.converter.FooConverter;
  1133. public class Handler {
  1134. private FooConverter fooConverter;
  1135. public String use() { return fooConverter.convert("input"); }
  1136. }
  1137. `
  1138. );
  1139. cg = await CodeGraph.init(tempDir, { index: true });
  1140. const use = cg
  1141. .getNodesByKind('method')
  1142. .find((n) => n.qualifiedName === 'com.example.web::Handler::use');
  1143. expect(use).toBeDefined();
  1144. const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
  1145. expect(calls.length).toBeGreaterThanOrEqual(1);
  1146. const target = cg.getNode(calls[0]!.target);
  1147. expect(target?.name).toBe('convert');
  1148. expect(target?.filePath.replace(/\\/g, '/')).toBe(
  1149. 'service/src/main/java/com/example/service/converter/FooConverter.java'
  1150. );
  1151. });
  1152. it('C# extracts references from method/property/field types (#381)', async () => {
  1153. // Pre-#381, every C# project produced ZERO `references` edges:
  1154. // csharp.ts was missing returnField, and the type-leaf walker
  1155. // only recognized TS/Java's `type_identifier` nodes — C# uses
  1156. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  1157. const srcDir = path.join(tempDir, 'src');
  1158. fs.mkdirSync(srcDir, { recursive: true });
  1159. fs.writeFileSync(
  1160. path.join(srcDir, 'Dtos.cs'),
  1161. `namespace MyApp;
  1162. public class SessionInfoDto { public string Id { get; set; } = ""; }
  1163. public class UserDto { public string Name { get; set; } = ""; }
  1164. `
  1165. );
  1166. fs.writeFileSync(
  1167. path.join(srcDir, 'Service.cs'),
  1168. `using System.Threading.Tasks;
  1169. namespace MyApp;
  1170. public class DataExporter
  1171. {
  1172. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  1173. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  1174. public SessionInfoDto Latest { get; set; } = new();
  1175. private UserDto _cached;
  1176. }
  1177. `
  1178. );
  1179. cg = await CodeGraph.init(tempDir, { index: true });
  1180. const sessionDto = cg
  1181. .getNodesByKind('class')
  1182. .find((n) => n.name === 'SessionInfoDto');
  1183. const userDto = cg
  1184. .getNodesByKind('class')
  1185. .find((n) => n.name === 'UserDto');
  1186. expect(sessionDto).toBeDefined();
  1187. expect(userDto).toBeDefined();
  1188. const sessionIncoming = cg
  1189. .getIncomingEdges(sessionDto!.id)
  1190. .filter((e) => e.kind === 'references');
  1191. const userIncoming = cg
  1192. .getIncomingEdges(userDto!.id)
  1193. .filter((e) => e.kind === 'references');
  1194. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  1195. // UserDto: Build param, BuildAsync param, _cached field.
  1196. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  1197. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  1198. });
  1199. it('C# primary-constructor parameters record their type dependencies (#237)', async () => {
  1200. // C# 12 primary constructors declare a type's injected dependencies inline
  1201. // (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache)`). Each
  1202. // ctor parameter's type is recorded as a `references` edge from the class,
  1203. // so a DI-registered contract reached only through a primary ctor is no
  1204. // longer reported as having no dependents.
  1205. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1206. fs.writeFileSync(
  1207. path.join(tempDir, 'src', 'Contracts.cs'),
  1208. `namespace App;
  1209. public interface IRepo { }
  1210. public class ICache { }
  1211. `
  1212. );
  1213. fs.writeFileSync(
  1214. path.join(tempDir, 'src', 'OrderService.cs'),
  1215. `namespace App;
  1216. public sealed class OrderService(IRepo repo, [FromKeyedServices("primary")] ICache cache)
  1217. {
  1218. public void Run() { }
  1219. }
  1220. `
  1221. );
  1222. cg = await CodeGraph.init(tempDir, { index: true });
  1223. const svc = cg.getNodesByKind('class').find((n) => n.name === 'OrderService');
  1224. expect(svc).toBeDefined();
  1225. // The class itself must index (it used to vanish under the old grammar).
  1226. const out = cg.getOutgoingEdges(svc!.id).filter((e) => e.kind === 'references');
  1227. const depNames = out.map((e) => cg.getNode(e.target)?.name);
  1228. expect(depNames).toContain('IRepo');
  1229. expect(depNames).toContain('ICache'); // the keyed-DI ([FromKeyedServices]) dependency
  1230. });
  1231. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  1232. fs.writeFileSync(
  1233. path.join(tempDir, 'go.mod'),
  1234. 'module github.com/example/myproject\n\ngo 1.21\n'
  1235. );
  1236. fs.writeFileSync(
  1237. path.join(tempDir, 'main.go'),
  1238. `package main
  1239. import "fmt"
  1240. func main() {
  1241. fmt.Println("hi")
  1242. }
  1243. `
  1244. );
  1245. cg = await CodeGraph.init(tempDir, { index: true });
  1246. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  1247. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  1248. // No spurious in-project edge — fmt.* must stay unresolved/external.
  1249. expect(calls).toHaveLength(0);
  1250. });
  1251. });
  1252. describe('Name Matcher: kind bias for new ref kinds', () => {
  1253. const baseContext = (candidates: Node[]): ResolutionContext => ({
  1254. getNodesInFile: () => [],
  1255. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  1256. getNodesByQualifiedName: () => [],
  1257. getNodesByKind: () => [],
  1258. fileExists: () => true,
  1259. readFile: () => null,
  1260. getProjectRoot: () => '/test',
  1261. getAllFiles: () => [],
  1262. getNodesByLowerName: () => [],
  1263. getImportMappings: () => [],
  1264. });
  1265. it('prefers a class candidate over a function for `instantiates` refs', () => {
  1266. // A class and a function share a name across the codebase.
  1267. // Without the kind bias, the function (which gets the +25 `calls`
  1268. // bonus historically applied to all candidates of that kind) would
  1269. // win. Now the instantiates branch reverses it.
  1270. const fn: Node = {
  1271. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  1272. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  1273. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1274. };
  1275. const cls: Node = {
  1276. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  1277. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  1278. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1279. };
  1280. const ref = {
  1281. fromNodeId: 'func:main.ts:bootstrap:1',
  1282. referenceName: 'Logger',
  1283. referenceKind: 'instantiates' as const,
  1284. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  1285. };
  1286. const result = matchReference(ref, baseContext([fn, cls]));
  1287. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  1288. });
  1289. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  1290. const variable: Node = {
  1291. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  1292. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  1293. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1294. };
  1295. const decorator: Node = {
  1296. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  1297. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  1298. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  1299. };
  1300. const ref = {
  1301. fromNodeId: 'class:svc.ts:UserService:1',
  1302. referenceName: 'Inject',
  1303. referenceKind: 'decorates' as const,
  1304. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  1305. };
  1306. const result = matchReference(ref, baseContext([variable, decorator]));
  1307. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  1308. });
  1309. });
  1310. describe('tsconfig path aliases', () => {
  1311. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  1312. // Two same-named exports in different directories. Without alias
  1313. // resolution, name-matcher would pick whichever it finds first;
  1314. // with alias resolution, the import path uniquely picks one.
  1315. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1316. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  1317. fs.writeFileSync(
  1318. path.join(tempDir, 'src/utils/format.ts'),
  1319. `export function pickMe(): number { return 1; }\n`
  1320. );
  1321. fs.writeFileSync(
  1322. path.join(tempDir, 'src/legacy/format.ts'),
  1323. `export function pickMe(): number { return 99; }\n`
  1324. );
  1325. fs.writeFileSync(
  1326. path.join(tempDir, 'src/main.ts'),
  1327. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  1328. );
  1329. fs.writeFileSync(
  1330. path.join(tempDir, 'tsconfig.json'),
  1331. JSON.stringify({
  1332. compilerOptions: {
  1333. baseUrl: './src',
  1334. paths: { '@utils/*': ['utils/*'] },
  1335. },
  1336. })
  1337. );
  1338. cg = await CodeGraph.init(tempDir, { index: true });
  1339. cg.resolveReferences();
  1340. // The two pickMe nodes live in different files. The aliased
  1341. // import should attach the call edge to the @utils-mapped one,
  1342. // not the legacy duplicate.
  1343. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  1344. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  1345. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  1346. expect(utilsNode).toBeDefined();
  1347. expect(legacyNode).toBeDefined();
  1348. const utilsCallers = cg.getCallers(utilsNode!.id);
  1349. const legacyCallers = cg.getCallers(legacyNode!.id);
  1350. expect(utilsCallers.length).toBeGreaterThan(0);
  1351. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1352. // The legacy node should NOT have a caller from src/main.ts —
  1353. // the alias correctly picked the utils version.
  1354. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  1355. });
  1356. it('falls back gracefully when tsconfig is absent', async () => {
  1357. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1358. fs.writeFileSync(
  1359. path.join(tempDir, 'src/a.ts'),
  1360. `export function aFn(): void {}\n`
  1361. );
  1362. fs.writeFileSync(
  1363. path.join(tempDir, 'src/b.ts'),
  1364. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  1365. );
  1366. cg = await CodeGraph.init(tempDir, { index: true });
  1367. // No tsconfig present — index should still complete and the
  1368. // relative-import-based call edge should be created.
  1369. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  1370. expect(aFn).toBeDefined();
  1371. const callers = cg.getCallers(aFn!.id);
  1372. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  1373. });
  1374. });
  1375. describe('re-export chain following', () => {
  1376. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  1377. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  1378. // Without chain following, `signIn` resolves to nothing because
  1379. // none of the barrel files declare it directly.
  1380. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  1381. fs.writeFileSync(
  1382. path.join(tempDir, 'src/services/auth.ts'),
  1383. `export function signIn(): void {}\n`
  1384. );
  1385. fs.writeFileSync(
  1386. path.join(tempDir, 'src/services/index.ts'),
  1387. `export { signIn } from './auth';\n`
  1388. );
  1389. fs.writeFileSync(
  1390. path.join(tempDir, 'src/all.ts'),
  1391. `export * from './services/index';\n`
  1392. );
  1393. fs.writeFileSync(
  1394. path.join(tempDir, 'src/main.ts'),
  1395. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  1396. );
  1397. cg = await CodeGraph.init(tempDir, { index: true });
  1398. cg.resolveReferences();
  1399. const signInNode = cg
  1400. .getNodesByKind('function')
  1401. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  1402. expect(signInNode).toBeDefined();
  1403. const callers = cg.getCallers(signInNode!.id);
  1404. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1405. });
  1406. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  1407. // The chase has to look up `foo` in the upstream module even
  1408. // though the importer asked for `bar` — exercises the rename
  1409. // branch of findExportedSymbol.
  1410. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1411. fs.writeFileSync(
  1412. path.join(tempDir, 'src/auth.ts'),
  1413. `export function signIn(): void {}\n`
  1414. );
  1415. fs.writeFileSync(
  1416. path.join(tempDir, 'src/index.ts'),
  1417. `export { signIn as login } from './auth';\n`
  1418. );
  1419. fs.writeFileSync(
  1420. path.join(tempDir, 'src/main.ts'),
  1421. `import { login } from './index';\nexport function go(): void { login(); }\n`
  1422. );
  1423. cg = await CodeGraph.init(tempDir, { index: true });
  1424. cg.resolveReferences();
  1425. const signInNode = cg
  1426. .getNodesByKind('function')
  1427. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  1428. expect(signInNode).toBeDefined();
  1429. const callers = cg.getCallers(signInNode!.id);
  1430. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1431. });
  1432. it('follows a default re-export of a .svelte component (export { default as Foo } from ./RealButton.svelte) (#629)', async () => {
  1433. // The ubiquitous Svelte/React component-barrel form. The leaf is a
  1434. // .svelte component (extracted as kind 'component', the default
  1435. // export). The re-export ALIAS (`Foo`) deliberately differs from the
  1436. // component's real name (`RealButton`) so the name-matcher fallback
  1437. // can't coincidentally connect them — the only path to the edge is
  1438. // the import-chase, which must match a `component` (not just
  1439. // function/class) for the default export. Otherwise the
  1440. // consumer↔component edge is never created and `callers` returns a
  1441. // false 0.
  1442. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  1443. fs.writeFileSync(
  1444. path.join(tempDir, 'src/lib/RealButton.svelte'),
  1445. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1446. );
  1447. fs.writeFileSync(
  1448. path.join(tempDir, 'src/lib/index.ts'),
  1449. `export { default as Foo } from './RealButton.svelte';\n`
  1450. );
  1451. fs.writeFileSync(
  1452. path.join(tempDir, 'src/Bar.svelte'),
  1453. `<script lang="ts">\n import { Foo } from './lib';\n</script>\n\n<Foo />\n`
  1454. );
  1455. cg = await CodeGraph.init(tempDir, { index: true });
  1456. cg.resolveReferences();
  1457. const fooNode = cg
  1458. .getNodesByKind('component')
  1459. .find((n) => n.name === 'RealButton' && n.filePath === 'src/lib/RealButton.svelte');
  1460. expect(fooNode).toBeDefined();
  1461. const callers = cg.getCallers(fooNode!.id);
  1462. expect(callers.some((c) => c.node.filePath === 'src/Bar.svelte')).toBe(true);
  1463. });
  1464. it('links an .astro page to the component and TS util it uses (#768)', async () => {
  1465. // The canonical Astro shape: a page imports a layout/component in
  1466. // frontmatter and uses it as a template tag; the component's template
  1467. // calls an imported .ts util. Both hops must produce graph edges or
  1468. // an Astro project is invisible to callers/impact.
  1469. fs.mkdirSync(path.join(tempDir, 'src/components'), { recursive: true });
  1470. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  1471. fs.mkdirSync(path.join(tempDir, 'src/pages'), { recursive: true });
  1472. fs.writeFileSync(
  1473. path.join(tempDir, 'src/utils/format.ts'),
  1474. `export function formatDate(d: Date): string { return d.toISOString(); }\n`
  1475. );
  1476. fs.writeFileSync(
  1477. path.join(tempDir, 'src/components/PostCard.astro'),
  1478. `---\nimport { formatDate } from '../utils/format';\nconst { date } = Astro.props;\n---\n<time>{formatDate(date)}</time>\n`
  1479. );
  1480. fs.writeFileSync(
  1481. path.join(tempDir, 'src/pages/index.astro'),
  1482. `---\nimport PostCard from '../components/PostCard.astro';\n---\n<PostCard date={new Date()} />\n`
  1483. );
  1484. cg = await CodeGraph.init(tempDir, { index: true });
  1485. cg.resolveReferences();
  1486. // Hop 1: page → component (template tag through the frontmatter import)
  1487. const cardNode = cg
  1488. .getNodesByKind('component')
  1489. .find((n) => n.name === 'PostCard' && n.filePath === 'src/components/PostCard.astro');
  1490. expect(cardNode).toBeDefined();
  1491. const cardCallers = cg.getCallers(cardNode!.id);
  1492. expect(cardCallers.some((c) => c.node.filePath === 'src/pages/index.astro')).toBe(true);
  1493. // Hop 2: component template call → .ts util
  1494. const fmtNode = cg
  1495. .getNodesByKind('function')
  1496. .find((n) => n.name === 'formatDate' && n.filePath === 'src/utils/format.ts');
  1497. expect(fmtNode).toBeDefined();
  1498. const fmtCallers = cg.getCallers(fmtNode!.id);
  1499. expect(fmtCallers.some((c) => c.node.filePath === 'src/components/PostCard.astro')).toBe(true);
  1500. });
  1501. it('resolves a bare directory import (import { x } from "." / "./") to index.ts (#629)', async () => {
  1502. // `import { helper } from '.'` (or './') must map to the
  1503. // directory's index.ts before the re-export chase can run. The
  1504. // barrel renames `realHelper` → `helper` so the name-matcher can't
  1505. // mask a path-resolution failure: only the bare-dir resolution +
  1506. // rename chase can connect the edge.
  1507. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1508. fs.writeFileSync(
  1509. path.join(tempDir, 'src/util.ts'),
  1510. `export function realHelper(): void {}\n`
  1511. );
  1512. fs.writeFileSync(
  1513. path.join(tempDir, 'src/index.ts'),
  1514. `export { realHelper as helper } from './util';\n`
  1515. );
  1516. fs.writeFileSync(
  1517. path.join(tempDir, 'src/main.ts'),
  1518. `import { helper } from '.';\nexport function go(): void { helper(); }\n`
  1519. );
  1520. fs.writeFileSync(
  1521. path.join(tempDir, 'src/main2.ts'),
  1522. `import { helper } from './';\nexport function go2(): void { helper(); }\n`
  1523. );
  1524. cg = await CodeGraph.init(tempDir, { index: true });
  1525. cg.resolveReferences();
  1526. const helperNode = cg
  1527. .getNodesByKind('function')
  1528. .find((n) => n.name === 'realHelper' && n.filePath === 'src/util.ts');
  1529. expect(helperNode).toBeDefined();
  1530. const callers = cg.getCallers(helperNode!.id);
  1531. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  1532. expect(callers.some((c) => c.node.filePath === 'src/main2.ts')).toBe(true);
  1533. });
  1534. it('resolves a workspace package-subpath barrel (@scope/pkg/sub) to its index (#629)', async () => {
  1535. // bun/npm/pnpm workspace: `@scope/ui/widgets` → the `ui` package's
  1536. // `widgets/` subdir index, which re-exports a .svelte component.
  1537. // Alias `Thing` ≠ component `Widget` defeats the name-matcher, so
  1538. // only workspace-package resolution can connect the edge.
  1539. fs.mkdirSync(path.join(tempDir, 'packages/ui/widgets'), { recursive: true });
  1540. fs.writeFileSync(
  1541. path.join(tempDir, 'package.json'),
  1542. JSON.stringify({ name: 'root', private: true, workspaces: ['packages/*'] }, null, 2)
  1543. );
  1544. fs.writeFileSync(
  1545. path.join(tempDir, 'packages/ui/package.json'),
  1546. JSON.stringify({ name: '@scope/ui', version: '1.0.0' }, null, 2)
  1547. );
  1548. fs.writeFileSync(
  1549. path.join(tempDir, 'packages/ui/widgets/Widget.svelte'),
  1550. `<script lang="ts">\n export let label: string = '';\n</script>\n\n<button>{label}</button>\n`
  1551. );
  1552. fs.writeFileSync(
  1553. path.join(tempDir, 'packages/ui/widgets/index.ts'),
  1554. `export { default as Thing } from './Widget.svelte';\n`
  1555. );
  1556. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  1557. fs.writeFileSync(
  1558. path.join(tempDir, 'app/App.svelte'),
  1559. `<script lang="ts">\n import { Thing } from '@scope/ui/widgets';\n</script>\n\n<Thing />\n`
  1560. );
  1561. cg = await CodeGraph.init(tempDir, { index: true });
  1562. cg.resolveReferences();
  1563. const buttonNode = cg
  1564. .getNodesByKind('component')
  1565. .find((n) => n.name === 'Widget' && n.filePath === 'packages/ui/widgets/Widget.svelte');
  1566. expect(buttonNode).toBeDefined();
  1567. const callers = cg.getCallers(buttonNode!.id);
  1568. expect(callers.some((c) => c.node.filePath === 'app/App.svelte')).toBe(true);
  1569. });
  1570. it('resolves a barrel import from a Vue SFC <script> block (#629)', async () => {
  1571. // The same import-resolution gaps (no SFC import mappings, no SFC
  1572. // extension list, barrel parsed in the consumer's language) broke
  1573. // Vue SFCs too. Guards the resolver-side generalization to `.vue`.
  1574. // The barrel renames `realRun` → `run` so only the import-chase (not
  1575. // the name-matcher) can connect the call.
  1576. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  1577. fs.writeFileSync(
  1578. path.join(tempDir, 'src/util.ts'),
  1579. `export function realRun(): void {}\n`
  1580. );
  1581. fs.writeFileSync(
  1582. path.join(tempDir, 'src/index.ts'),
  1583. `export { realRun as run } from './util';\n`
  1584. );
  1585. fs.writeFileSync(
  1586. path.join(tempDir, 'src/App.vue'),
  1587. `<script lang="ts">\nimport { run } from './';\nexport default { mounted() { run(); } };\n</script>\n<template><div/></template>\n`
  1588. );
  1589. cg = await CodeGraph.init(tempDir, { index: true });
  1590. cg.resolveReferences();
  1591. const runNode = cg
  1592. .getNodesByKind('function')
  1593. .find((n) => n.name === 'realRun' && n.filePath === 'src/util.ts');
  1594. expect(runNode).toBeDefined();
  1595. const callers = cg.getCallers(runNode!.id);
  1596. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  1597. });
  1598. it('follows a Vue component used in a <template> through a default re-export barrel (#629)', async () => {
  1599. // End-to-end Vue analogue of the Svelte case: the leaf is a `.vue`
  1600. // component re-exported under an alias (`Thing`) that differs from its
  1601. // real name (`Widget`), and the consumer uses it ONLY in markup
  1602. // (`<Thing />`). Requires both the new template-tag extraction AND the
  1603. // barrel default-export chase to connect the edge.
  1604. fs.mkdirSync(path.join(tempDir, 'src/lib'), { recursive: true });
  1605. fs.writeFileSync(
  1606. path.join(tempDir, 'src/lib/Widget.vue'),
  1607. `<script setup lang="ts">\ndefineProps<{ label?: string }>();\n</script>\n<template><button>x</button></template>\n`
  1608. );
  1609. fs.writeFileSync(
  1610. path.join(tempDir, 'src/lib/index.ts'),
  1611. `export { default as Thing } from './Widget.vue';\n`
  1612. );
  1613. fs.writeFileSync(
  1614. path.join(tempDir, 'src/App.vue'),
  1615. `<script setup lang="ts">\nimport { Thing } from './lib';\n</script>\n<template>\n <Thing />\n</template>\n`
  1616. );
  1617. cg = await CodeGraph.init(tempDir, { index: true });
  1618. cg.resolveReferences();
  1619. const widgetNode = cg
  1620. .getNodesByKind('component')
  1621. .find((n) => n.name === 'Widget' && n.filePath === 'src/lib/Widget.vue');
  1622. expect(widgetNode).toBeDefined();
  1623. const callers = cg.getCallers(widgetNode!.id);
  1624. expect(callers.some((c) => c.node.filePath === 'src/App.vue')).toBe(true);
  1625. });
  1626. });
  1627. describe('C/C++ Import Resolution', () => {
  1628. afterEach(() => {
  1629. clearCppIncludeDirCache();
  1630. });
  1631. it('should resolve C include to header in same directory', () => {
  1632. const context: ResolutionContext = {
  1633. getNodesInFile: () => [],
  1634. getNodesByName: () => [],
  1635. getNodesByQualifiedName: () => [],
  1636. getNodesByKind: () => [],
  1637. fileExists: (p) => p === 'utils.h',
  1638. readFile: () => null,
  1639. getProjectRoot: () => '',
  1640. getAllFiles: () => ['utils.h', 'main.c'],
  1641. };
  1642. const result = resolveImportPath(
  1643. 'utils.h',
  1644. 'main.c',
  1645. 'c',
  1646. context
  1647. );
  1648. expect(result).toBe('utils.h');
  1649. });
  1650. it('should resolve C++ include with .hpp extension', () => {
  1651. const context: ResolutionContext = {
  1652. getNodesInFile: () => [],
  1653. getNodesByName: () => [],
  1654. getNodesByQualifiedName: () => [],
  1655. getNodesByKind: () => [],
  1656. fileExists: (p) => p === 'include/myclass.hpp',
  1657. readFile: () => null,
  1658. getProjectRoot: () => '',
  1659. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  1660. getCppIncludeDirs: () => ['include'],
  1661. };
  1662. const result = resolveImportPath(
  1663. 'myclass.hpp',
  1664. 'src/main.cpp',
  1665. 'cpp',
  1666. context
  1667. );
  1668. expect(result).toBe('include/myclass.hpp');
  1669. });
  1670. it('should resolve include with subdirectory path', () => {
  1671. const context: ResolutionContext = {
  1672. getNodesInFile: () => [],
  1673. getNodesByName: () => [],
  1674. getNodesByQualifiedName: () => [],
  1675. getNodesByKind: () => [],
  1676. fileExists: (p) => p === 'utils/helpers.h',
  1677. readFile: () => null,
  1678. getProjectRoot: () => '',
  1679. getAllFiles: () => ['utils/helpers.h', 'main.c'],
  1680. };
  1681. const result = resolveImportPath(
  1682. 'utils/helpers.h',
  1683. 'main.c',
  1684. 'c',
  1685. context
  1686. );
  1687. expect(result).toBe('utils/helpers.h');
  1688. });
  1689. it('should resolve include via include directories', () => {
  1690. const context: ResolutionContext = {
  1691. getNodesInFile: () => [],
  1692. getNodesByName: () => [],
  1693. getNodesByQualifiedName: () => [],
  1694. getNodesByKind: () => [],
  1695. fileExists: (p) => p === 'include/myheader.h',
  1696. readFile: () => null,
  1697. getProjectRoot: () => '',
  1698. getAllFiles: () => ['include/myheader.h', 'src/main.cpp'],
  1699. getCppIncludeDirs: () => ['include'],
  1700. };
  1701. const result = resolveImportPath(
  1702. 'myheader.h',
  1703. 'src/main.cpp',
  1704. 'cpp',
  1705. context
  1706. );
  1707. expect(result).toBe('include/myheader.h');
  1708. });
  1709. it('should resolve include trying multiple extensions', () => {
  1710. const context: ResolutionContext = {
  1711. getNodesInFile: () => [],
  1712. getNodesByName: () => [],
  1713. getNodesByQualifiedName: () => [],
  1714. getNodesByKind: () => [],
  1715. // myclass.h does not exist, but myclass.hpp does
  1716. fileExists: (p) => p === 'include/myclass.hpp',
  1717. readFile: () => null,
  1718. getProjectRoot: () => '',
  1719. getAllFiles: () => ['include/myclass.hpp', 'src/main.cpp'],
  1720. getCppIncludeDirs: () => ['include'],
  1721. };
  1722. const result = resolveImportPath(
  1723. 'myclass',
  1724. 'src/main.cpp',
  1725. 'cpp',
  1726. context
  1727. );
  1728. expect(result).toBe('include/myclass.hpp');
  1729. });
  1730. it('should return null for system headers', () => {
  1731. const context: ResolutionContext = {
  1732. getNodesInFile: () => [],
  1733. getNodesByName: () => [],
  1734. getNodesByQualifiedName: () => [],
  1735. getNodesByKind: () => [],
  1736. fileExists: () => true,
  1737. readFile: () => null,
  1738. getProjectRoot: () => '',
  1739. getAllFiles: () => [],
  1740. };
  1741. // C standard library header
  1742. expect(resolveImportPath('stdio.h', 'main.c', 'c', context)).toBeNull();
  1743. // C++ standard library header
  1744. expect(resolveImportPath('vector', 'main.cpp', 'cpp', context)).toBeNull();
  1745. // C++ C-wrapper header
  1746. expect(resolveImportPath('cstdio', 'main.cpp', 'cpp', context)).toBeNull();
  1747. });
  1748. it('should return null for single-component third-party paths that cannot be resolved', () => {
  1749. const context: ResolutionContext = {
  1750. getNodesInFile: () => [],
  1751. getNodesByName: () => [],
  1752. getNodesByQualifiedName: () => [],
  1753. getNodesByKind: () => [],
  1754. fileExists: () => false,
  1755. readFile: () => null,
  1756. getProjectRoot: () => '',
  1757. getAllFiles: () => [],
  1758. getCppIncludeDirs: () => [],
  1759. };
  1760. // Third-party bare header without path — not resolvable, returns null
  1761. const result = resolveImportPath(
  1762. 'openssl/ssl.h',
  1763. 'main.cpp',
  1764. 'cpp',
  1765. context
  1766. );
  1767. expect(result).toBeNull();
  1768. });
  1769. it('should not filter project headers with path separators', () => {
  1770. const context: ResolutionContext = {
  1771. getNodesInFile: () => [],
  1772. getNodesByName: () => [],
  1773. getNodesByQualifiedName: () => [],
  1774. getNodesByKind: () => [],
  1775. fileExists: (p) => p === 'mylib/utils.h',
  1776. readFile: () => null,
  1777. getProjectRoot: () => '',
  1778. getAllFiles: () => ['mylib/utils.h'],
  1779. };
  1780. // Path with separator should NOT be filtered as external
  1781. const result = resolveImportPath(
  1782. 'mylib/utils.h',
  1783. 'main.c',
  1784. 'c',
  1785. context
  1786. );
  1787. expect(result).toBe('mylib/utils.h');
  1788. });
  1789. it('should extract C/C++ import mappings from #include directives', () => {
  1790. const code = `#include <iostream>
  1791. #include "myheader.h"
  1792. #include "utils/helpers.hpp"`;
  1793. const mappings = extractImportMappings('main.cpp', code, 'cpp');
  1794. expect(mappings.length).toBe(3);
  1795. expect(mappings[0]).toEqual({
  1796. localName: 'iostream',
  1797. exportedName: '*',
  1798. source: 'iostream',
  1799. isDefault: false,
  1800. isNamespace: true,
  1801. });
  1802. expect(mappings[1]).toEqual({
  1803. localName: 'myheader',
  1804. exportedName: '*',
  1805. source: 'myheader.h',
  1806. isDefault: false,
  1807. isNamespace: true,
  1808. });
  1809. expect(mappings[2]).toEqual({
  1810. localName: 'helpers',
  1811. exportedName: '*',
  1812. source: 'utils/helpers.hpp',
  1813. isDefault: false,
  1814. isNamespace: true,
  1815. });
  1816. });
  1817. it('should discover include directories from compile_commands.json', () => {
  1818. // Create a temp project with compile_commands.json
  1819. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1820. try {
  1821. const compileDb = [
  1822. {
  1823. directory: tempProject,
  1824. command: 'g++ -Iinclude -Isrc/lib -isystem /usr/include -c src/main.cpp',
  1825. file: 'src/main.cpp',
  1826. },
  1827. ];
  1828. fs.writeFileSync(
  1829. path.join(tempProject, 'compile_commands.json'),
  1830. JSON.stringify(compileDb)
  1831. );
  1832. // Create the include dirs so they exist
  1833. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1834. fs.mkdirSync(path.join(tempProject, 'src', 'lib'), { recursive: true });
  1835. clearCppIncludeDirCache();
  1836. const dirs = loadCppIncludeDirs(tempProject);
  1837. // Should find include and src/lib (relative to project root)
  1838. // /usr/include is absolute and outside project, should be excluded
  1839. expect(dirs).toContain('include');
  1840. expect(dirs).toContain('src/lib');
  1841. expect(dirs.some(d => d.includes('usr'))).toBe(false);
  1842. } finally {
  1843. fs.rmSync(tempProject, { recursive: true });
  1844. }
  1845. });
  1846. it('should fall back to heuristic include dirs when no compile_commands.json', () => {
  1847. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1848. try {
  1849. // Create include/ and src/ directories with headers
  1850. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1851. fs.writeFileSync(path.join(tempProject, 'include', 'types.h'), '');
  1852. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  1853. fs.writeFileSync(path.join(tempProject, 'src', 'main.cpp'), '');
  1854. // Create a directory without headers — should not be included
  1855. fs.mkdirSync(path.join(tempProject, 'docs'), { recursive: true });
  1856. clearCppIncludeDirCache();
  1857. const dirs = loadCppIncludeDirs(tempProject);
  1858. expect(dirs).toContain('include');
  1859. expect(dirs).toContain('src');
  1860. expect(dirs).not.toContain('docs');
  1861. } finally {
  1862. fs.rmSync(tempProject, { recursive: true });
  1863. }
  1864. });
  1865. // Documents the cross-language `.h` behavior. Objective-C and C++ share
  1866. // the `.h` extension, so in a mixed iOS-style project an Obj-C header
  1867. // dir gets claimed as a C/C++ include dir too. That's intentional — a
  1868. // C++ file legitimately can `#include "Foo.h"` against an Obj-C header
  1869. // (Obj-C++ / .mm callers), and false-positive inclusion is far cheaper
  1870. // than missing real resolutions. The test pins this so a later
  1871. // "exclude objc dirs" refactor breaks loudly and reviewers see the
  1872. // trade-off explicitly.
  1873. it('heuristic claims any top-level dir containing .h files, including Obj-C', () => {
  1874. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-test-'));
  1875. try {
  1876. // C++ side: an `cppmod` dir with a .hpp (C++-only extension)
  1877. fs.mkdirSync(path.join(tempProject, 'cppmod'), { recursive: true });
  1878. fs.writeFileSync(path.join(tempProject, 'cppmod', 'shared.hpp'), '');
  1879. // Obj-C side: an `iosmod` dir with .h + .m (no .cpp/.hpp).
  1880. fs.mkdirSync(path.join(tempProject, 'iosmod'), { recursive: true });
  1881. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.h'), '');
  1882. fs.writeFileSync(path.join(tempProject, 'iosmod', 'View.m'), '');
  1883. clearCppIncludeDirCache();
  1884. const dirs = loadCppIncludeDirs(tempProject);
  1885. // Both included — Obj-C dirs are intentionally allowed.
  1886. expect(dirs).toContain('cppmod');
  1887. expect(dirs).toContain('iosmod');
  1888. } finally {
  1889. fs.rmSync(tempProject, { recursive: true });
  1890. }
  1891. });
  1892. // End-to-end: ensure `#include "X.h"` produces a file→file `imports` edge
  1893. // in the actual indexing pipeline (not just a phantom file→import-node
  1894. // edge). This pins the include-dir resolution path so the headline PR
  1895. // feature can't silently regress to a no-op in the indexing flow.
  1896. it('connects #include to the real header file via include-dir scan (end-to-end)', async () => {
  1897. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-e2e-'));
  1898. try {
  1899. fs.mkdirSync(path.join(tempProject, 'include'), { recursive: true });
  1900. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  1901. fs.writeFileSync(
  1902. path.join(tempProject, 'include', 'utils.h'),
  1903. `#ifndef UTILS_H\n#define UTILS_H\nint add(int, int);\n#endif\n`
  1904. );
  1905. fs.writeFileSync(
  1906. path.join(tempProject, 'src', 'main.cpp'),
  1907. `#include "utils.h"\n#include <vector>\nint main(){ return add(1,2); }\n`
  1908. );
  1909. clearCppIncludeDirCache();
  1910. cg = await CodeGraph.init(tempProject, { index: true });
  1911. // Sanity: file nodes exist for the header and the cpp.
  1912. const allFiles = cg.getStats();
  1913. expect(allFiles.fileCount).toBe(2);
  1914. // The `#include "utils.h"` edge should target the real
  1915. // `include/utils.h` file node — not a floating `import` node
  1916. // living inside main.cpp.
  1917. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  1918. const rows = db.getDb().prepare(`
  1919. select dst.kind as dstKind, dst.file_path as dstPath
  1920. from edges e
  1921. join nodes src on e.source = src.id
  1922. join nodes dst on e.target = dst.id
  1923. where e.kind = 'imports'
  1924. and src.kind = 'file'
  1925. and src.file_path = 'src/main.cpp'
  1926. `).all() as Array<{ dstKind: string; dstPath: string }>;
  1927. const resolvedToHeader = rows.find(
  1928. (r) => r.dstKind === 'file' && r.dstPath === 'include/utils.h'
  1929. );
  1930. expect(resolvedToHeader, 'main.cpp → include/utils.h imports edge missing').toBeDefined();
  1931. // `<vector>` should NOT produce a file edge — it's a stdlib header.
  1932. const stdlibFile = rows.find(
  1933. (r) => r.dstKind === 'file' && r.dstPath && r.dstPath.endsWith('vector')
  1934. );
  1935. expect(stdlibFile).toBeUndefined();
  1936. } finally {
  1937. fs.rmSync(tempProject, { recursive: true, force: true });
  1938. }
  1939. });
  1940. });
  1941. describe('PHP Include Resolution', () => {
  1942. it('isPhpIncludePathRef distinguishes include paths from namespace use (#660)', () => {
  1943. const mk = (name: string, over: Partial<UnresolvedRef> = {}): UnresolvedRef => ({
  1944. fromNodeId: 'f', referenceName: name, referenceKind: 'imports',
  1945. line: 1, column: 0, filePath: 'x.php', language: 'php', ...over,
  1946. });
  1947. // include paths: contain a slash or a file extension
  1948. expect(isPhpIncludePathRef(mk('lib.php'))).toBe(true);
  1949. expect(isPhpIncludePathRef(mk('inc/db.php'))).toBe(true);
  1950. expect(isPhpIncludePathRef(mk('../config.php'))).toBe(true);
  1951. // namespace use symbols: a bare class (Closure) or FQN — never a path,
  1952. // so they must NOT be treated as includes (would mis-connect to a
  1953. // same-named Closure.php / Bar.php file).
  1954. expect(isPhpIncludePathRef(mk('Closure'))).toBe(false);
  1955. expect(isPhpIncludePathRef(mk('PDO'))).toBe(false);
  1956. expect(isPhpIncludePathRef(mk('App\\Foo\\Bar'))).toBe(false);
  1957. // scoped to PHP imports only
  1958. expect(isPhpIncludePathRef(mk('lib.php', { language: 'c' }))).toBe(false);
  1959. expect(isPhpIncludePathRef(mk('lib.php', { referenceKind: 'calls' }))).toBe(false);
  1960. });
  1961. it('resolves require_once to a file→file imports edge (#660)', async () => {
  1962. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-e2e-'));
  1963. try {
  1964. fs.mkdirSync(path.join(tempProject, 'src'), { recursive: true });
  1965. fs.writeFileSync(
  1966. path.join(tempProject, 'src', 'lib.php'),
  1967. `<?php\nfunction greet() { return "hi"; }\n`
  1968. );
  1969. fs.writeFileSync(
  1970. path.join(tempProject, 'src', 'page.php'),
  1971. `<?php\nrequire_once("lib.php");\necho greet();\n`
  1972. );
  1973. cg = await CodeGraph.init(tempProject, { index: true });
  1974. // reporter's repro: page.php's `require_once("lib.php")` must resolve
  1975. // to the real src/lib.php file node — a file→file `imports` edge, so
  1976. // callers(lib.php) now includes page.php.
  1977. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  1978. const rows = db.getDb().prepare(`
  1979. select dst.kind as dstKind, dst.file_path as dstPath
  1980. from edges e
  1981. join nodes src on e.source = src.id
  1982. join nodes dst on e.target = dst.id
  1983. where e.kind = 'imports'
  1984. and src.kind = 'file'
  1985. and src.file_path = 'src/page.php'
  1986. `).all() as Array<{ dstKind: string; dstPath: string }>;
  1987. const resolved = rows.find(
  1988. (r) => r.dstKind === 'file' && r.dstPath === 'src/lib.php'
  1989. );
  1990. expect(resolved, 'page.php → src/lib.php imports edge missing').toBeDefined();
  1991. } finally {
  1992. fs.rmSync(tempProject, { recursive: true, force: true });
  1993. }
  1994. });
  1995. it('resolves a subdirectory include path to the correct file (#660)', async () => {
  1996. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-subdir-'));
  1997. try {
  1998. fs.mkdirSync(path.join(tempProject, 'inc'), { recursive: true });
  1999. fs.writeFileSync(
  2000. path.join(tempProject, 'inc', 'db.php'),
  2001. `<?php\nfunction query() { return 1; }\n`
  2002. );
  2003. fs.writeFileSync(
  2004. path.join(tempProject, 'index.php'),
  2005. `<?php\nrequire "inc/db.php";\nquery();\n`
  2006. );
  2007. cg = await CodeGraph.init(tempProject, { index: true });
  2008. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2009. const rows = db.getDb().prepare(`
  2010. select dst.kind as dstKind, dst.file_path as dstPath
  2011. from edges e
  2012. join nodes src on e.source = src.id
  2013. join nodes dst on e.target = dst.id
  2014. where e.kind = 'imports'
  2015. and src.kind = 'file'
  2016. and src.file_path = 'index.php'
  2017. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2018. expect(
  2019. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'inc/db.php'),
  2020. 'index.php → inc/db.php imports edge missing'
  2021. ).toBeDefined();
  2022. } finally {
  2023. fs.rmSync(tempProject, { recursive: true, force: true });
  2024. }
  2025. });
  2026. it('does not mis-connect an unresolvable include to a same-named file elsewhere (#660)', async () => {
  2027. const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-php-misresolve-'));
  2028. try {
  2029. // app/page.php's `require "inc/db.php"` resolves relative to app/, where
  2030. // inc/db.php does NOT exist. A same-named lib/inc/db.php exists elsewhere
  2031. // but is unrelated — no edge should be created (a wrong edge is worse
  2032. // than a missing one).
  2033. fs.mkdirSync(path.join(tempProject, 'app'), { recursive: true });
  2034. fs.mkdirSync(path.join(tempProject, 'lib', 'inc'), { recursive: true });
  2035. fs.writeFileSync(
  2036. path.join(tempProject, 'lib', 'inc', 'db.php'),
  2037. `<?php\nfunction unrelated() {}\n`
  2038. );
  2039. fs.writeFileSync(
  2040. path.join(tempProject, 'app', 'page.php'),
  2041. `<?php\nrequire "inc/db.php";\n`
  2042. );
  2043. cg = await CodeGraph.init(tempProject, { index: true });
  2044. const db = DatabaseConnection.open(path.join(tempProject, '.codegraph', 'codegraph.db'));
  2045. const rows = db.getDb().prepare(`
  2046. select dst.kind as dstKind, dst.file_path as dstPath
  2047. from edges e
  2048. join nodes src on e.source = src.id
  2049. join nodes dst on e.target = dst.id
  2050. where e.kind = 'imports'
  2051. and src.kind = 'file'
  2052. and src.file_path = 'app/page.php'
  2053. `).all() as Array<{ dstKind: string; dstPath: string }>;
  2054. expect(
  2055. rows.find((r) => r.dstKind === 'file' && r.dstPath === 'lib/inc/db.php'),
  2056. 'app/page.php must NOT mis-connect to unrelated lib/inc/db.php'
  2057. ).toBeUndefined();
  2058. } finally {
  2059. fs.rmSync(tempProject, { recursive: true, force: true });
  2060. }
  2061. });
  2062. });
  2063. describe('C++ chained-call receiver resolution (#645)', () => {
  2064. async function indexCpp(files: Record<string, string>): Promise<void> {
  2065. for (const [name, content] of Object.entries(files)) {
  2066. fs.writeFileSync(path.join(tempDir, name), content);
  2067. }
  2068. cg = await CodeGraph.init(tempDir, { index: true });
  2069. }
  2070. function callerNamesOf(qualifiedName: string): string[] {
  2071. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2072. if (!target) return [];
  2073. const names = cg
  2074. .getIncomingEdges(target.id)
  2075. .filter((e) => e.kind === 'calls')
  2076. .map((e) => cg.getNode(e.source)?.name)
  2077. .filter((n): n is string => !!n);
  2078. return [...new Set(names)].sort();
  2079. }
  2080. it('resolves singleton chains and auto locals to the right class, never the first-sorted one', async () => {
  2081. // Two classes share writeLog; Logger sorts first so it wins any name-only
  2082. // tie. All three call forms target Metrics.
  2083. await indexCpp({
  2084. 'logger.hpp': `#pragma once
  2085. #include <string>
  2086. class Logger { public: static Logger& instance(); void writeLog(const std::string&); };
  2087. class Metrics { public: static Metrics& instance(); void writeLog(const std::string&); };
  2088. `,
  2089. 'impl.cpp': `#include "logger.hpp"
  2090. Logger& Logger::instance() { static Logger l; return l; }
  2091. Metrics& Metrics::instance() { static Metrics m; return m; }
  2092. void Logger::writeLog(const std::string&) {}
  2093. void Metrics::writeLog(const std::string&) {}
  2094. `,
  2095. 'app.cpp': `#include "logger.hpp"
  2096. void a() { Metrics::instance().writeLog("x"); } // chained singleton
  2097. void b() { auto& m = Metrics::instance(); m.writeLog("x"); } // stored in auto
  2098. void c() { Metrics& m = Metrics::instance(); m.writeLog("x"); } // explicit type
  2099. `,
  2100. });
  2101. expect(callerNamesOf('Metrics::writeLog')).toEqual(['a', 'b', 'c']);
  2102. expect(callerNamesOf('Logger::writeLog')).toEqual([]);
  2103. });
  2104. it('resolves factories, free-function factories, and member chains via the inner call return type', async () => {
  2105. await indexCpp({
  2106. 'types.hpp': `#pragma once
  2107. #include <memory>
  2108. struct Widget { void draw(); };
  2109. struct Session { void run(); };
  2110. struct View { void render(); };
  2111. class WidgetFactory { public: static Widget create(); };
  2112. class Manager { public: View view(); };
  2113. Session* openSession();
  2114. // Decoy that sorts first and has all three methods — must never win.
  2115. struct Aaa { void draw(); void run(); void render(); };
  2116. `,
  2117. 'impl.cpp': `#include "types.hpp"
  2118. void Widget::draw() {}
  2119. void Session::run() {}
  2120. void View::render() {}
  2121. void Aaa::draw() {}
  2122. void Aaa::run() {}
  2123. void Aaa::render() {}
  2124. Widget WidgetFactory::create() { return Widget(); }
  2125. View Manager::view() { return View(); }
  2126. Session* openSession() { return nullptr; }
  2127. `,
  2128. 'app.cpp': `#include "types.hpp"
  2129. void factory() { WidgetFactory::create().draw(); } // -> Widget::draw
  2130. void freefunc() { openSession()->run(); } // -> Session::run
  2131. void member() { Manager mgr; mgr.view().render(); } // -> View::render
  2132. void makeUnique() { auto w = std::make_unique<Widget>(); w->draw(); } // -> Widget::draw
  2133. `,
  2134. });
  2135. expect(callerNamesOf('Widget::draw')).toEqual(['factory', 'makeUnique']);
  2136. expect(callerNamesOf('Session::run')).toEqual(['freefunc']);
  2137. expect(callerNamesOf('View::render')).toEqual(['member']);
  2138. // The first-sorted decoy never captures any of them.
  2139. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2140. expect(callerNamesOf('Aaa::run')).toEqual([]);
  2141. expect(callerNamesOf('Aaa::render')).toEqual([]);
  2142. });
  2143. it('creates NO edge when the inferred type lacks the method (silent miss, not a wrong edge)', async () => {
  2144. await indexCpp({
  2145. 'types.hpp': `#pragma once
  2146. struct Widget { void draw(); };
  2147. struct Other { void onlyOther(); };
  2148. class WidgetFactory { public: static Widget create(); };
  2149. `,
  2150. 'impl.cpp': `#include "types.hpp"
  2151. void Widget::draw() {}
  2152. void Other::onlyOther() {}
  2153. Widget WidgetFactory::create() { return Widget(); }
  2154. `,
  2155. 'app.cpp': `#include "types.hpp"
  2156. // Widget has no onlyOther() — must produce NO edge, never a wrong one to Other.
  2157. void wrong() { WidgetFactory::create().onlyOther(); }
  2158. `,
  2159. });
  2160. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2161. });
  2162. });
  2163. describe('PHP chained static-factory call resolution (#608)', () => {
  2164. function callerNamesOf(qualifiedName: string): string[] {
  2165. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2166. if (!target) return [];
  2167. const names = cg
  2168. .getIncomingEdges(target.id)
  2169. .filter((e) => e.kind === 'calls')
  2170. .map((e) => cg.getNode(e.source)?.name)
  2171. .filter((n): n is string => !!n);
  2172. return [...new Set(names)].sort();
  2173. }
  2174. it('resolves Cls::for($x)->method() via the factory\'s `: self` return (#608)', async () => {
  2175. fs.writeFileSync(
  2176. path.join(tempDir, 'ApiClient.php'),
  2177. `<?php\nclass ApiClient {\n public static function for(string $c): self { return new self; }\n public function createOrder(array $p): array { return []; }\n}\n`
  2178. );
  2179. fs.writeFileSync(
  2180. path.join(tempDir, 'DispatchOrder.php'),
  2181. `<?php\nclass DispatchOrder {\n public function handle(): void {\n ApiClient::for('cred')->createOrder([]);\n }\n}\n`
  2182. );
  2183. cg = await CodeGraph.init(tempDir, { index: true });
  2184. // The chained call's edge attaches to the factory result's method.
  2185. expect(callerNamesOf('ApiClient::createOrder')).toContain('handle');
  2186. });
  2187. it('creates NO edge when the factory result lacks the method (#608)', async () => {
  2188. fs.writeFileSync(
  2189. path.join(tempDir, 'lib.php'),
  2190. `<?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`
  2191. );
  2192. cg = await CodeGraph.init(tempDir, { index: true });
  2193. // ApiClient has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  2194. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2195. });
  2196. });
  2197. describe('Java chained static-factory call resolution (#645/#608 mechanism)', () => {
  2198. function callerNamesOf(qualifiedName: string): string[] {
  2199. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2200. if (!target) return [];
  2201. const names = cg
  2202. .getIncomingEdges(target.id)
  2203. .filter((e) => e.kind === 'calls')
  2204. .map((e) => cg.getNode(e.source)?.name)
  2205. .filter((n): n is string => !!n);
  2206. return [...new Set(names)].sort();
  2207. }
  2208. it('resolves Foo.getInstance().bar() via the factory return type, never a same-named decoy', async () => {
  2209. // Aaa sorts first and has a same-named bar() — it must never win the chain.
  2210. fs.writeFileSync(
  2211. path.join(tempDir, 'Main.java'),
  2212. `class Aaa { void bar() {} }
  2213. class Foo {
  2214. static Foo getInstance() { return new Foo(); }
  2215. void bar() {}
  2216. }
  2217. class Caller {
  2218. void run() { Foo.getInstance().bar(); }
  2219. }
  2220. `
  2221. );
  2222. cg = await CodeGraph.init(tempDir, { index: true });
  2223. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2224. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2225. });
  2226. it('resolves a factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2227. // The factory call carries an argument; the extractor must normalize the
  2228. // receiver to empty parens (`Foo.create().build`) so the chain still splits.
  2229. fs.writeFileSync(
  2230. path.join(tempDir, 'Main.java'),
  2231. `class Config {}
  2232. class Foo {
  2233. static Foo create(Config c) { return new Foo(); }
  2234. void build() {}
  2235. }
  2236. class Caller {
  2237. void run() { Foo.create(new Config()).build(); }
  2238. }
  2239. `
  2240. );
  2241. cg = await CodeGraph.init(tempDir, { index: true });
  2242. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2243. });
  2244. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2245. fs.writeFileSync(
  2246. path.join(tempDir, 'Main.java'),
  2247. `class Foo {
  2248. static Foo getInstance() { return new Foo(); }
  2249. }
  2250. class Other { void onlyOther() {} }
  2251. class Caller {
  2252. void run() { Foo.getInstance().onlyOther(); }
  2253. }
  2254. `
  2255. );
  2256. cg = await CodeGraph.init(tempDir, { index: true });
  2257. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2258. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2259. });
  2260. });
  2261. describe('Kotlin chained companion-factory call resolution (#645/#608 mechanism)', () => {
  2262. function callerNamesOf(qualifiedName: string): string[] {
  2263. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2264. if (!target) return [];
  2265. const names = cg
  2266. .getIncomingEdges(target.id)
  2267. .filter((e) => e.kind === 'calls')
  2268. .map((e) => cg.getNode(e.source)?.name)
  2269. .filter((n): n is string => !!n);
  2270. return [...new Set(names)].sort();
  2271. }
  2272. it('resolves Foo.getInstance().bar() via the companion return type, never a same-named decoy', async () => {
  2273. // Aaa sorts first and has a same-named bar() — without the chain fix Kotlin
  2274. // dropped the receiver to a bare `bar` and attached to Aaa (a wrong edge).
  2275. fs.writeFileSync(
  2276. path.join(tempDir, 'Main.kt'),
  2277. `class Aaa { fun bar() {} }
  2278. class Foo {
  2279. companion object {
  2280. fun getInstance(): Foo = Foo()
  2281. }
  2282. fun bar() {}
  2283. }
  2284. class Caller {
  2285. fun run() { Foo.getInstance().bar() }
  2286. }
  2287. `
  2288. );
  2289. cg = await CodeGraph.init(tempDir, { index: true });
  2290. expect(callerNamesOf('Foo::bar')).toEqual(['run']);
  2291. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2292. });
  2293. it('resolves a companion factory chain that passes arguments — Foo.create(cfg).build()', async () => {
  2294. fs.writeFileSync(
  2295. path.join(tempDir, 'Main.kt'),
  2296. `class Config
  2297. class Foo {
  2298. companion object {
  2299. fun create(c: Config): Foo = Foo()
  2300. }
  2301. fun build() {}
  2302. }
  2303. class Caller {
  2304. fun run() { Foo.create(Config()).build() }
  2305. }
  2306. `
  2307. );
  2308. cg = await CodeGraph.init(tempDir, { index: true });
  2309. expect(callerNamesOf('Foo::build')).toEqual(['run']);
  2310. });
  2311. it('creates NO edge when the companion return type lacks the method (silent miss, not a wrong edge)', async () => {
  2312. fs.writeFileSync(
  2313. path.join(tempDir, 'Main.kt'),
  2314. `class Foo {
  2315. companion object {
  2316. fun getInstance(): Foo = Foo()
  2317. }
  2318. }
  2319. class Other { fun onlyOther() {} }
  2320. class Caller {
  2321. fun run() { Foo.getInstance().onlyOther() }
  2322. }
  2323. `
  2324. );
  2325. cg = await CodeGraph.init(tempDir, { index: true });
  2326. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2327. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2328. });
  2329. });
  2330. describe('C# chained static-factory call resolution (#645/#608 mechanism)', () => {
  2331. function callerNamesOf(qualifiedName: string): string[] {
  2332. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2333. if (!target) return [];
  2334. const names = cg
  2335. .getIncomingEdges(target.id)
  2336. .filter((e) => e.kind === 'calls')
  2337. .map((e) => cg.getNode(e.source)?.name)
  2338. .filter((n): n is string => !!n);
  2339. return [...new Set(names)].sort();
  2340. }
  2341. it('resolves Foo.Create().Bar() via the factory return type, never a same-named decoy', async () => {
  2342. // Aaa sorts first and has a same-named Bar() — it must never win the chain.
  2343. fs.writeFileSync(
  2344. path.join(tempDir, 'Main.cs'),
  2345. `class Aaa { void Bar() {} }
  2346. class Foo {
  2347. static Foo Create() { return new Foo(); }
  2348. void Bar() {}
  2349. }
  2350. class Caller {
  2351. void Run() { Foo.Create().Bar(); }
  2352. }
  2353. `
  2354. );
  2355. cg = await CodeGraph.init(tempDir, { index: true });
  2356. expect(callerNamesOf('Foo::Bar')).toEqual(['Run']);
  2357. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  2358. });
  2359. it('resolves a factory chain that passes arguments — Foo.Make(cfg).Build()', async () => {
  2360. fs.writeFileSync(
  2361. path.join(tempDir, 'Main.cs'),
  2362. `class Config {}
  2363. class Foo {
  2364. static Foo Make(Config c) { return new Foo(); }
  2365. void Build() {}
  2366. }
  2367. class Caller {
  2368. void Run() { Foo.Make(new Config()).Build(); }
  2369. }
  2370. `
  2371. );
  2372. cg = await CodeGraph.init(tempDir, { index: true });
  2373. expect(callerNamesOf('Foo::Build')).toEqual(['Run']);
  2374. });
  2375. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2376. fs.writeFileSync(
  2377. path.join(tempDir, 'Main.cs'),
  2378. `class Foo {
  2379. static Foo Create() { return new Foo(); }
  2380. }
  2381. class Other { void OnlyOther() {} }
  2382. class Caller {
  2383. void Run() { Foo.Create().OnlyOther(); }
  2384. }
  2385. `
  2386. );
  2387. cg = await CodeGraph.init(tempDir, { index: true });
  2388. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  2389. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  2390. });
  2391. });
  2392. describe('Swift chained static-factory call resolution (#645/#608 mechanism)', () => {
  2393. function callerNamesOf(qualifiedName: string): string[] {
  2394. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2395. if (!target) return [];
  2396. const names = cg
  2397. .getIncomingEdges(target.id)
  2398. .filter((e) => e.kind === 'calls')
  2399. .map((e) => cg.getNode(e.source)?.name)
  2400. .filter((n): n is string => !!n);
  2401. return [...new Set(names)].sort();
  2402. }
  2403. it('resolves Foo.make().draw() via the factory return type, never a same-named decoy', async () => {
  2404. // Aaa sorts first and has a same-named draw() — without the fix Swift dropped
  2405. // the receiver to a bare `draw` and attached to Aaa (a wrong edge).
  2406. fs.writeFileSync(
  2407. path.join(tempDir, 'Main.swift'),
  2408. `class Aaa { func draw() {} }
  2409. class Foo {
  2410. static func make() -> Foo { return Foo() }
  2411. func draw() {}
  2412. }
  2413. func runCaller() { Foo.make().draw() }
  2414. `
  2415. );
  2416. cg = await CodeGraph.init(tempDir, { index: true });
  2417. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2418. expect(callerNamesOf('Aaa::draw')).toEqual([]);
  2419. });
  2420. it('resolves a constructor chain Foo().draw() and an args factory chain Foo.build(c).render()', async () => {
  2421. fs.writeFileSync(
  2422. path.join(tempDir, 'Main.swift'),
  2423. `class Config {}
  2424. class Foo {
  2425. static func build(_ c: Config) -> Foo { return Foo() }
  2426. func draw() {}
  2427. func render() {}
  2428. }
  2429. func runCaller() {
  2430. Foo().draw()
  2431. Foo.build(Config()).render()
  2432. }
  2433. `
  2434. );
  2435. cg = await CodeGraph.init(tempDir, { index: true });
  2436. expect(callerNamesOf('Foo::draw')).toEqual(['runCaller']);
  2437. expect(callerNamesOf('Foo::render')).toEqual(['runCaller']);
  2438. });
  2439. it('creates NO edge when the factory return type lacks the method (silent miss, not a wrong edge)', async () => {
  2440. fs.writeFileSync(
  2441. path.join(tempDir, 'Main.swift'),
  2442. `class Foo {
  2443. static func make() -> Foo { return Foo() }
  2444. }
  2445. class Other { func onlyOther() {} }
  2446. func runCaller() { Foo.make().onlyOther() }
  2447. `
  2448. );
  2449. cg = await CodeGraph.init(tempDir, { index: true });
  2450. // Foo has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2451. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2452. });
  2453. });
  2454. describe('Chained call resolves a method on a supertype (conformance, #750)', () => {
  2455. function callerNamesOf(qualifiedName: string): string[] {
  2456. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2457. if (!target) return [];
  2458. const names = cg
  2459. .getIncomingEdges(target.id)
  2460. .filter((e) => e.kind === 'calls')
  2461. .map((e) => cg.getNode(e.source)?.name)
  2462. .filter((n): n is string => !!n);
  2463. return [...new Set(names)].sort();
  2464. }
  2465. it('resolves a chained method defined only on a SUPERCLASS the return type extends', async () => {
  2466. // draw() lives on Base; Widget (the factory's return type) has no draw() of
  2467. // its own. Decoy.draw must never win. Needs the conformance second pass.
  2468. fs.writeFileSync(
  2469. path.join(tempDir, 'Main.java'),
  2470. `class Base { void draw() {} }
  2471. class Widget extends Base {}
  2472. class Decoy { void draw() {} }
  2473. class Factory { static Widget create() { return new Widget(); } }
  2474. class Caller {
  2475. void run() { Factory.create().draw(); }
  2476. }
  2477. `
  2478. );
  2479. cg = await CodeGraph.init(tempDir, { index: true });
  2480. expect(callerNamesOf('Base::draw')).toEqual(['run']);
  2481. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2482. });
  2483. it('resolves a chained method defined on an INTERFACE the return type implements (default method)', async () => {
  2484. fs.writeFileSync(
  2485. path.join(tempDir, 'Main.java'),
  2486. `interface Drawable { default void draw() {} }
  2487. class Widget implements Drawable {}
  2488. class Decoy { void draw() {} }
  2489. class Factory { static Widget create() { return new Widget(); } }
  2490. class Caller {
  2491. void run() { Factory.create().draw(); }
  2492. }
  2493. `
  2494. );
  2495. cg = await CodeGraph.init(tempDir, { index: true });
  2496. expect(callerNamesOf('Drawable::draw')).toEqual(['run']);
  2497. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2498. });
  2499. it('still creates NO edge when no supertype has the method (safety preserved)', async () => {
  2500. fs.writeFileSync(
  2501. path.join(tempDir, 'Main.java'),
  2502. `class Base {}
  2503. class Widget extends Base {}
  2504. class Other { void onlyOther() {} }
  2505. class Factory { static Widget create() { return new Widget(); } }
  2506. class Caller {
  2507. void run() { Factory.create().onlyOther(); }
  2508. }
  2509. `
  2510. );
  2511. cg = await CodeGraph.init(tempDir, { index: true });
  2512. // Neither Widget nor Base has onlyOther() — must not attach to Other::onlyOther.
  2513. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2514. });
  2515. });
  2516. describe('Rust chained associated-function call resolution (#645/#608 mechanism)', () => {
  2517. function callerNamesOf(qualifiedName: string): string[] {
  2518. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2519. if (!target) return [];
  2520. const names = cg
  2521. .getIncomingEdges(target.id)
  2522. .filter((e) => e.kind === 'calls')
  2523. .map((e) => cg.getNode(e.source)?.name)
  2524. .filter((n): n is string => !!n);
  2525. return [...new Set(names)].sort();
  2526. }
  2527. it('resolves Foo::new().bar() (and a Self return) via the associated fn, never a same-named decoy', async () => {
  2528. fs.writeFileSync(
  2529. path.join(tempDir, 'main.rs'),
  2530. `struct Aaa { _x: i32 }
  2531. impl Aaa { fn bar(&self) {} }
  2532. struct Foo { _x: i32 }
  2533. impl Foo {
  2534. fn new() -> Foo { Foo { _x: 0 } }
  2535. fn make() -> Self { Foo { _x: 0 } }
  2536. fn bar(&self) {}
  2537. }
  2538. fn caller() {
  2539. Foo::new().bar();
  2540. Foo::make().bar();
  2541. }
  2542. `
  2543. );
  2544. cg = await CodeGraph.init(tempDir, { index: true });
  2545. expect(callerNamesOf('Foo::bar')).toEqual(['caller']);
  2546. expect(callerNamesOf('Aaa::bar')).toEqual([]);
  2547. });
  2548. it('resolves a chain that passes arguments — Foo::with(c).build()', async () => {
  2549. fs.writeFileSync(
  2550. path.join(tempDir, 'main.rs'),
  2551. `struct Config;
  2552. struct Foo { _x: i32 }
  2553. impl Foo {
  2554. fn with(c: Config) -> Foo { Foo { _x: 0 } }
  2555. fn build(&self) {}
  2556. }
  2557. fn caller() { Foo::with(Config).build(); }
  2558. `
  2559. );
  2560. cg = await CodeGraph.init(tempDir, { index: true });
  2561. expect(callerNamesOf('Foo::build')).toEqual(['caller']);
  2562. });
  2563. it('resolves a chained method from a trait the type implements (default method, via conformance)', async () => {
  2564. fs.writeFileSync(
  2565. path.join(tempDir, 'main.rs'),
  2566. `struct Foo { _x: i32 }
  2567. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  2568. struct Decoy { _x: i32 }
  2569. impl Decoy { fn draw(&self) {} }
  2570. trait Drawable { fn draw(&self) {} }
  2571. impl Drawable for Foo {}
  2572. fn caller() { Foo::new().draw(); }
  2573. `
  2574. );
  2575. cg = await CodeGraph.init(tempDir, { index: true });
  2576. expect(callerNamesOf('Drawable::draw')).toEqual(['caller']);
  2577. expect(callerNamesOf('Decoy::draw')).toEqual([]);
  2578. });
  2579. it('creates NO edge when neither the type nor a supertype has the method (silent miss)', async () => {
  2580. fs.writeFileSync(
  2581. path.join(tempDir, 'main.rs'),
  2582. `struct Foo { _x: i32 }
  2583. impl Foo { fn new() -> Foo { Foo { _x: 0 } } }
  2584. struct Other { _x: i32 }
  2585. impl Other { fn only_other(&self) {} }
  2586. fn caller() { Foo::new().only_other(); }
  2587. `
  2588. );
  2589. cg = await CodeGraph.init(tempDir, { index: true });
  2590. // Foo has no only_other() — must not mis-attach to the same-named Other::only_other.
  2591. expect(callerNamesOf('Other::only_other')).toEqual([]);
  2592. });
  2593. });
  2594. describe('Go chained factory-function call resolution (#645/#608 mechanism)', () => {
  2595. function callerNamesOf(qualifiedName: string): string[] {
  2596. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2597. if (!target) return [];
  2598. const names = cg
  2599. .getIncomingEdges(target.id)
  2600. .filter((e) => e.kind === 'calls')
  2601. .map((e) => cg.getNode(e.source)?.name)
  2602. .filter((n): n is string => !!n);
  2603. return [...new Set(names)].sort();
  2604. }
  2605. it('resolves New().Bar() via the factory return type (pointer), never a same-named decoy', async () => {
  2606. fs.writeFileSync(
  2607. path.join(tempDir, 'main.go'),
  2608. `package main
  2609. type Aaa struct{}
  2610. func (a *Aaa) Bar() {}
  2611. type Foo struct{}
  2612. func New() *Foo { return &Foo{} }
  2613. func (f *Foo) Bar() {}
  2614. func caller() { New().Bar() }
  2615. `
  2616. );
  2617. cg = await CodeGraph.init(tempDir, { index: true });
  2618. expect(callerNamesOf('Foo::Bar')).toEqual(['caller']);
  2619. expect(callerNamesOf('Aaa::Bar')).toEqual([]);
  2620. });
  2621. it('resolves an args chain and a multi-return factory — With(c).Build(), (*Foo, error)', async () => {
  2622. fs.writeFileSync(
  2623. path.join(tempDir, 'main.go'),
  2624. `package main
  2625. type Config struct{}
  2626. type Foo struct{}
  2627. func With(c Config) (*Foo, error) { return &Foo{}, nil }
  2628. func (f *Foo) Build() {}
  2629. func caller() { With(Config{}).Build() }
  2630. `
  2631. );
  2632. cg = await CodeGraph.init(tempDir, { index: true });
  2633. expect(callerNamesOf('Foo::Build')).toEqual(['caller']);
  2634. });
  2635. it('resolves a method provided by an embedded struct (via conformance)', async () => {
  2636. fs.writeFileSync(
  2637. path.join(tempDir, 'main.go'),
  2638. `package main
  2639. type Base struct{}
  2640. func (b *Base) Embedded() {}
  2641. type Decoy struct{}
  2642. func (d *Decoy) Embedded() {}
  2643. type Widget struct{ Base }
  2644. func NewWidget() *Widget { return &Widget{} }
  2645. func caller() { NewWidget().Embedded() }
  2646. `
  2647. );
  2648. cg = await CodeGraph.init(tempDir, { index: true });
  2649. expect(callerNamesOf('Base::Embedded')).toEqual(['caller']);
  2650. expect(callerNamesOf('Decoy::Embedded')).toEqual([]);
  2651. });
  2652. it('creates NO edge when neither the type nor an embedded type has the method (silent miss)', async () => {
  2653. fs.writeFileSync(
  2654. path.join(tempDir, 'main.go'),
  2655. `package main
  2656. type Foo struct{}
  2657. func New() *Foo { return &Foo{} }
  2658. type Other struct{}
  2659. func (o *Other) OnlyOther() {}
  2660. func caller() { New().OnlyOther() }
  2661. `
  2662. );
  2663. cg = await CodeGraph.init(tempDir, { index: true });
  2664. // Foo has no OnlyOther() — must not mis-attach to the same-named Other::OnlyOther.
  2665. expect(callerNamesOf('Other::OnlyOther')).toEqual([]);
  2666. });
  2667. it('falls back to bare-name resolution for a VARIABLE-inner chain without exploding the graph', async () => {
  2668. // `engine` is a package-level VARIABLE holding a func value, not a factory
  2669. // FUNCTION — so its return type can't be recovered and the chain falls back
  2670. // to bare-name resolution of the method (restoring the pre-re-encoding edge).
  2671. // Regression for the runaway this fallback originally caused: it resolved
  2672. // with a mutated `original.referenceName` (the bare `ServeHTTP`, not the
  2673. // stored `engine().ServeHTTP`), so the batched resolver's keyed delete
  2674. // no-oped, the offset-0 batch never drained, and edges inserted forever
  2675. // (5M edges / 1.4 GB on a 99-file repo). The fallback now ties the match to
  2676. // the original ref, and a non-progress guard backstops the loop.
  2677. fs.writeFileSync(
  2678. path.join(tempDir, 'main.go'),
  2679. `package main
  2680. type Server struct{}
  2681. func (s *Server) ServeHTTP() {}
  2682. var engine = func() *Server { return &Server{} }
  2683. func caller() { engine().ServeHTTP() }
  2684. `
  2685. );
  2686. cg = await CodeGraph.init(tempDir, { index: true });
  2687. // Recall: the variable-inner chain still finds the method by bare name.
  2688. expect(callerNamesOf('Server::ServeHTTP')).toEqual(['caller']);
  2689. // No runaway: a single call site yields a single edge, not millions.
  2690. const target = cg
  2691. .getNodesByKind('method')
  2692. .find((n) => n.qualifiedName === 'Server::ServeHTTP')!;
  2693. const rawCalls = cg
  2694. .getIncomingEdges(target.id)
  2695. .filter((e) => e.kind === 'calls');
  2696. expect(rawCalls.length).toBeLessThan(5);
  2697. });
  2698. });
  2699. describe('Scala chained static-factory call resolution (#645/#608 mechanism)', () => {
  2700. function callerNamesOf(qualifiedName: string): string[] {
  2701. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2702. if (!target) return [];
  2703. const names = cg
  2704. .getIncomingEdges(target.id)
  2705. .filter((e) => e.kind === 'calls')
  2706. .map((e) => cg.getNode(e.source)?.name)
  2707. .filter((n): n is string => !!n);
  2708. return [...new Set(names)].sort();
  2709. }
  2710. it('resolves a companion-factory chain Foo.create().doIt() to the return type, never a same-named decoy', async () => {
  2711. fs.writeFileSync(
  2712. path.join(tempDir, 'Main.scala'),
  2713. `object Foo {
  2714. def create(): Bar = new Bar()
  2715. }
  2716. class Bar {
  2717. def doIt(): Unit = {}
  2718. }
  2719. class Decoy {
  2720. def doIt(): Unit = {}
  2721. }
  2722. object Main {
  2723. def run(): Unit = { Foo.create().doIt() }
  2724. }
  2725. `
  2726. );
  2727. cg = await CodeGraph.init(tempDir, { index: true });
  2728. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  2729. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  2730. });
  2731. it('resolves a case-class apply construction Point(x).dist() on the constructed class', async () => {
  2732. fs.writeFileSync(
  2733. path.join(tempDir, 'Main.scala'),
  2734. `class Point(x: Int) {
  2735. def dist(): Int = x
  2736. }
  2737. class Other {
  2738. def dist(): Int = 0
  2739. }
  2740. object Main {
  2741. def run(): Unit = { Point(3).dist() }
  2742. }
  2743. `
  2744. );
  2745. cg = await CodeGraph.init(tempDir, { index: true });
  2746. expect(callerNamesOf('Point::dist')).toEqual(['run']);
  2747. expect(callerNamesOf('Other::dist')).toEqual([]);
  2748. });
  2749. it('resolves a chained method provided by a trait the return type extends (via conformance)', async () => {
  2750. fs.writeFileSync(
  2751. path.join(tempDir, 'Main.scala'),
  2752. `trait Base {
  2753. def shared(): Unit = {}
  2754. }
  2755. class Widget extends Base
  2756. class Decoy {
  2757. def shared(): Unit = {}
  2758. }
  2759. object Factory {
  2760. def make(): Widget = new Widget()
  2761. }
  2762. object Main {
  2763. def run(): Unit = { Factory.make().shared() }
  2764. }
  2765. `
  2766. );
  2767. cg = await CodeGraph.init(tempDir, { index: true });
  2768. expect(callerNamesOf('Base::shared')).toEqual(['run']);
  2769. expect(callerNamesOf('Decoy::shared')).toEqual([]);
  2770. });
  2771. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  2772. fs.writeFileSync(
  2773. path.join(tempDir, 'Main.scala'),
  2774. `object Foo {
  2775. def create(): Bar = new Bar()
  2776. }
  2777. class Bar {
  2778. }
  2779. class Other {
  2780. def onlyOther(): Unit = {}
  2781. }
  2782. object Main {
  2783. def run(): Unit = { Foo.create().onlyOther() }
  2784. }
  2785. `
  2786. );
  2787. cg = await CodeGraph.init(tempDir, { index: true });
  2788. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2789. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2790. });
  2791. });
  2792. describe('Dart chained static-factory / factory-constructor call resolution (#645/#608 mechanism)', () => {
  2793. function callerNamesOf(qualifiedName: string): string[] {
  2794. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2795. if (!target) return [];
  2796. const names = cg
  2797. .getIncomingEdges(target.id)
  2798. .filter((e) => e.kind === 'calls')
  2799. .map((e) => cg.getNode(e.source)?.name)
  2800. .filter((n): n is string => !!n);
  2801. return [...new Set(names)].sort();
  2802. }
  2803. it('resolves a static-factory chain Foo.makeBar().doIt() to the return type, never a same-named decoy', async () => {
  2804. fs.writeFileSync(
  2805. path.join(tempDir, 'main.dart'),
  2806. `class Foo {
  2807. static Bar makeBar() => Bar();
  2808. }
  2809. class Bar {
  2810. void doIt() {}
  2811. }
  2812. class Decoy {
  2813. void doIt() {}
  2814. }
  2815. void run() {
  2816. Foo.makeBar().doIt();
  2817. }
  2818. `
  2819. );
  2820. cg = await CodeGraph.init(tempDir, { index: true });
  2821. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  2822. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  2823. });
  2824. it('resolves a named factory-constructor chain Foo.create().ship() on the constructed class', async () => {
  2825. fs.writeFileSync(
  2826. path.join(tempDir, 'main.dart'),
  2827. `class Foo {
  2828. Foo._();
  2829. factory Foo.create() => Foo._();
  2830. void ship() {}
  2831. }
  2832. class Decoy {
  2833. void ship() {}
  2834. }
  2835. void run() {
  2836. Foo.create().ship();
  2837. }
  2838. `
  2839. );
  2840. cg = await CodeGraph.init(tempDir, { index: true });
  2841. // The factory constructor `Foo.create` is now a node whose return type is Foo,
  2842. // so `ship` resolves on Foo, not the same-named Decoy.
  2843. expect(callerNamesOf('Foo::ship')).toEqual(['run']);
  2844. expect(callerNamesOf('Decoy::ship')).toEqual([]);
  2845. });
  2846. it('resolves a constructor-receiver chain Bar().doIt() on the constructed class', async () => {
  2847. fs.writeFileSync(
  2848. path.join(tempDir, 'main.dart'),
  2849. `class Bar {
  2850. void doIt() {}
  2851. }
  2852. class Decoy {
  2853. void doIt() {}
  2854. }
  2855. void run() {
  2856. Bar().doIt();
  2857. }
  2858. `
  2859. );
  2860. cg = await CodeGraph.init(tempDir, { index: true });
  2861. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  2862. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  2863. });
  2864. it('resolves a chained method inherited from a superclass the return type extends (via conformance)', async () => {
  2865. fs.writeFileSync(
  2866. path.join(tempDir, 'main.dart'),
  2867. `class Base {
  2868. void render() {}
  2869. }
  2870. class Widget extends Base {
  2871. static Widget make() => Widget();
  2872. }
  2873. class Decoy {
  2874. void render() {}
  2875. }
  2876. void run() {
  2877. Widget.make().render();
  2878. }
  2879. `
  2880. );
  2881. cg = await CodeGraph.init(tempDir, { index: true });
  2882. expect(callerNamesOf('Base::render')).toEqual(['run']);
  2883. expect(callerNamesOf('Decoy::render')).toEqual([]);
  2884. });
  2885. it('creates NO edge when neither the factory return type nor a supertype has the method (silent miss)', async () => {
  2886. fs.writeFileSync(
  2887. path.join(tempDir, 'main.dart'),
  2888. `class Foo {
  2889. static Bar makeBar() => Bar();
  2890. }
  2891. class Bar {
  2892. }
  2893. class Other {
  2894. void onlyOther() {}
  2895. }
  2896. void run() {
  2897. Foo.makeBar().onlyOther();
  2898. }
  2899. `
  2900. );
  2901. cg = await CodeGraph.init(tempDir, { index: true });
  2902. // Bar has no onlyOther() — must not mis-attach to the same-named Other::onlyOther.
  2903. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  2904. });
  2905. it('still extracts a method tree-sitter misparses as a constructor (@override + record return)', async () => {
  2906. // tree-sitter-dart misparses `@override (A, B) reduce()` — the annotation
  2907. // swallows the record return type, so `reduce()` looks like a single-
  2908. // identifier constructor_signature. It must NOT be skipped as an unnamed
  2909. // ctor (its name doesn't match the class); its body call must attribute to
  2910. // `reduce`, not the class.
  2911. fs.writeFileSync(
  2912. path.join(tempDir, 'main.dart'),
  2913. `class Base {}
  2914. class Action extends Base {
  2915. Action({required int x});
  2916. @override
  2917. (int, String) reduce() {
  2918. return (compute(), "y");
  2919. }
  2920. int compute() => 1;
  2921. }
  2922. `
  2923. );
  2924. cg = await CodeGraph.init(tempDir, { index: true });
  2925. // reduce must be a node and its body call must resolve to Action::compute.
  2926. expect(callerNamesOf('Action::compute')).toEqual(['reduce']);
  2927. });
  2928. it('keeps plain construction Foo() as instantiation, not a Foo::Foo method call', async () => {
  2929. // The unnamed constructor is intentionally NOT extracted as a `Foo::Foo`
  2930. // method, so `Foo(...)` resolves to the class (an `instantiates` edge),
  2931. // never hijacked into a call to a phantom constructor method.
  2932. fs.writeFileSync(
  2933. path.join(tempDir, 'main.dart'),
  2934. `class Widget {
  2935. final int x;
  2936. Widget(this.x);
  2937. }
  2938. void run() {
  2939. Widget(3);
  2940. }
  2941. `
  2942. );
  2943. cg = await CodeGraph.init(tempDir, { index: true });
  2944. // No Foo::Foo phantom method node.
  2945. expect(cg.getNodesByKind('method').some((n) => n.qualifiedName === 'Widget::Widget')).toBe(false);
  2946. // The construction resolves to the class as an `instantiates` edge.
  2947. const widget = cg.getNodesByKind('class').find((n) => n.name === 'Widget')!;
  2948. const incoming = cg.getIncomingEdges(widget.id);
  2949. expect(incoming.some((e) => e.kind === 'instantiates')).toBe(true);
  2950. });
  2951. });
  2952. describe('Objective-C chained message-send call resolution (#645/#608 mechanism)', () => {
  2953. function callerNamesOf(qualifiedName: string): string[] {
  2954. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  2955. if (!target) return [];
  2956. const names = cg
  2957. .getIncomingEdges(target.id)
  2958. .filter((e) => e.kind === 'calls')
  2959. .map((e) => cg.getNode(e.source)?.name)
  2960. .filter((n): n is string => !!n);
  2961. return [...new Set(names)].sort();
  2962. }
  2963. it('resolves a chained message send [[Foo create] doIt] via the return type, never a same-named decoy', async () => {
  2964. fs.writeFileSync(
  2965. path.join(tempDir, 'main.m'),
  2966. `@interface Bar : NSObject
  2967. - (void)doIt;
  2968. @end
  2969. @implementation Bar
  2970. - (void)doIt {}
  2971. @end
  2972. @interface Decoy : NSObject
  2973. - (void)doIt;
  2974. @end
  2975. @implementation Decoy
  2976. - (void)doIt {}
  2977. @end
  2978. @interface Foo : NSObject
  2979. + (Bar *)create;
  2980. @end
  2981. @implementation Foo
  2982. + (Bar *)create { return nil; }
  2983. - (void)run { [[Foo create] doIt]; }
  2984. @end
  2985. `
  2986. );
  2987. cg = await CodeGraph.init(tempDir, { index: true });
  2988. expect(callerNamesOf('Bar::doIt')).toEqual(['run']);
  2989. expect(callerNamesOf('Decoy::doIt')).toEqual([]);
  2990. });
  2991. it('resolves a chained message whose method is inherited from a superclass (via conformance)', async () => {
  2992. fs.writeFileSync(
  2993. path.join(tempDir, 'main.m'),
  2994. `@interface Base : NSObject
  2995. - (void)render;
  2996. @end
  2997. @implementation Base
  2998. - (void)render {}
  2999. @end
  3000. @interface Widget : Base
  3001. @end
  3002. @implementation Widget
  3003. @end
  3004. @interface Decoy : NSObject
  3005. - (void)render;
  3006. @end
  3007. @implementation Decoy
  3008. - (void)render {}
  3009. @end
  3010. @interface Factory : NSObject
  3011. + (Widget *)make;
  3012. @end
  3013. @implementation Factory
  3014. + (Widget *)make { return nil; }
  3015. - (void)run { [[Factory make] render]; }
  3016. @end
  3017. `
  3018. );
  3019. cg = await CodeGraph.init(tempDir, { index: true });
  3020. expect(callerNamesOf('Base::render')).toEqual(['run']);
  3021. expect(callerNamesOf('Decoy::render')).toEqual([]);
  3022. });
  3023. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3024. fs.writeFileSync(
  3025. path.join(tempDir, 'main.m'),
  3026. `@interface Bar : NSObject
  3027. @end
  3028. @implementation Bar
  3029. @end
  3030. @interface Other : NSObject
  3031. - (void)onlyOther;
  3032. @end
  3033. @implementation Other
  3034. - (void)onlyOther {}
  3035. @end
  3036. @interface Foo : NSObject
  3037. + (Bar *)create;
  3038. @end
  3039. @implementation Foo
  3040. + (Bar *)create { return nil; }
  3041. - (void)run { [[Foo create] onlyOther]; }
  3042. @end
  3043. `
  3044. );
  3045. cg = await CodeGraph.init(tempDir, { index: true });
  3046. // Bar has no onlyOther — must not mis-attach to the same-named Other::onlyOther.
  3047. expect(callerNamesOf('Other::onlyOther')).toEqual([]);
  3048. });
  3049. it('resolves a singleton chain [[Cache shared] clearAll] whose factory returns nonnull instancetype', async () => {
  3050. // The factory returns `nonnull instancetype` — the nullability qualifier must
  3051. // be skipped (not captured AS the type), and an instancetype class-message
  3052. // factory returns the receiver class, so clearAll resolves on Cache, never a
  3053. // same-named decoy. (Regression for both: the captured-`nonnull` bug and the
  3054. // ubiquitous `[[X alloc] init]` / singleton pattern.)
  3055. fs.writeFileSync(
  3056. path.join(tempDir, 'main.m'),
  3057. `@interface Cache : NSObject
  3058. + (nonnull instancetype)shared;
  3059. - (void)clearAll;
  3060. @end
  3061. @implementation Cache
  3062. + (nonnull instancetype)shared { return nil; }
  3063. - (void)clearAll {}
  3064. @end
  3065. @interface Decoy : NSObject
  3066. - (void)clearAll;
  3067. @end
  3068. @implementation Decoy
  3069. - (void)clearAll {}
  3070. @end
  3071. @interface Caller : NSObject
  3072. - (void)run;
  3073. @end
  3074. @implementation Caller
  3075. - (void)run { [[Cache shared] clearAll]; }
  3076. @end
  3077. `
  3078. );
  3079. cg = await CodeGraph.init(tempDir, { index: true });
  3080. expect(callerNamesOf('Cache::clearAll')).toEqual(['run']);
  3081. expect(callerNamesOf('Decoy::clearAll')).toEqual([]);
  3082. });
  3083. });
  3084. describe('Pascal/Delphi chained static-factory call resolution (#645/#608 mechanism)', () => {
  3085. function callerNamesOf(qualifiedName: string): string[] {
  3086. const target = cg.getNodesByKind('method').find((n) => n.qualifiedName === qualifiedName);
  3087. if (!target) return [];
  3088. const names = cg
  3089. .getIncomingEdges(target.id)
  3090. .filter((e) => e.kind === 'calls')
  3091. .map((e) => cg.getNode(e.source)?.name)
  3092. .filter((n): n is string => !!n);
  3093. return [...new Set(names)].sort();
  3094. }
  3095. function isCalled(qn: string): boolean {
  3096. const t = cg.getNodesByKind('method').find((n) => n.qualifiedName === qn);
  3097. return !!t && cg.getIncomingEdges(t.id).some((e) => e.kind === 'calls');
  3098. }
  3099. it('resolves a chained factory call TFoo.GetInstance().DoIt() via the return type, never a same-named decoy', async () => {
  3100. fs.writeFileSync(
  3101. path.join(tempDir, 'main.pas'),
  3102. `unit Main;
  3103. interface
  3104. type
  3105. TBar = class
  3106. procedure DoIt;
  3107. end;
  3108. TDecoy = class
  3109. procedure DoIt;
  3110. end;
  3111. TFoo = class
  3112. class function GetInstance: TBar;
  3113. end;
  3114. implementation
  3115. procedure TBar.DoIt; begin end;
  3116. procedure TDecoy.DoIt; begin end;
  3117. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3118. procedure Run;
  3119. begin
  3120. TFoo.GetInstance().DoIt();
  3121. end;
  3122. end.
  3123. `
  3124. );
  3125. cg = await CodeGraph.init(tempDir, { index: true });
  3126. expect(isCalled('TBar::DoIt')).toBe(true);
  3127. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3128. });
  3129. it('resolves a constructor chain TFoo.Create().Configure() on the constructed class', async () => {
  3130. fs.writeFileSync(
  3131. path.join(tempDir, 'main.pas'),
  3132. `unit Main;
  3133. interface
  3134. type
  3135. TFoo = class
  3136. constructor Create;
  3137. procedure Configure;
  3138. end;
  3139. TDecoy = class
  3140. procedure Configure;
  3141. end;
  3142. implementation
  3143. constructor TFoo.Create; begin end;
  3144. procedure TFoo.Configure; begin end;
  3145. procedure TDecoy.Configure; begin end;
  3146. procedure Run;
  3147. begin
  3148. TFoo.Create().Configure();
  3149. end;
  3150. end.
  3151. `
  3152. );
  3153. cg = await CodeGraph.init(tempDir, { index: true });
  3154. // A constructor returns its own class (no `: TBar` annotation), so Configure
  3155. // resolves on TFoo, not the same-named decoy.
  3156. expect(isCalled('TFoo::Configure')).toBe(true);
  3157. expect(isCalled('TDecoy::Configure')).toBe(false);
  3158. });
  3159. it('resolves a typecast chain TFoo(x).DoIt() on the cast type', async () => {
  3160. fs.writeFileSync(
  3161. path.join(tempDir, 'main.pas'),
  3162. `unit Main;
  3163. interface
  3164. type
  3165. TFoo = class
  3166. procedure DoIt;
  3167. end;
  3168. TDecoy = class
  3169. procedure DoIt;
  3170. end;
  3171. implementation
  3172. procedure TFoo.DoIt; begin end;
  3173. procedure TDecoy.DoIt; begin end;
  3174. procedure Run(obj: TObject);
  3175. begin
  3176. TFoo(obj).DoIt();
  3177. end;
  3178. end.
  3179. `
  3180. );
  3181. cg = await CodeGraph.init(tempDir, { index: true });
  3182. expect(isCalled('TFoo::DoIt')).toBe(true);
  3183. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3184. });
  3185. it('creates NO edge when the factory return type lacks the method (silent miss)', async () => {
  3186. fs.writeFileSync(
  3187. path.join(tempDir, 'main.pas'),
  3188. `unit Main;
  3189. interface
  3190. type
  3191. TBar = class
  3192. end;
  3193. TOther = class
  3194. procedure OnlyOther;
  3195. end;
  3196. TFoo = class
  3197. class function GetInstance: TBar;
  3198. end;
  3199. implementation
  3200. procedure TOther.OnlyOther; begin end;
  3201. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3202. procedure Run;
  3203. begin
  3204. TFoo.GetInstance().OnlyOther();
  3205. end;
  3206. end.
  3207. `
  3208. );
  3209. cg = await CodeGraph.init(tempDir, { index: true });
  3210. // TBar has no OnlyOther — must not mis-attach to the same-named TOther::OnlyOther.
  3211. expect(isCalled('TOther::OnlyOther')).toBe(false);
  3212. });
  3213. it('extracts paren-less method calls (Pascal lets a no-arg method drop its parens)', async () => {
  3214. fs.writeFileSync(
  3215. path.join(tempDir, 'main.pas'),
  3216. `unit Main;
  3217. interface
  3218. type
  3219. TFoo = class
  3220. procedure DoThing;
  3221. procedure Reset;
  3222. end;
  3223. implementation
  3224. procedure TFoo.DoThing; begin end;
  3225. procedure TFoo.Reset; begin end;
  3226. procedure Run(f: TFoo);
  3227. begin
  3228. f.DoThing;
  3229. f.Reset;
  3230. end;
  3231. end.
  3232. `
  3233. );
  3234. cg = await CodeGraph.init(tempDir, { index: true });
  3235. expect(isCalled('TFoo::DoThing')).toBe(true);
  3236. expect(isCalled('TFoo::Reset')).toBe(true);
  3237. });
  3238. it('resolves a PAREN-LESS chained factory call TFoo.GetInstance.DoIt via the return type', async () => {
  3239. fs.writeFileSync(
  3240. path.join(tempDir, 'main.pas'),
  3241. `unit Main;
  3242. interface
  3243. type
  3244. TBar = class
  3245. procedure DoIt;
  3246. end;
  3247. TDecoy = class
  3248. procedure DoIt;
  3249. end;
  3250. TFoo = class
  3251. class function GetInstance: TBar;
  3252. end;
  3253. implementation
  3254. procedure TBar.DoIt; begin end;
  3255. procedure TDecoy.DoIt; begin end;
  3256. class function TFoo.GetInstance: TBar; begin Result := nil; end;
  3257. procedure Run;
  3258. begin
  3259. TFoo.GetInstance.DoIt;
  3260. end;
  3261. end.
  3262. `
  3263. );
  3264. cg = await CodeGraph.init(tempDir, { index: true });
  3265. expect(isCalled('TBar::DoIt')).toBe(true);
  3266. expect(isCalled('TDecoy::DoIt')).toBe(false);
  3267. });
  3268. it('does NOT turn a property write/read into a call edge (only statement-level dots are calls)', async () => {
  3269. fs.writeFileSync(
  3270. path.join(tempDir, 'main.pas'),
  3271. `unit Main;
  3272. interface
  3273. type
  3274. TFoo = class
  3275. function GetValue: Integer;
  3276. procedure SetValue(v: Integer);
  3277. property Value: Integer read GetValue write SetValue;
  3278. end;
  3279. implementation
  3280. function TFoo.GetValue: Integer; begin Result := 0; end;
  3281. procedure TFoo.SetValue(v: Integer); begin end;
  3282. procedure Run(f: TFoo);
  3283. var x: Integer;
  3284. begin
  3285. f.Value := 5;
  3286. x := f.Value;
  3287. end;
  3288. end.
  3289. `
  3290. );
  3291. cg = await CodeGraph.init(tempDir, { index: true });
  3292. // A property read/write is a bare dot in assignment position, not a statement,
  3293. // so it must not be mis-extracted as a call to the property's getter/setter.
  3294. expect(isCalled('TFoo::GetValue')).toBe(false);
  3295. expect(isCalled('TFoo::SetValue')).toBe(false);
  3296. });
  3297. it('attributes an implementation-only free procedure\'s calls to the procedure, not the file', async () => {
  3298. fs.writeFileSync(
  3299. path.join(tempDir, 'main.pas'),
  3300. `unit Main;
  3301. interface
  3302. type
  3303. TTgt = class
  3304. procedure Hit;
  3305. end;
  3306. TFoo = class
  3307. procedure DoStuff;
  3308. end;
  3309. implementation
  3310. procedure TTgt.Hit; begin end;
  3311. procedure TFoo.DoStuff; var t: TTgt; begin t.Hit; end;
  3312. procedure Helper; var t: TTgt; begin t.Hit; end;
  3313. `
  3314. );
  3315. cg = await CodeGraph.init(tempDir, { index: true });
  3316. // `Helper` is implementation-only (no interface decl, not a method), but its
  3317. // body's call must attribute to `Helper`, not the file/module — alongside the
  3318. // method `DoStuff`.
  3319. expect(callerNamesOf('TTgt::Hit')).toEqual(['DoStuff', 'Helper']);
  3320. });
  3321. });
  3322. });