resolution.test.ts 124 KB

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