1
0

extraction.test.ts 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeAll, 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 { extractFromSource, scanDirectory } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. beforeAll(async () => {
  15. await initGrammars();
  16. await loadAllGrammars();
  17. });
  18. // Create a temporary directory for each test
  19. function createTempDir(): string {
  20. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  21. }
  22. // Clean up temporary directory
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('Language Detection', () => {
  29. it('should detect TypeScript files', () => {
  30. expect(detectLanguage('src/index.ts')).toBe('typescript');
  31. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  32. });
  33. it('should detect JavaScript files', () => {
  34. expect(detectLanguage('index.js')).toBe('javascript');
  35. expect(detectLanguage('App.jsx')).toBe('jsx');
  36. expect(detectLanguage('config.mjs')).toBe('javascript');
  37. });
  38. it('should detect Python files', () => {
  39. expect(detectLanguage('main.py')).toBe('python');
  40. });
  41. it('should detect Go files', () => {
  42. expect(detectLanguage('main.go')).toBe('go');
  43. });
  44. it('should detect Rust files', () => {
  45. expect(detectLanguage('lib.rs')).toBe('rust');
  46. });
  47. it('should detect Java files', () => {
  48. expect(detectLanguage('Main.java')).toBe('java');
  49. });
  50. it('should detect C files', () => {
  51. expect(detectLanguage('main.c')).toBe('c');
  52. expect(detectLanguage('utils.h')).toBe('c');
  53. });
  54. it('should detect C++ files', () => {
  55. expect(detectLanguage('main.cpp')).toBe('cpp');
  56. expect(detectLanguage('class.hpp')).toBe('cpp');
  57. });
  58. it('should detect C# files', () => {
  59. expect(detectLanguage('Program.cs')).toBe('csharp');
  60. });
  61. it('should detect PHP files', () => {
  62. expect(detectLanguage('index.php')).toBe('php');
  63. });
  64. it('should detect Ruby files', () => {
  65. expect(detectLanguage('app.rb')).toBe('ruby');
  66. });
  67. it('should detect Swift files', () => {
  68. expect(detectLanguage('ViewController.swift')).toBe('swift');
  69. });
  70. it('should detect Kotlin files', () => {
  71. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  72. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  73. });
  74. it('should detect Dart files', () => {
  75. expect(detectLanguage('main.dart')).toBe('dart');
  76. });
  77. it('should detect Objective-C files', () => {
  78. expect(detectLanguage('AppDelegate.m')).toBe('objc');
  79. expect(detectLanguage('ViewController.mm')).toBe('objc');
  80. const objcHeader = '@interface Foo : NSObject\n@end\n';
  81. expect(detectLanguage('Foo.h', objcHeader)).toBe('objc');
  82. expect(detectLanguage('stdio.h', '#ifndef STDIO_H\nvoid printf();\n#endif\n')).toBe('c');
  83. });
  84. it('should return unknown for unsupported extensions', () => {
  85. expect(detectLanguage('styles.css')).toBe('unknown');
  86. expect(detectLanguage('data.json')).toBe('unknown');
  87. });
  88. });
  89. describe('Language Support', () => {
  90. it('should report supported languages', () => {
  91. expect(isLanguageSupported('typescript')).toBe(true);
  92. expect(isLanguageSupported('python')).toBe(true);
  93. expect(isLanguageSupported('go')).toBe(true);
  94. expect(isLanguageSupported('unknown')).toBe(false);
  95. });
  96. it('should list all supported languages', () => {
  97. const languages = getSupportedLanguages();
  98. expect(languages).toContain('typescript');
  99. expect(languages).toContain('javascript');
  100. expect(languages).toContain('python');
  101. expect(languages).toContain('go');
  102. expect(languages).toContain('rust');
  103. expect(languages).toContain('java');
  104. expect(languages).toContain('csharp');
  105. expect(languages).toContain('php');
  106. expect(languages).toContain('ruby');
  107. expect(languages).toContain('swift');
  108. expect(languages).toContain('kotlin');
  109. expect(languages).toContain('dart');
  110. });
  111. });
  112. describe('TypeScript Extraction', () => {
  113. it('should extract function declarations', () => {
  114. const code = `
  115. export function processPayment(amount: number): Promise<Receipt> {
  116. return stripe.charge(amount);
  117. }
  118. `;
  119. const result = extractFromSource('payment.ts', code);
  120. // File node + function node
  121. const fileNode = result.nodes.find((n) => n.kind === 'file');
  122. expect(fileNode).toBeDefined();
  123. expect(fileNode?.name).toBe('payment.ts');
  124. const funcNode = result.nodes.find((n) => n.kind === 'function');
  125. expect(funcNode).toMatchObject({
  126. kind: 'function',
  127. name: 'processPayment',
  128. language: 'typescript',
  129. isExported: true,
  130. });
  131. expect(funcNode?.signature).toContain('amount: number');
  132. });
  133. it('should extract class declarations', () => {
  134. const code = `
  135. export class PaymentService {
  136. private stripe: StripeClient;
  137. constructor(apiKey: string) {
  138. this.stripe = new StripeClient(apiKey);
  139. }
  140. async charge(amount: number): Promise<Receipt> {
  141. return this.stripe.charge(amount);
  142. }
  143. }
  144. `;
  145. const result = extractFromSource('service.ts', code);
  146. const classNode = result.nodes.find((n) => n.kind === 'class');
  147. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  148. expect(classNode).toBeDefined();
  149. expect(classNode?.name).toBe('PaymentService');
  150. expect(classNode?.isExported).toBe(true);
  151. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  152. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  153. expect(chargeMethod).toBeDefined();
  154. });
  155. it('should extract interfaces', () => {
  156. const code = `
  157. export interface User {
  158. id: string;
  159. name: string;
  160. email: string;
  161. }
  162. `;
  163. const result = extractFromSource('types.ts', code);
  164. const fileNode = result.nodes.find((n) => n.kind === 'file');
  165. expect(fileNode).toBeDefined();
  166. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  167. expect(ifaceNode).toMatchObject({
  168. kind: 'interface',
  169. name: 'User',
  170. isExported: true,
  171. });
  172. });
  173. it('should extract type references from interface property signatures', () => {
  174. const code = `
  175. import type { IPage } from '../PromoterList';
  176. import type { IOrderField } from '../types';
  177. interface Hprops {
  178. value?: Partial<IPage> & Partial<IOrderField>;
  179. }
  180. `;
  181. const result = extractFromSource('HeaderFilter.ts', code);
  182. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  183. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  184. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  185. });
  186. it('should extract type references from interface method signatures', () => {
  187. const code = `
  188. import type { IPage } from '../PromoterList';
  189. import type { IOrderField } from '../types';
  190. interface MethodForm {
  191. fetchPage(arg: IPage): IOrderField;
  192. }
  193. `;
  194. const result = extractFromSource('MethodForm.ts', code);
  195. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  196. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  197. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  198. });
  199. it('should track function calls', () => {
  200. const code = `
  201. function main() {
  202. const result = processData();
  203. console.log(result);
  204. }
  205. `;
  206. const result = extractFromSource('main.ts', code);
  207. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  208. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  209. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  210. });
  211. });
  212. describe('Arrow Function Export Extraction', () => {
  213. it('should extract exported arrow functions assigned to const', () => {
  214. const code = `
  215. export const useAuth = (): AuthContextValue => {
  216. return useContext(AuthContext);
  217. };
  218. `;
  219. const result = extractFromSource('hooks.ts', code);
  220. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  221. expect(funcNode).toBeDefined();
  222. expect(funcNode).toMatchObject({
  223. kind: 'function',
  224. name: 'useAuth',
  225. isExported: true,
  226. });
  227. });
  228. it('should extract exported function expressions assigned to const', () => {
  229. const code = `
  230. export const processData = function(input: string): string {
  231. return input.trim();
  232. };
  233. `;
  234. const result = extractFromSource('utils.ts', code);
  235. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  236. expect(funcNode).toBeDefined();
  237. expect(funcNode).toMatchObject({
  238. kind: 'function',
  239. name: 'processData',
  240. isExported: true,
  241. });
  242. });
  243. it('should not extract non-exported arrow functions as exported', () => {
  244. const code = `
  245. const internalHelper = () => {
  246. return 42;
  247. };
  248. `;
  249. const result = extractFromSource('internal.ts', code);
  250. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  251. expect(helperNode).toBeDefined();
  252. expect(helperNode?.isExported).toBeFalsy();
  253. });
  254. it('should still skip truly anonymous arrow functions', () => {
  255. const code = `
  256. const items = [1, 2, 3].map((x) => x * 2);
  257. `;
  258. const result = extractFromSource('anon.ts', code);
  259. // The inline arrow function passed to .map() has no variable_declarator parent
  260. // and should remain anonymous (skipped)
  261. const anonFunctions = result.nodes.filter(
  262. (n) => n.kind === 'function' && n.name === '<anonymous>'
  263. );
  264. expect(anonFunctions).toHaveLength(0);
  265. });
  266. it('should extract multiple exported arrow functions from the same file', () => {
  267. const code = `
  268. export const add = (a: number, b: number): number => a + b;
  269. export const subtract = (a: number, b: number): number => a - b;
  270. const internal = () => 'not exported';
  271. `;
  272. const result = extractFromSource('math.ts', code);
  273. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  274. expect(exported).toHaveLength(2);
  275. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  276. const internalNode = result.nodes.find((n) => n.name === 'internal');
  277. expect(internalNode).toBeDefined();
  278. expect(internalNode?.isExported).toBeFalsy();
  279. });
  280. it('should extract arrow functions in JavaScript files', () => {
  281. const code = `
  282. export const fetchData = async () => {
  283. const response = await fetch('/api/data');
  284. return response.json();
  285. };
  286. `;
  287. const result = extractFromSource('api.js', code);
  288. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  289. expect(funcNode).toBeDefined();
  290. expect(funcNode).toMatchObject({
  291. kind: 'function',
  292. name: 'fetchData',
  293. isExported: true,
  294. });
  295. });
  296. });
  297. describe('Type Alias Extraction', () => {
  298. it('should extract exported type aliases in TypeScript', () => {
  299. const code = `
  300. export type AuthContextValue = {
  301. user: User | null;
  302. login: () => void;
  303. logout: () => void;
  304. };
  305. `;
  306. const result = extractFromSource('types.ts', code);
  307. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  308. expect(typeNode).toMatchObject({
  309. kind: 'type_alias',
  310. name: 'AuthContextValue',
  311. isExported: true,
  312. });
  313. });
  314. it('should extract non-exported type aliases', () => {
  315. const code = `
  316. type InternalState = {
  317. loading: boolean;
  318. error: string | null;
  319. };
  320. `;
  321. const result = extractFromSource('internal.ts', code);
  322. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  323. expect(typeNode).toMatchObject({
  324. kind: 'type_alias',
  325. name: 'InternalState',
  326. isExported: false,
  327. });
  328. });
  329. it('should extract multiple type aliases from the same file', () => {
  330. const code = `
  331. export type UnitSystem = 'metric' | 'imperial';
  332. export type DateFormat = 'ISO' | 'US' | 'EU';
  333. type Internal = string;
  334. `;
  335. const result = extractFromSource('config.ts', code);
  336. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  337. expect(typeAliases).toHaveLength(3);
  338. const exported = typeAliases.filter((n) => n.isExported);
  339. expect(exported).toHaveLength(2);
  340. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  341. });
  342. });
  343. describe('Exported Variable Extraction', () => {
  344. it('should extract exported const with call expression (Zustand store)', () => {
  345. const code = `
  346. export const useUIStore = create<UIState>((set) => ({
  347. isOpen: false,
  348. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  349. }));
  350. `;
  351. const result = extractFromSource('store.ts', code);
  352. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  353. expect(varNode).toBeDefined();
  354. expect(varNode?.isExported).toBe(true);
  355. });
  356. it('should extract exported const with object literal', () => {
  357. const code = `
  358. export const config = {
  359. apiUrl: 'https://api.example.com',
  360. timeout: 5000,
  361. };
  362. `;
  363. const result = extractFromSource('config.ts', code);
  364. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  365. expect(varNode).toBeDefined();
  366. expect(varNode?.isExported).toBe(true);
  367. });
  368. it('should extract exported const with array literal', () => {
  369. const code = `
  370. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  371. `;
  372. const result = extractFromSource('constants.ts', code);
  373. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  374. expect(varNode).toBeDefined();
  375. expect(varNode?.isExported).toBe(true);
  376. });
  377. it('should extract exported const with primitive value', () => {
  378. const code = `
  379. export const MAX_RETRIES = 3;
  380. export const API_VERSION = "v2";
  381. `;
  382. const result = extractFromSource('constants.ts', code);
  383. const variables = result.nodes.filter((n) => n.kind === 'constant');
  384. expect(variables).toHaveLength(2);
  385. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  386. });
  387. it('should NOT duplicate arrow functions as both function and variable', () => {
  388. const code = `
  389. export const useAuth = () => {
  390. return useContext(AuthContext);
  391. };
  392. `;
  393. const result = extractFromSource('hooks.ts', code);
  394. // Should be extracted as function (from arrow function handler), NOT as variable
  395. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  396. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  397. expect(funcNodes).toHaveLength(1);
  398. expect(varNodes).toHaveLength(0);
  399. });
  400. it('should extract non-exported const as non-exported variable', () => {
  401. const code = `
  402. const internalConfig = {
  403. debug: true,
  404. };
  405. `;
  406. const result = extractFromSource('internal.ts', code);
  407. // Non-exported const at file level should be extracted as a constant (not exported)
  408. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  409. expect(varNodes).toHaveLength(1);
  410. expect(varNodes[0]?.isExported).toBeFalsy();
  411. });
  412. it('should extract Zod schema exports', () => {
  413. const code = `
  414. export const userSchema = z.object({
  415. id: z.string(),
  416. name: z.string(),
  417. email: z.string().email(),
  418. });
  419. `;
  420. const result = extractFromSource('schemas.ts', code);
  421. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  422. expect(varNode).toBeDefined();
  423. expect(varNode?.isExported).toBe(true);
  424. });
  425. it('should extract XState machine exports', () => {
  426. const code = `
  427. export const authMachine = createMachine({
  428. id: "auth",
  429. initial: "idle",
  430. states: {
  431. idle: {},
  432. authenticated: {},
  433. },
  434. });
  435. `;
  436. const result = extractFromSource('machine.ts', code);
  437. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  438. expect(varNode).toBeDefined();
  439. expect(varNode?.isExported).toBe(true);
  440. });
  441. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  442. const code = `
  443. import { getTokenMp } from './api/upload';
  444. const token = getTokenMp();
  445. `;
  446. const result = extractFromSource('app.ts', code);
  447. const call = result.unresolvedReferences.find(
  448. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  449. );
  450. expect(call).toBeDefined();
  451. });
  452. });
  453. describe('File Node Extraction', () => {
  454. it('should create a file-kind node for each parsed file', () => {
  455. const code = `
  456. export function greet(name: string): string {
  457. return "Hello " + name;
  458. }
  459. `;
  460. const result = extractFromSource('greeter.ts', code);
  461. const fileNode = result.nodes.find((n) => n.kind === 'file');
  462. expect(fileNode).toBeDefined();
  463. expect(fileNode?.name).toBe('greeter.ts');
  464. expect(fileNode?.filePath).toBe('greeter.ts');
  465. expect(fileNode?.language).toBe('typescript');
  466. expect(fileNode?.startLine).toBe(1);
  467. });
  468. it('should create file nodes for Python files', () => {
  469. const code = `
  470. def main():
  471. pass
  472. `;
  473. const result = extractFromSource('main.py', code);
  474. const fileNode = result.nodes.find((n) => n.kind === 'file');
  475. expect(fileNode).toBeDefined();
  476. expect(fileNode?.name).toBe('main.py');
  477. expect(fileNode?.language).toBe('python');
  478. });
  479. it('should create containment edges from file node to top-level declarations', () => {
  480. const code = `
  481. export function foo() {}
  482. export function bar() {}
  483. `;
  484. const result = extractFromSource('fns.ts', code);
  485. const fileNode = result.nodes.find((n) => n.kind === 'file');
  486. expect(fileNode).toBeDefined();
  487. // There should be contains edges from the file node to each function
  488. const containsEdges = result.edges.filter(
  489. (e) => e.source === fileNode?.id && e.kind === 'contains'
  490. );
  491. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  492. });
  493. });
  494. describe('Python Extraction', () => {
  495. it('should extract function definitions', () => {
  496. const code = `
  497. def calculate_total(items: list, tax_rate: float) -> float:
  498. """Calculate total with tax."""
  499. subtotal = sum(item.price for item in items)
  500. return subtotal * (1 + tax_rate)
  501. `;
  502. const result = extractFromSource('calc.py', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. const funcNode = result.nodes.find((n) => n.kind === 'function');
  506. expect(funcNode).toMatchObject({
  507. kind: 'function',
  508. name: 'calculate_total',
  509. language: 'python',
  510. });
  511. });
  512. it('should extract class definitions', () => {
  513. const code = `
  514. class UserService:
  515. """Service for managing users."""
  516. def __init__(self, db):
  517. self.db = db
  518. def get_user(self, user_id: str) -> User:
  519. return self.db.find_user(user_id)
  520. `;
  521. const result = extractFromSource('service.py', code);
  522. const classNode = result.nodes.find((n) => n.kind === 'class');
  523. expect(classNode).toBeDefined();
  524. expect(classNode?.name).toBe('UserService');
  525. });
  526. });
  527. describe('Go Extraction', () => {
  528. it('should extract function declarations', () => {
  529. const code = `
  530. package main
  531. func ProcessOrder(order Order) (Receipt, error) {
  532. // Process the order
  533. return Receipt{}, nil
  534. }
  535. `;
  536. const result = extractFromSource('main.go', code);
  537. const funcNode = result.nodes.find((n) => n.kind === 'function');
  538. expect(funcNode).toBeDefined();
  539. expect(funcNode?.name).toBe('ProcessOrder');
  540. });
  541. it('should extract method declarations', () => {
  542. const code = `
  543. package main
  544. type Service struct {
  545. db *Database
  546. }
  547. func (s *Service) GetUser(id string) (*User, error) {
  548. return s.db.FindUser(id)
  549. }
  550. `;
  551. const result = extractFromSource('service.go', code);
  552. const methodNode = result.nodes.find((n) => n.kind === 'method');
  553. expect(methodNode).toBeDefined();
  554. expect(methodNode?.name).toBe('GetUser');
  555. });
  556. });
  557. describe('Rust Extraction', () => {
  558. it('should extract function declarations', () => {
  559. const code = `
  560. pub fn process_data(input: &str) -> Result<Output, Error> {
  561. // Process data
  562. Ok(Output::new())
  563. }
  564. `;
  565. const result = extractFromSource('lib.rs', code);
  566. const funcNode = result.nodes.find((n) => n.kind === 'function');
  567. expect(funcNode).toBeDefined();
  568. expect(funcNode?.name).toBe('process_data');
  569. expect(funcNode?.visibility).toBe('public');
  570. });
  571. it('should extract struct declarations', () => {
  572. const code = `
  573. pub struct User {
  574. pub id: String,
  575. pub name: String,
  576. email: String,
  577. }
  578. `;
  579. const result = extractFromSource('models.rs', code);
  580. const structNode = result.nodes.find((n) => n.kind === 'struct');
  581. expect(structNode).toBeDefined();
  582. expect(structNode?.name).toBe('User');
  583. });
  584. it('should extract trait declarations', () => {
  585. const code = `
  586. pub trait Repository {
  587. fn find(&self, id: &str) -> Option<Entity>;
  588. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  589. }
  590. `;
  591. const result = extractFromSource('traits.rs', code);
  592. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  593. expect(traitNode).toBeDefined();
  594. expect(traitNode?.name).toBe('Repository');
  595. });
  596. it('should extract impl Trait for Type as implements edges', () => {
  597. const code = `
  598. pub struct MyCache {}
  599. pub trait Cache {
  600. fn get(&self, key: &str) -> Option<String>;
  601. }
  602. impl Cache for MyCache {
  603. fn get(&self, key: &str) -> Option<String> {
  604. None
  605. }
  606. }
  607. `;
  608. const result = extractFromSource('cache.rs', code);
  609. // Should have an unresolved reference for implements
  610. const implRef = result.unresolvedReferences.find(
  611. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  612. );
  613. expect(implRef).toBeDefined();
  614. // The struct MyCache should be the source
  615. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  616. expect(myCacheNode).toBeDefined();
  617. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  618. });
  619. it('should extract trait supertraits as extends references', () => {
  620. const code = `
  621. pub trait Display {}
  622. pub trait Error: Display {
  623. fn description(&self) -> &str;
  624. }
  625. `;
  626. const result = extractFromSource('error.rs', code);
  627. const extendsRef = result.unresolvedReferences.find(
  628. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  629. );
  630. expect(extendsRef).toBeDefined();
  631. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  632. expect(errorTrait).toBeDefined();
  633. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  634. });
  635. it('should not create implements edges for plain impl blocks', () => {
  636. const code = `
  637. pub struct Counter {
  638. count: u32,
  639. }
  640. impl Counter {
  641. pub fn new() -> Counter {
  642. Counter { count: 0 }
  643. }
  644. pub fn increment(&mut self) {
  645. self.count += 1;
  646. }
  647. }
  648. `;
  649. const result = extractFromSource('counter.rs', code);
  650. // Should have no implements references (no trait involved)
  651. const implRefs = result.unresolvedReferences.filter(
  652. (r) => r.referenceKind === 'implements'
  653. );
  654. expect(implRefs).toHaveLength(0);
  655. });
  656. });
  657. describe('Java Extraction', () => {
  658. it('should extract class declarations', () => {
  659. const code = `
  660. public class UserService {
  661. private final UserRepository repository;
  662. public UserService(UserRepository repository) {
  663. this.repository = repository;
  664. }
  665. public User getUser(String id) {
  666. return repository.findById(id);
  667. }
  668. }
  669. `;
  670. const result = extractFromSource('UserService.java', code);
  671. const classNode = result.nodes.find((n) => n.kind === 'class');
  672. expect(classNode).toBeDefined();
  673. expect(classNode?.name).toBe('UserService');
  674. expect(classNode?.visibility).toBe('public');
  675. });
  676. it('should extract method declarations', () => {
  677. const code = `
  678. public class Calculator {
  679. public static int add(int a, int b) {
  680. return a + b;
  681. }
  682. }
  683. `;
  684. const result = extractFromSource('Calculator.java', code);
  685. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  686. expect(methodNode).toBeDefined();
  687. expect(methodNode?.isStatic).toBe(true);
  688. });
  689. it('wraps top-level declarations in a namespace from package_declaration', () => {
  690. const code = `
  691. package com.example.foo;
  692. public class Bar {
  693. public String greet() { return "hi"; }
  694. }
  695. `;
  696. const result = extractFromSource('Bar.java', code);
  697. const ns = result.nodes.find((n) => n.kind === 'namespace');
  698. expect(ns?.name).toBe('com.example.foo');
  699. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  700. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  701. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  702. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  703. });
  704. it('does not wrap when no package is declared', () => {
  705. const code = `
  706. public class Bar {
  707. public String greet() { return "hi"; }
  708. }
  709. `;
  710. const result = extractFromSource('Bar.java', code);
  711. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  712. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  713. expect(cls?.qualifiedName).toBe('Bar');
  714. });
  715. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  716. // The pattern that breaks the trace through `strategy.foo()` in
  717. // libraries like guava's Splitter: the lambda-returned anonymous
  718. // class overrides abstract methods on the base, but without
  719. // extracting those overrides the interface→impl synthesizer has
  720. // nothing to bridge.
  721. const code = `
  722. package com.example;
  723. abstract class Base {
  724. abstract int compute(int x);
  725. }
  726. public class Factory {
  727. public Base make() {
  728. return new Base() {
  729. @Override
  730. int compute(int x) { return x + 1; }
  731. };
  732. }
  733. }
  734. `;
  735. const result = extractFromSource('Factory.java', code);
  736. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  737. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  738. const compute = result.nodes.find(
  739. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  740. );
  741. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  742. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  743. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  744. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  745. const extendsRef = result.unresolvedReferences.find(
  746. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  747. );
  748. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  749. // The enclosing `make` method still emits an instantiates edge to Base —
  750. // anon extraction must not swallow that signal.
  751. const instantiatesRef = result.unresolvedReferences.find(
  752. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  753. );
  754. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  755. });
  756. it('extracts anonymous-class overrides inside a lambda body', () => {
  757. // The exact guava pattern: a lambda is passed to a constructor, and the
  758. // lambda body returns `new T() { @Override ... }`. The anon class must
  759. // still surface even though it sits inside a lambda_expression node.
  760. const code = `
  761. package com.example;
  762. interface Strategy {
  763. java.util.Iterator<String> iterator(String s);
  764. }
  765. abstract class BaseIter implements java.util.Iterator<String> {
  766. abstract int separatorStart(int start);
  767. }
  768. public class Splitter {
  769. private final Strategy strategy;
  770. public Splitter(Strategy s) { this.strategy = s; }
  771. public static Splitter on(char c) {
  772. return new Splitter((seq) ->
  773. new BaseIter() {
  774. @Override
  775. int separatorStart(int start) { return start + 1; }
  776. @Override public boolean hasNext() { return false; }
  777. @Override public String next() { return null; }
  778. });
  779. }
  780. }
  781. `;
  782. const result = extractFromSource('Splitter.java', code);
  783. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  784. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  785. const sepStart = result.nodes.find(
  786. (n) =>
  787. n.kind === 'method' &&
  788. n.name === 'separatorStart' &&
  789. n.qualifiedName.includes('$anon@')
  790. );
  791. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  792. });
  793. });
  794. describe('C# Extraction', () => {
  795. it('should extract class declarations', () => {
  796. const code = `
  797. public class OrderService
  798. {
  799. private readonly IOrderRepository _repository;
  800. public OrderService(IOrderRepository repository)
  801. {
  802. _repository = repository;
  803. }
  804. public async Task<Order> GetOrderAsync(string id)
  805. {
  806. return await _repository.FindByIdAsync(id);
  807. }
  808. }
  809. `;
  810. const result = extractFromSource('OrderService.cs', code);
  811. const classNode = result.nodes.find((n) => n.kind === 'class');
  812. expect(classNode).toBeDefined();
  813. expect(classNode?.name).toBe('OrderService');
  814. expect(classNode?.visibility).toBe('public');
  815. });
  816. });
  817. describe('PHP Extraction', () => {
  818. it('should extract class declarations', () => {
  819. const code = `<?php
  820. class UserController
  821. {
  822. private UserService $userService;
  823. public function __construct(UserService $userService)
  824. {
  825. $this->userService = $userService;
  826. }
  827. public function show(string $id): User
  828. {
  829. return $this->userService->find($id);
  830. }
  831. }
  832. `;
  833. const result = extractFromSource('UserController.php', code);
  834. const classNode = result.nodes.find((n) => n.kind === 'class');
  835. expect(classNode).toBeDefined();
  836. expect(classNode?.name).toBe('UserController');
  837. });
  838. it('should extract class inheritance (extends) and interface implementation', () => {
  839. const code = `<?php
  840. class ChildController extends BaseController implements Serializable, JsonSerializable
  841. {
  842. public function serialize(): string
  843. {
  844. return json_encode($this);
  845. }
  846. }
  847. `;
  848. const result = extractFromSource('ChildController.php', code);
  849. const classNode = result.nodes.find((n) => n.kind === 'class');
  850. expect(classNode).toBeDefined();
  851. expect(classNode?.name).toBe('ChildController');
  852. const extendsRef = result.unresolvedReferences.find(
  853. (r) => r.referenceKind === 'extends'
  854. );
  855. expect(extendsRef).toBeDefined();
  856. expect(extendsRef?.referenceName).toBe('BaseController');
  857. const implementsRefs = result.unresolvedReferences.filter(
  858. (r) => r.referenceKind === 'implements'
  859. );
  860. expect(implementsRefs.length).toBe(2);
  861. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  862. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  863. });
  864. });
  865. describe('Swift Extraction', () => {
  866. it('should extract class declarations', () => {
  867. const code = `
  868. public class NetworkManager {
  869. private let session: URLSession
  870. public init(session: URLSession = .shared) {
  871. self.session = session
  872. }
  873. public func fetchData(from url: URL) async throws -> Data {
  874. let (data, _) = try await session.data(from: url)
  875. return data
  876. }
  877. }
  878. `;
  879. const result = extractFromSource('NetworkManager.swift', code);
  880. const classNode = result.nodes.find((n) => n.kind === 'class');
  881. expect(classNode).toBeDefined();
  882. expect(classNode?.name).toBe('NetworkManager');
  883. });
  884. it('should extract function declarations', () => {
  885. const code = `
  886. func calculateSum(_ numbers: [Int]) -> Int {
  887. return numbers.reduce(0, +)
  888. }
  889. public func formatCurrency(amount: Double) -> String {
  890. return String(format: "$%.2f", amount)
  891. }
  892. `;
  893. const result = extractFromSource('utils.swift', code);
  894. const functions = result.nodes.filter((n) => n.kind === 'function');
  895. expect(functions.length).toBeGreaterThanOrEqual(1);
  896. });
  897. it('should extract struct declarations', () => {
  898. const code = `
  899. public struct User {
  900. let id: UUID
  901. var name: String
  902. var email: String
  903. func displayName() -> String {
  904. return name
  905. }
  906. }
  907. `;
  908. const result = extractFromSource('User.swift', code);
  909. const structNode = result.nodes.find((n) => n.kind === 'struct');
  910. expect(structNode).toBeDefined();
  911. expect(structNode?.name).toBe('User');
  912. });
  913. it('should extract protocol declarations', () => {
  914. const code = `
  915. public protocol Repository {
  916. associatedtype Entity
  917. func find(id: String) async throws -> Entity?
  918. func save(_ entity: Entity) async throws
  919. }
  920. `;
  921. const result = extractFromSource('Repository.swift', code);
  922. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  923. expect(protocolNode).toBeDefined();
  924. expect(protocolNode?.name).toBe('Repository');
  925. });
  926. it('should extract class inheritance and protocol conformance', () => {
  927. const code = `
  928. class DataRequest: Request {
  929. func validate() {}
  930. }
  931. class UploadRequest: DataRequest, Sendable {
  932. func upload() {}
  933. }
  934. enum AFError: Error {
  935. case invalidURL
  936. }
  937. struct HTTPMethod: RawRepresentable {
  938. let rawValue: String
  939. }
  940. protocol UploadConvertible: URLRequestConvertible {
  941. func asURLRequest() throws -> URLRequest
  942. }
  943. `;
  944. const result = extractFromSource('Inheritance.swift', code);
  945. const extendsRefs = result.unresolvedReferences.filter(
  946. (r) => r.referenceKind === 'extends'
  947. );
  948. // DataRequest extends Request
  949. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  950. // UploadRequest extends DataRequest and Sendable
  951. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  952. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  953. // AFError extends Error
  954. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  955. // HTTPMethod extends RawRepresentable
  956. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  957. // UploadConvertible extends URLRequestConvertible
  958. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  959. });
  960. });
  961. describe('Kotlin Extraction', () => {
  962. it('should extract class declarations', () => {
  963. const code = `
  964. class UserRepository(private val database: Database) {
  965. fun findById(id: String): User? {
  966. return database.query("SELECT * FROM users WHERE id = ?", id)
  967. }
  968. suspend fun save(user: User) {
  969. database.insert(user)
  970. }
  971. }
  972. `;
  973. const result = extractFromSource('UserRepository.kt', code);
  974. const classNode = result.nodes.find((n) => n.kind === 'class');
  975. expect(classNode).toBeDefined();
  976. expect(classNode?.name).toBe('UserRepository');
  977. });
  978. it('should extract function declarations', () => {
  979. const code = `
  980. fun calculateTotal(items: List<Item>): Double {
  981. return items.sumOf { it.price }
  982. }
  983. suspend fun fetchUserData(userId: String): User {
  984. return api.getUser(userId)
  985. }
  986. `;
  987. const result = extractFromSource('utils.kt', code);
  988. const functions = result.nodes.filter((n) => n.kind === 'function');
  989. expect(functions.length).toBeGreaterThanOrEqual(1);
  990. });
  991. it('should detect suspend functions as async', () => {
  992. const code = `
  993. suspend fun loadData(): List<String> {
  994. delay(1000)
  995. return listOf("a", "b", "c")
  996. }
  997. `;
  998. const result = extractFromSource('loader.kt', code);
  999. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1000. expect(funcNode).toBeDefined();
  1001. expect(funcNode?.isAsync).toBe(true);
  1002. });
  1003. it('should extract fun interface declarations', () => {
  1004. const code = `
  1005. fun interface OnObjectRetainedListener {
  1006. fun onObjectRetained()
  1007. }
  1008. `;
  1009. const result = extractFromSource('listener.kt', code);
  1010. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1011. expect(ifaceNode).toBeDefined();
  1012. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1013. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1014. expect(methodNode).toBeDefined();
  1015. expect(methodNode?.name).toBe('onObjectRetained');
  1016. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1017. });
  1018. it('should extract complex fun interface with nested classes', () => {
  1019. const code = `
  1020. fun interface EventListener {
  1021. fun onEvent(event: Event)
  1022. sealed class Event {
  1023. class DumpingHeap : Event()
  1024. }
  1025. }
  1026. `;
  1027. const result = extractFromSource('events.kt', code);
  1028. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1029. expect(ifaceNode).toBeDefined();
  1030. expect(ifaceNode?.name).toBe('EventListener');
  1031. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1032. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1033. expect(eventClass).toBeDefined();
  1034. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1035. expect(dumpingHeap).toBeDefined();
  1036. });
  1037. it('should not affect regular function declarations', () => {
  1038. const code = `
  1039. fun interface MyCallback {
  1040. fun invoke(value: Int)
  1041. }
  1042. fun regularFunction(): String {
  1043. return "hello"
  1044. }
  1045. `;
  1046. const result = extractFromSource('mixed.kt', code);
  1047. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1048. expect(ifaceNode).toBeDefined();
  1049. expect(ifaceNode?.name).toBe('MyCallback');
  1050. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1051. expect(funcNode).toBeDefined();
  1052. expect(funcNode?.name).toBe('regularFunction');
  1053. });
  1054. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1055. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1056. // misparse: function_declaration > ERROR("interface Name {") instead of
  1057. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1058. const code = `
  1059. import java.io.IOException
  1060. fun interface Interceptor {
  1061. @Throws(IOException::class)
  1062. fun intercept(chain: Chain): Response
  1063. }
  1064. `;
  1065. const result = extractFromSource('interceptor.kt', code);
  1066. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1067. expect(ifaceNode).toBeDefined();
  1068. expect(ifaceNode?.name).toBe('Interceptor');
  1069. });
  1070. it('should extract methods from interface with nested fun interface', () => {
  1071. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1072. // the parent body as ERROR. Methods inside should still be extracted.
  1073. const code = `
  1074. interface WebSocket {
  1075. fun request(): Request
  1076. fun send(text: String): Boolean
  1077. fun cancel()
  1078. fun interface Factory {
  1079. fun newWebSocket(request: Request): WebSocket
  1080. }
  1081. }
  1082. `;
  1083. const result = extractFromSource('websocket.kt', code);
  1084. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1085. expect(wsIface).toBeDefined();
  1086. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1087. const methodNames = methods.map((m) => m.name);
  1088. expect(methodNames).toContain('request');
  1089. expect(methodNames).toContain('send');
  1090. expect(methodNames).toContain('cancel');
  1091. });
  1092. it('wraps top-level declarations in a namespace from package_header', () => {
  1093. const code = `
  1094. package com.example.foo
  1095. class Bar {
  1096. fun greet(): String = "hi"
  1097. }
  1098. fun util(): Int = 42
  1099. `;
  1100. const result = extractFromSource('Bar.kt', code);
  1101. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1102. expect(ns?.name).toBe('com.example.foo');
  1103. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1104. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1105. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1106. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1107. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1108. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1109. });
  1110. it('handles a single-segment package', () => {
  1111. const code = `
  1112. package foo
  1113. class Bar
  1114. `;
  1115. const result = extractFromSource('Bar.kt', code);
  1116. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1117. expect(cls?.qualifiedName).toBe('foo::Bar');
  1118. });
  1119. it('does not wrap when no package is declared', () => {
  1120. const code = `
  1121. class Bar {
  1122. fun greet() = "hi"
  1123. }
  1124. `;
  1125. const result = extractFromSource('Bar.kt', code);
  1126. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1127. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1128. expect(cls?.qualifiedName).toBe('Bar');
  1129. });
  1130. });
  1131. describe('Dart Extraction', () => {
  1132. it('should extract class declarations', () => {
  1133. const code = `
  1134. class UserService {
  1135. final Database _db;
  1136. Future<User> findById(String id) async {
  1137. return await _db.query(id);
  1138. }
  1139. void _privateMethod() {}
  1140. }
  1141. `;
  1142. const result = extractFromSource('service.dart', code);
  1143. const classNode = result.nodes.find((n) => n.kind === 'class');
  1144. expect(classNode).toBeDefined();
  1145. expect(classNode?.name).toBe('UserService');
  1146. expect(classNode?.visibility).toBe('public');
  1147. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1148. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1149. const findById = methodNodes.find((m) => m.name === 'findById');
  1150. expect(findById).toBeDefined();
  1151. expect(findById?.isAsync).toBe(true);
  1152. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1153. expect(privateMethod).toBeDefined();
  1154. expect(privateMethod?.visibility).toBe('private');
  1155. // Dart models a method body as a SIBLING of the signature, so the method
  1156. // node must be extended to span its body (not just the signature line) —
  1157. // required for body-level analysis (callees, the callback synthesizer).
  1158. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1159. });
  1160. it('should extract top-level function declarations', () => {
  1161. const code = `
  1162. void topLevelFunction(String name) {
  1163. print(name);
  1164. }
  1165. `;
  1166. const result = extractFromSource('utils.dart', code);
  1167. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1168. expect(funcNode).toBeDefined();
  1169. expect(funcNode?.name).toBe('topLevelFunction');
  1170. expect(funcNode?.language).toBe('dart');
  1171. });
  1172. it('should extract enum declarations', () => {
  1173. const code = `
  1174. enum Status { active, inactive, pending }
  1175. `;
  1176. const result = extractFromSource('models.dart', code);
  1177. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1178. expect(enumNode).toBeDefined();
  1179. expect(enumNode?.name).toBe('Status');
  1180. });
  1181. it('should extract mixin declarations', () => {
  1182. const code = `
  1183. mixin LoggerMixin {
  1184. void log(String message) {}
  1185. }
  1186. `;
  1187. const result = extractFromSource('mixins.dart', code);
  1188. const classNode = result.nodes.find((n) => n.kind === 'class');
  1189. expect(classNode).toBeDefined();
  1190. expect(classNode?.name).toBe('LoggerMixin');
  1191. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1192. expect(methodNode).toBeDefined();
  1193. expect(methodNode?.name).toBe('log');
  1194. });
  1195. it('should extract extension declarations', () => {
  1196. const code = `
  1197. extension StringExt on String {
  1198. bool get isBlank => trim().isEmpty;
  1199. }
  1200. `;
  1201. const result = extractFromSource('extensions.dart', code);
  1202. const classNode = result.nodes.find((n) => n.kind === 'class');
  1203. expect(classNode).toBeDefined();
  1204. expect(classNode?.name).toBe('StringExt');
  1205. });
  1206. it('should detect static methods', () => {
  1207. const code = `
  1208. class Utils {
  1209. static void doWork() {}
  1210. }
  1211. `;
  1212. const result = extractFromSource('utils.dart', code);
  1213. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1214. expect(methodNode).toBeDefined();
  1215. expect(methodNode?.name).toBe('doWork');
  1216. expect(methodNode?.isStatic).toBe(true);
  1217. });
  1218. it('should detect async functions', () => {
  1219. const code = `
  1220. Future<String> fetchData() async {
  1221. return await http.get('/data');
  1222. }
  1223. `;
  1224. const result = extractFromSource('api.dart', code);
  1225. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1226. expect(funcNode).toBeDefined();
  1227. expect(funcNode?.name).toBe('fetchData');
  1228. expect(funcNode?.isAsync).toBe(true);
  1229. });
  1230. it('should detect private visibility via underscore convention', () => {
  1231. const code = `
  1232. void _privateHelper() {}
  1233. void publicFunction() {}
  1234. `;
  1235. const result = extractFromSource('helpers.dart', code);
  1236. const functions = result.nodes.filter((n) => n.kind === 'function');
  1237. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1238. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1239. expect(privateFunc?.visibility).toBe('private');
  1240. expect(publicFunc?.visibility).toBe('public');
  1241. });
  1242. });
  1243. describe('Import Extraction', () => {
  1244. describe('TypeScript/JavaScript imports', () => {
  1245. it('should extract default imports', () => {
  1246. const code = `import React from 'react';`;
  1247. const result = extractFromSource('app.tsx', code);
  1248. const importNode = result.nodes.find((n) => n.kind === 'import');
  1249. expect(importNode).toBeDefined();
  1250. expect(importNode?.name).toBe('react');
  1251. expect(importNode?.signature).toBe("import React from 'react';");
  1252. });
  1253. it('should extract named imports', () => {
  1254. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1255. const result = extractFromSource('icons.tsx', code);
  1256. const importNode = result.nodes.find((n) => n.kind === 'import');
  1257. expect(importNode).toBeDefined();
  1258. expect(importNode?.name).toBe('@phosphor-icons/react');
  1259. expect(importNode?.signature).toContain('Bug');
  1260. expect(importNode?.signature).toContain('Database');
  1261. });
  1262. it('should extract namespace imports', () => {
  1263. const code = `import * as Icons from '@phosphor-icons/react';`;
  1264. const result = extractFromSource('icons.tsx', code);
  1265. const importNode = result.nodes.find((n) => n.kind === 'import');
  1266. expect(importNode).toBeDefined();
  1267. expect(importNode?.name).toBe('@phosphor-icons/react');
  1268. expect(importNode?.signature).toContain('* as Icons');
  1269. });
  1270. it('should extract side-effect imports', () => {
  1271. const code = `import './styles.css';`;
  1272. const result = extractFromSource('app.tsx', code);
  1273. const importNode = result.nodes.find((n) => n.kind === 'import');
  1274. expect(importNode).toBeDefined();
  1275. expect(importNode?.name).toBe('./styles.css');
  1276. });
  1277. it('should extract mixed imports (default + named)', () => {
  1278. const code = `import React, { useState, useEffect } from 'react';`;
  1279. const result = extractFromSource('app.tsx', code);
  1280. const importNode = result.nodes.find((n) => n.kind === 'import');
  1281. expect(importNode).toBeDefined();
  1282. expect(importNode?.name).toBe('react');
  1283. expect(importNode?.signature).toContain('React');
  1284. expect(importNode?.signature).toContain('useState');
  1285. expect(importNode?.signature).toContain('useEffect');
  1286. });
  1287. it('should extract multiple import statements', () => {
  1288. const code = `
  1289. import React from 'react';
  1290. import { Button } from './components';
  1291. import './styles.css';
  1292. `;
  1293. const result = extractFromSource('app.tsx', code);
  1294. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1295. expect(importNodes.length).toBe(3);
  1296. const names = importNodes.map((n) => n.name);
  1297. expect(names).toContain('react');
  1298. expect(names).toContain('./components');
  1299. expect(names).toContain('./styles.css');
  1300. });
  1301. it('should extract type imports', () => {
  1302. const code = `import type { FC, ReactNode } from 'react';`;
  1303. const result = extractFromSource('types.ts', code);
  1304. const importNode = result.nodes.find((n) => n.kind === 'import');
  1305. expect(importNode).toBeDefined();
  1306. expect(importNode?.name).toBe('react');
  1307. expect(importNode?.signature).toContain('type');
  1308. expect(importNode?.signature).toContain('FC');
  1309. });
  1310. it('should extract aliased named imports', () => {
  1311. const code = `import { useState as useStateAlias } from 'react';`;
  1312. const result = extractFromSource('hooks.ts', code);
  1313. const importNode = result.nodes.find((n) => n.kind === 'import');
  1314. expect(importNode).toBeDefined();
  1315. expect(importNode?.name).toBe('react');
  1316. expect(importNode?.signature).toContain('useState');
  1317. expect(importNode?.signature).toContain('useStateAlias');
  1318. });
  1319. it('should extract relative path imports', () => {
  1320. const code = `import { helper } from '../utils/helper';`;
  1321. const result = extractFromSource('components/Button.tsx', code);
  1322. const importNode = result.nodes.find((n) => n.kind === 'import');
  1323. expect(importNode).toBeDefined();
  1324. expect(importNode?.name).toBe('../utils/helper');
  1325. expect(importNode?.signature).toContain('helper');
  1326. });
  1327. });
  1328. describe('Python imports', () => {
  1329. it('should extract simple import statement', () => {
  1330. const code = `import json`;
  1331. const result = extractFromSource('utils.py', code);
  1332. const importNode = result.nodes.find((n) => n.kind === 'import');
  1333. expect(importNode).toBeDefined();
  1334. expect(importNode?.name).toBe('json');
  1335. });
  1336. it('should extract from import statement', () => {
  1337. const code = `from os import path`;
  1338. const result = extractFromSource('utils.py', code);
  1339. const importNode = result.nodes.find((n) => n.kind === 'import');
  1340. expect(importNode).toBeDefined();
  1341. expect(importNode?.name).toBe('os');
  1342. expect(importNode?.signature).toContain('path');
  1343. });
  1344. it('should extract multiple imports from same module', () => {
  1345. const code = `from typing import List, Dict, Optional`;
  1346. const result = extractFromSource('types.py', code);
  1347. const importNode = result.nodes.find((n) => n.kind === 'import');
  1348. expect(importNode).toBeDefined();
  1349. expect(importNode?.name).toBe('typing');
  1350. expect(importNode?.signature).toContain('List');
  1351. expect(importNode?.signature).toContain('Dict');
  1352. });
  1353. it('should extract multiple import statements', () => {
  1354. const code = `
  1355. import os
  1356. import sys
  1357. `;
  1358. const result = extractFromSource('main.py', code);
  1359. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1360. expect(importNodes.length).toBe(2);
  1361. const names = importNodes.map((n) => n.name);
  1362. expect(names).toContain('os');
  1363. expect(names).toContain('sys');
  1364. });
  1365. it('should extract aliased import', () => {
  1366. const code = `import numpy as np`;
  1367. const result = extractFromSource('data.py', code);
  1368. const importNode = result.nodes.find((n) => n.kind === 'import');
  1369. expect(importNode).toBeDefined();
  1370. expect(importNode?.name).toBe('numpy');
  1371. expect(importNode?.signature).toContain('as np');
  1372. });
  1373. it('should extract relative import', () => {
  1374. const code = `from .utils import helper`;
  1375. const result = extractFromSource('module.py', code);
  1376. const importNode = result.nodes.find((n) => n.kind === 'import');
  1377. expect(importNode).toBeDefined();
  1378. expect(importNode?.name).toBe('.utils');
  1379. expect(importNode?.signature).toContain('helper');
  1380. });
  1381. it('should extract wildcard import', () => {
  1382. const code = `from typing import *`;
  1383. const result = extractFromSource('types.py', code);
  1384. const importNode = result.nodes.find((n) => n.kind === 'import');
  1385. expect(importNode).toBeDefined();
  1386. expect(importNode?.name).toBe('typing');
  1387. expect(importNode?.signature).toContain('*');
  1388. });
  1389. });
  1390. describe('Rust imports', () => {
  1391. it('should extract simple use declaration', () => {
  1392. const code = `use std::io;`;
  1393. const result = extractFromSource('main.rs', code);
  1394. const importNode = result.nodes.find((n) => n.kind === 'import');
  1395. expect(importNode).toBeDefined();
  1396. expect(importNode?.name).toBe('std');
  1397. expect(importNode?.signature).toBe('use std::io;');
  1398. });
  1399. it('should extract scoped use list', () => {
  1400. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1401. const result = extractFromSource('main.rs', code);
  1402. const importNode = result.nodes.find((n) => n.kind === 'import');
  1403. expect(importNode).toBeDefined();
  1404. expect(importNode?.name).toBe('std');
  1405. expect(importNode?.signature).toContain('ffi::OsStr');
  1406. expect(importNode?.signature).toContain('path::Path');
  1407. });
  1408. it('should extract crate imports', () => {
  1409. const code = `use crate::error::Error;`;
  1410. const result = extractFromSource('lib.rs', code);
  1411. const importNode = result.nodes.find((n) => n.kind === 'import');
  1412. expect(importNode).toBeDefined();
  1413. expect(importNode?.name).toBe('crate');
  1414. });
  1415. it('should extract super imports', () => {
  1416. const code = `use super::utils;`;
  1417. const result = extractFromSource('submod.rs', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('super');
  1421. });
  1422. it('should extract external crate imports', () => {
  1423. const code = `use serde::{Serialize, Deserialize};`;
  1424. const result = extractFromSource('types.rs', code);
  1425. const importNode = result.nodes.find((n) => n.kind === 'import');
  1426. expect(importNode).toBeDefined();
  1427. expect(importNode?.name).toBe('serde');
  1428. expect(importNode?.signature).toContain('Serialize');
  1429. expect(importNode?.signature).toContain('Deserialize');
  1430. });
  1431. });
  1432. describe('Go imports', () => {
  1433. it('should extract single import', () => {
  1434. const code = `
  1435. package main
  1436. import "fmt"
  1437. `;
  1438. const result = extractFromSource('main.go', code);
  1439. const importNode = result.nodes.find((n) => n.kind === 'import');
  1440. expect(importNode).toBeDefined();
  1441. expect(importNode?.name).toBe('fmt');
  1442. });
  1443. it('should extract grouped imports', () => {
  1444. const code = `
  1445. package main
  1446. import (
  1447. "fmt"
  1448. "os"
  1449. "encoding/json"
  1450. )
  1451. `;
  1452. const result = extractFromSource('main.go', code);
  1453. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1454. expect(importNodes.length).toBe(3);
  1455. const names = importNodes.map((n) => n.name);
  1456. expect(names).toContain('fmt');
  1457. expect(names).toContain('os');
  1458. expect(names).toContain('encoding/json');
  1459. });
  1460. it('should extract aliased import', () => {
  1461. const code = `
  1462. package main
  1463. import f "fmt"
  1464. `;
  1465. const result = extractFromSource('main.go', code);
  1466. const importNode = result.nodes.find((n) => n.kind === 'import');
  1467. expect(importNode).toBeDefined();
  1468. expect(importNode?.name).toBe('fmt');
  1469. expect(importNode?.signature).toContain('f');
  1470. });
  1471. it('should extract dot import', () => {
  1472. const code = `
  1473. package main
  1474. import . "math"
  1475. `;
  1476. const result = extractFromSource('main.go', code);
  1477. const importNode = result.nodes.find((n) => n.kind === 'import');
  1478. expect(importNode).toBeDefined();
  1479. expect(importNode?.name).toBe('math');
  1480. expect(importNode?.signature).toContain('.');
  1481. });
  1482. it('should extract blank import', () => {
  1483. const code = `
  1484. package main
  1485. import _ "github.com/go-sql-driver/mysql"
  1486. `;
  1487. const result = extractFromSource('main.go', code);
  1488. const importNode = result.nodes.find((n) => n.kind === 'import');
  1489. expect(importNode).toBeDefined();
  1490. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1491. expect(importNode?.signature).toContain('_');
  1492. });
  1493. });
  1494. describe('Swift imports', () => {
  1495. it('should extract simple import', () => {
  1496. const code = `import Foundation`;
  1497. const result = extractFromSource('main.swift', code);
  1498. const importNode = result.nodes.find((n) => n.kind === 'import');
  1499. expect(importNode).toBeDefined();
  1500. expect(importNode?.name).toBe('Foundation');
  1501. expect(importNode?.signature).toBe('import Foundation');
  1502. });
  1503. it('should extract @testable import', () => {
  1504. const code = `@testable import Alamofire`;
  1505. const result = extractFromSource('Tests.swift', code);
  1506. const importNode = result.nodes.find((n) => n.kind === 'import');
  1507. expect(importNode).toBeDefined();
  1508. expect(importNode?.name).toBe('Alamofire');
  1509. expect(importNode?.signature).toContain('@testable');
  1510. });
  1511. it('should extract @preconcurrency import', () => {
  1512. const code = `@preconcurrency import Security`;
  1513. const result = extractFromSource('Auth.swift', code);
  1514. const importNode = result.nodes.find((n) => n.kind === 'import');
  1515. expect(importNode).toBeDefined();
  1516. expect(importNode?.name).toBe('Security');
  1517. });
  1518. it('should extract multiple imports', () => {
  1519. const code = `
  1520. import Foundation
  1521. import UIKit
  1522. import Alamofire
  1523. `;
  1524. const result = extractFromSource('App.swift', code);
  1525. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1526. expect(importNodes.length).toBe(3);
  1527. const names = importNodes.map((n) => n.name);
  1528. expect(names).toContain('Foundation');
  1529. expect(names).toContain('UIKit');
  1530. expect(names).toContain('Alamofire');
  1531. });
  1532. });
  1533. describe('Kotlin imports', () => {
  1534. it('should extract simple import', () => {
  1535. const code = `import java.io.IOException`;
  1536. const result = extractFromSource('Main.kt', code);
  1537. const importNode = result.nodes.find((n) => n.kind === 'import');
  1538. expect(importNode).toBeDefined();
  1539. expect(importNode?.name).toBe('java.io.IOException');
  1540. expect(importNode?.signature).toBe('import java.io.IOException');
  1541. });
  1542. it('should extract aliased import', () => {
  1543. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1544. const result = extractFromSource('Utils.kt', code);
  1545. const importNode = result.nodes.find((n) => n.kind === 'import');
  1546. expect(importNode).toBeDefined();
  1547. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1548. expect(importNode?.signature).toContain('as RequestBuilder');
  1549. });
  1550. it('should extract wildcard import', () => {
  1551. const code = `import java.util.concurrent.TimeUnit.*`;
  1552. const result = extractFromSource('Time.kt', code);
  1553. const importNode = result.nodes.find((n) => n.kind === 'import');
  1554. expect(importNode).toBeDefined();
  1555. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1556. expect(importNode?.signature).toContain('.*');
  1557. });
  1558. it('should extract multiple imports', () => {
  1559. const code = `
  1560. import java.io.IOException
  1561. import kotlin.test.assertFailsWith
  1562. import okhttp3.OkHttpClient
  1563. `;
  1564. const result = extractFromSource('Test.kt', code);
  1565. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1566. expect(importNodes.length).toBe(3);
  1567. const names = importNodes.map((n) => n.name);
  1568. expect(names).toContain('java.io.IOException');
  1569. expect(names).toContain('kotlin.test.assertFailsWith');
  1570. expect(names).toContain('okhttp3.OkHttpClient');
  1571. });
  1572. });
  1573. describe('Java imports', () => {
  1574. it('should extract simple import', () => {
  1575. const code = `import java.util.List;`;
  1576. const result = extractFromSource('Main.java', code);
  1577. const importNode = result.nodes.find((n) => n.kind === 'import');
  1578. expect(importNode).toBeDefined();
  1579. expect(importNode?.name).toBe('java.util.List');
  1580. expect(importNode?.signature).toBe('import java.util.List;');
  1581. });
  1582. it('should extract static import', () => {
  1583. const code = `import static java.util.Collections.emptyList;`;
  1584. const result = extractFromSource('Utils.java', code);
  1585. const importNode = result.nodes.find((n) => n.kind === 'import');
  1586. expect(importNode).toBeDefined();
  1587. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1588. expect(importNode?.signature).toContain('static');
  1589. });
  1590. it('should extract wildcard import', () => {
  1591. const code = `import java.util.*;`;
  1592. const result = extractFromSource('App.java', code);
  1593. const importNode = result.nodes.find((n) => n.kind === 'import');
  1594. expect(importNode).toBeDefined();
  1595. expect(importNode?.name).toBe('java.util');
  1596. expect(importNode?.signature).toContain('.*');
  1597. });
  1598. it('should extract nested class import', () => {
  1599. const code = `import java.util.Map.Entry;`;
  1600. const result = extractFromSource('MapUtil.java', code);
  1601. const importNode = result.nodes.find((n) => n.kind === 'import');
  1602. expect(importNode).toBeDefined();
  1603. expect(importNode?.name).toBe('java.util.Map.Entry');
  1604. });
  1605. it('should extract multiple imports', () => {
  1606. const code = `
  1607. import java.util.List;
  1608. import java.util.Map;
  1609. import java.io.IOException;
  1610. `;
  1611. const result = extractFromSource('Service.java', code);
  1612. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1613. expect(importNodes.length).toBe(3);
  1614. const names = importNodes.map((n) => n.name);
  1615. expect(names).toContain('java.util.List');
  1616. expect(names).toContain('java.util.Map');
  1617. expect(names).toContain('java.io.IOException');
  1618. });
  1619. });
  1620. describe('C# imports', () => {
  1621. it('should extract simple using', () => {
  1622. const code = `using System;`;
  1623. const result = extractFromSource('Program.cs', code);
  1624. const importNode = result.nodes.find((n) => n.kind === 'import');
  1625. expect(importNode).toBeDefined();
  1626. expect(importNode?.name).toBe('System');
  1627. expect(importNode?.signature).toBe('using System;');
  1628. });
  1629. it('should extract qualified using', () => {
  1630. const code = `using System.Collections.Generic;`;
  1631. const result = extractFromSource('Utils.cs', code);
  1632. const importNode = result.nodes.find((n) => n.kind === 'import');
  1633. expect(importNode).toBeDefined();
  1634. expect(importNode?.name).toBe('System.Collections.Generic');
  1635. });
  1636. it('should extract static using', () => {
  1637. const code = `using static System.Console;`;
  1638. const result = extractFromSource('App.cs', code);
  1639. const importNode = result.nodes.find((n) => n.kind === 'import');
  1640. expect(importNode).toBeDefined();
  1641. expect(importNode?.name).toBe('System.Console');
  1642. expect(importNode?.signature).toContain('static');
  1643. });
  1644. it('should extract alias using', () => {
  1645. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1646. const result = extractFromSource('Types.cs', code);
  1647. const importNode = result.nodes.find((n) => n.kind === 'import');
  1648. expect(importNode).toBeDefined();
  1649. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1650. expect(importNode?.signature).toContain('MyList =');
  1651. });
  1652. it('should extract multiple usings', () => {
  1653. const code = `
  1654. using System;
  1655. using System.Threading.Tasks;
  1656. using Microsoft.Extensions.DependencyInjection;
  1657. `;
  1658. const result = extractFromSource('Service.cs', code);
  1659. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1660. expect(importNodes.length).toBe(3);
  1661. const names = importNodes.map((n) => n.name);
  1662. expect(names).toContain('System');
  1663. expect(names).toContain('System.Threading.Tasks');
  1664. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1665. });
  1666. });
  1667. describe('PHP imports', () => {
  1668. it('should extract simple use', () => {
  1669. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1670. const result = extractFromSource('Test.php', code);
  1671. const importNode = result.nodes.find((n) => n.kind === 'import');
  1672. expect(importNode).toBeDefined();
  1673. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1674. });
  1675. it('should extract aliased use', () => {
  1676. const code = `<?php use Mockery as m;`;
  1677. const result = extractFromSource('Test.php', code);
  1678. const importNode = result.nodes.find((n) => n.kind === 'import');
  1679. expect(importNode).toBeDefined();
  1680. expect(importNode?.name).toBe('Mockery');
  1681. expect(importNode?.signature).toContain('as m');
  1682. });
  1683. it('should extract function use', () => {
  1684. const code = `<?php use function Illuminate\\Support\\env;`;
  1685. const result = extractFromSource('helpers.php', code);
  1686. const importNode = result.nodes.find((n) => n.kind === 'import');
  1687. expect(importNode).toBeDefined();
  1688. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1689. expect(importNode?.signature).toContain('function');
  1690. });
  1691. it('should extract grouped use', () => {
  1692. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1693. const result = extractFromSource('Models.php', code);
  1694. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1695. expect(importNodes.length).toBe(2);
  1696. const names = importNodes.map((n) => n.name);
  1697. expect(names).toContain('Illuminate\\Database\\Model');
  1698. expect(names).toContain('Illuminate\\Database\\Builder');
  1699. });
  1700. it('should extract multiple uses', () => {
  1701. const code = `<?php
  1702. use Illuminate\\Support\\Collection;
  1703. use Illuminate\\Support\\Str;
  1704. use Closure;
  1705. `;
  1706. const result = extractFromSource('Service.php', code);
  1707. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1708. expect(importNodes.length).toBe(3);
  1709. const names = importNodes.map((n) => n.name);
  1710. expect(names).toContain('Illuminate\\Support\\Collection');
  1711. expect(names).toContain('Illuminate\\Support\\Str');
  1712. expect(names).toContain('Closure');
  1713. });
  1714. });
  1715. describe('Ruby imports', () => {
  1716. it('should extract require', () => {
  1717. const code = `require 'json'`;
  1718. const result = extractFromSource('app.rb', code);
  1719. const importNode = result.nodes.find((n) => n.kind === 'import');
  1720. expect(importNode).toBeDefined();
  1721. expect(importNode?.name).toBe('json');
  1722. expect(importNode?.signature).toBe("require 'json'");
  1723. });
  1724. it('should extract require with path', () => {
  1725. const code = `require 'active_support/core_ext/string'`;
  1726. const result = extractFromSource('config.rb', code);
  1727. const importNode = result.nodes.find((n) => n.kind === 'import');
  1728. expect(importNode).toBeDefined();
  1729. expect(importNode?.name).toBe('active_support/core_ext/string');
  1730. });
  1731. it('should extract require_relative', () => {
  1732. const code = `require_relative '../test_helper'`;
  1733. const result = extractFromSource('test/my_test.rb', code);
  1734. const importNode = result.nodes.find((n) => n.kind === 'import');
  1735. expect(importNode).toBeDefined();
  1736. expect(importNode?.name).toBe('../test_helper');
  1737. expect(importNode?.signature).toContain('require_relative');
  1738. });
  1739. it('should not extract non-require calls', () => {
  1740. const code = `puts 'hello'`;
  1741. const result = extractFromSource('app.rb', code);
  1742. const importNode = result.nodes.find((n) => n.kind === 'import');
  1743. expect(importNode).toBeUndefined();
  1744. });
  1745. it('should extract multiple requires', () => {
  1746. const code = `
  1747. require 'json'
  1748. require 'yaml'
  1749. require_relative 'helper'
  1750. `;
  1751. const result = extractFromSource('lib.rb', code);
  1752. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1753. expect(importNodes.length).toBe(3);
  1754. const names = importNodes.map((n) => n.name);
  1755. expect(names).toContain('json');
  1756. expect(names).toContain('yaml');
  1757. expect(names).toContain('helper');
  1758. });
  1759. });
  1760. describe('Ruby modules', () => {
  1761. it('should extract module as module node with containment', () => {
  1762. const code = `
  1763. module CachedCounting
  1764. def self.disable
  1765. @enabled = false
  1766. end
  1767. def perform_increment!(key, count)
  1768. write_cache!(key, count)
  1769. end
  1770. end
  1771. `;
  1772. const result = extractFromSource('concerns/cached_counting.rb', code);
  1773. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1774. expect(moduleNode).toBeDefined();
  1775. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1776. // Methods inside module should have module-qualified names
  1777. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1778. expect(disableMethod).toBeDefined();
  1779. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1780. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1781. expect(incrementMethod).toBeDefined();
  1782. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1783. // Containment edge from module to methods
  1784. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1785. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1786. });
  1787. it('should handle nested modules with classes', () => {
  1788. const code = `
  1789. module Discourse
  1790. module Auth
  1791. class AuthProvider
  1792. def authenticate(params)
  1793. validate(params)
  1794. end
  1795. end
  1796. end
  1797. end
  1798. `;
  1799. const result = extractFromSource('lib/auth.rb', code);
  1800. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1801. expect(discourseModule).toBeDefined();
  1802. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1803. expect(authModule).toBeDefined();
  1804. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1805. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1806. expect(authProvider).toBeDefined();
  1807. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1808. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1809. expect(authMethod).toBeDefined();
  1810. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1811. });
  1812. });
  1813. describe('C/C++ imports', () => {
  1814. it('should extract system include', () => {
  1815. const code = `#include <iostream>`;
  1816. const result = extractFromSource('main.cpp', code);
  1817. const importNode = result.nodes.find((n) => n.kind === 'import');
  1818. expect(importNode).toBeDefined();
  1819. expect(importNode?.name).toBe('iostream');
  1820. expect(importNode?.signature).toBe('#include <iostream>');
  1821. });
  1822. it('should extract system include with path', () => {
  1823. const code = `#include <nlohmann/json.hpp>`;
  1824. const result = extractFromSource('app.cpp', code);
  1825. const importNode = result.nodes.find((n) => n.kind === 'import');
  1826. expect(importNode).toBeDefined();
  1827. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1828. });
  1829. it('should extract local include', () => {
  1830. const code = `#include "myheader.h"`;
  1831. const result = extractFromSource('main.cpp', code);
  1832. const importNode = result.nodes.find((n) => n.kind === 'import');
  1833. expect(importNode).toBeDefined();
  1834. expect(importNode?.name).toBe('myheader.h');
  1835. });
  1836. it('should extract C header', () => {
  1837. const code = `#include <stdio.h>`;
  1838. const result = extractFromSource('main.c', code);
  1839. const importNode = result.nodes.find((n) => n.kind === 'import');
  1840. expect(importNode).toBeDefined();
  1841. expect(importNode?.name).toBe('stdio.h');
  1842. });
  1843. it('should extract multiple includes', () => {
  1844. const code = `
  1845. #include <iostream>
  1846. #include <vector>
  1847. #include "config.h"
  1848. `;
  1849. const result = extractFromSource('app.cpp', code);
  1850. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1851. expect(importNodes.length).toBe(3);
  1852. const names = importNodes.map((n) => n.name);
  1853. expect(names).toContain('iostream');
  1854. expect(names).toContain('vector');
  1855. expect(names).toContain('config.h');
  1856. });
  1857. it('should create unresolved references for local includes', () => {
  1858. const code = `#include "myheader.h"`;
  1859. const result = extractFromSource('main.cpp', code);
  1860. const importRef = result.unresolvedReferences.find(
  1861. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1862. );
  1863. expect(importRef).toBeDefined();
  1864. expect(importRef?.line).toBe(1);
  1865. });
  1866. it('should create unresolved references for system includes', () => {
  1867. const code = `#include <iostream>`;
  1868. const result = extractFromSource('main.cpp', code);
  1869. const importRef = result.unresolvedReferences.find(
  1870. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1871. );
  1872. expect(importRef).toBeDefined();
  1873. });
  1874. });
  1875. describe('Dart imports', () => {
  1876. it('should extract dart: import', () => {
  1877. const code = `import 'dart:async';`;
  1878. const result = extractFromSource('main.dart', code);
  1879. const importNode = result.nodes.find((n) => n.kind === 'import');
  1880. expect(importNode).toBeDefined();
  1881. expect(importNode?.name).toBe('dart:async');
  1882. expect(importNode?.signature).toBe("import 'dart:async';");
  1883. });
  1884. it('should extract package import', () => {
  1885. const code = `import 'package:flutter/material.dart';`;
  1886. const result = extractFromSource('app.dart', code);
  1887. const importNode = result.nodes.find((n) => n.kind === 'import');
  1888. expect(importNode).toBeDefined();
  1889. expect(importNode?.name).toBe('package:flutter/material.dart');
  1890. });
  1891. it('should extract aliased import', () => {
  1892. const code = `import 'package:http/http.dart' as http;`;
  1893. const result = extractFromSource('api.dart', code);
  1894. const importNode = result.nodes.find((n) => n.kind === 'import');
  1895. expect(importNode).toBeDefined();
  1896. expect(importNode?.name).toBe('package:http/http.dart');
  1897. expect(importNode?.signature).toContain('as http');
  1898. });
  1899. it('should extract multiple imports', () => {
  1900. const code = `
  1901. import 'dart:async';
  1902. import 'dart:convert';
  1903. import 'package:flutter/material.dart';
  1904. `;
  1905. const result = extractFromSource('main.dart', code);
  1906. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1907. expect(importNodes.length).toBe(3);
  1908. const names = importNodes.map((n) => n.name);
  1909. expect(names).toContain('dart:async');
  1910. expect(names).toContain('dart:convert');
  1911. expect(names).toContain('package:flutter/material.dart');
  1912. });
  1913. it('should extract relative import', () => {
  1914. const code = `import '../utils/helpers.dart';`;
  1915. const result = extractFromSource('lib/main.dart', code);
  1916. const importNode = result.nodes.find((n) => n.kind === 'import');
  1917. expect(importNode).toBeDefined();
  1918. expect(importNode?.name).toBe('../utils/helpers.dart');
  1919. });
  1920. });
  1921. describe('Liquid imports', () => {
  1922. it('should extract render tag', () => {
  1923. const code = `{% render 'loading-spinner' %}`;
  1924. const result = extractFromSource('template.liquid', code);
  1925. const importNode = result.nodes.find((n) => n.kind === 'import');
  1926. expect(importNode).toBeDefined();
  1927. expect(importNode?.name).toBe('loading-spinner');
  1928. expect(importNode?.signature).toContain('render');
  1929. });
  1930. it('should extract section tag', () => {
  1931. const code = `{% section 'header' %}`;
  1932. const result = extractFromSource('layout/theme.liquid', code);
  1933. const importNode = result.nodes.find((n) => n.kind === 'import');
  1934. expect(importNode).toBeDefined();
  1935. expect(importNode?.name).toBe('header');
  1936. expect(importNode?.signature).toContain('section');
  1937. });
  1938. it('should extract include tag', () => {
  1939. const code = `{% include 'icon-cart' %}`;
  1940. const result = extractFromSource('snippets/header.liquid', code);
  1941. const importNode = result.nodes.find((n) => n.kind === 'import');
  1942. expect(importNode).toBeDefined();
  1943. expect(importNode?.name).toBe('icon-cart');
  1944. expect(importNode?.signature).toContain('include');
  1945. });
  1946. it('should extract render with whitespace control', () => {
  1947. const code = `{%- render 'price' -%}`;
  1948. const result = extractFromSource('snippets/product.liquid', code);
  1949. const importNode = result.nodes.find((n) => n.kind === 'import');
  1950. expect(importNode).toBeDefined();
  1951. expect(importNode?.name).toBe('price');
  1952. });
  1953. it('should extract multiple imports', () => {
  1954. const code = `
  1955. {% section 'header' %}
  1956. {% render 'loading-spinner' %}
  1957. {% render 'cart-drawer' %}
  1958. `;
  1959. const result = extractFromSource('layout/theme.liquid', code);
  1960. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1961. expect(importNodes.length).toBe(3);
  1962. const names = importNodes.map((n) => n.name);
  1963. expect(names).toContain('header');
  1964. expect(names).toContain('loading-spinner');
  1965. expect(names).toContain('cart-drawer');
  1966. });
  1967. });
  1968. });
  1969. // =============================================================================
  1970. // Pascal / Delphi Extraction
  1971. // =============================================================================
  1972. describe('Pascal / Delphi Extraction', () => {
  1973. describe('Language detection', () => {
  1974. it('should detect Pascal files', () => {
  1975. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1976. expect(detectLanguage('App.dpr')).toBe('pascal');
  1977. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1978. expect(detectLanguage('App.lpr')).toBe('pascal');
  1979. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1980. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1981. });
  1982. it('should report Pascal as supported', () => {
  1983. expect(isLanguageSupported('pascal')).toBe(true);
  1984. expect(getSupportedLanguages()).toContain('pascal');
  1985. });
  1986. });
  1987. describe('Unit extraction', () => {
  1988. it('should extract unit as module', () => {
  1989. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1990. const result = extractFromSource('MyUnit.pas', code);
  1991. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1992. expect(moduleNode).toBeDefined();
  1993. expect(moduleNode?.name).toBe('MyUnit');
  1994. expect(moduleNode?.language).toBe('pascal');
  1995. });
  1996. it('should extract program as module', () => {
  1997. const code = `program MyApp;\nbegin\nend.`;
  1998. const result = extractFromSource('MyApp.dpr', code);
  1999. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2000. expect(moduleNode).toBeDefined();
  2001. expect(moduleNode?.name).toBe('MyApp');
  2002. });
  2003. it('should fallback to filename when module name is empty', () => {
  2004. // Some .dpr templates use "program;" without a name
  2005. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2006. const result = extractFromSource('Console.dpr', code);
  2007. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2008. expect(moduleNode).toBeDefined();
  2009. expect(moduleNode?.name).toBe('Console');
  2010. });
  2011. });
  2012. describe('Uses clause (imports)', () => {
  2013. it('should extract uses as individual imports', () => {
  2014. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2015. const result = extractFromSource('Test.pas', code);
  2016. const imports = result.nodes.filter((n) => n.kind === 'import');
  2017. expect(imports.length).toBe(2);
  2018. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2019. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2020. });
  2021. it('should create unresolved references for imports', () => {
  2022. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2023. const result = extractFromSource('Test.pas', code);
  2024. const importRef = result.unresolvedReferences.find(
  2025. (r) => r.referenceKind === 'imports'
  2026. );
  2027. expect(importRef).toBeDefined();
  2028. expect(importRef?.referenceName).toBe('UAuth');
  2029. });
  2030. });
  2031. describe('Class extraction', () => {
  2032. it('should extract class declarations', () => {
  2033. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2034. const result = extractFromSource('Test.pas', code);
  2035. const classNode = result.nodes.find((n) => n.kind === 'class');
  2036. expect(classNode).toBeDefined();
  2037. expect(classNode?.name).toBe('TMyClass');
  2038. });
  2039. it('should extract class with inheritance', () => {
  2040. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2041. const result = extractFromSource('Test.pas', code);
  2042. const extendsRef = result.unresolvedReferences.find(
  2043. (r) => r.referenceKind === 'extends'
  2044. );
  2045. expect(extendsRef).toBeDefined();
  2046. expect(extendsRef?.referenceName).toBe('TParent');
  2047. });
  2048. it('should extract class with interface implementation', () => {
  2049. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2050. const result = extractFromSource('Test.pas', code);
  2051. const extendsRef = result.unresolvedReferences.find(
  2052. (r) => r.referenceKind === 'extends'
  2053. );
  2054. const implementsRef = result.unresolvedReferences.find(
  2055. (r) => r.referenceKind === 'implements'
  2056. );
  2057. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2058. expect(implementsRef?.referenceName).toBe('ILogger');
  2059. });
  2060. });
  2061. describe('Record extraction', () => {
  2062. it('should extract records as class nodes', () => {
  2063. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2064. const result = extractFromSource('Test.pas', code);
  2065. const classNode = result.nodes.find((n) => n.kind === 'class');
  2066. expect(classNode).toBeDefined();
  2067. expect(classNode?.name).toBe('TPoint');
  2068. const fields = result.nodes.filter((n) => n.kind === 'field');
  2069. expect(fields.length).toBe(2);
  2070. expect(fields.map((f) => f.name)).toContain('X');
  2071. expect(fields.map((f) => f.name)).toContain('Y');
  2072. });
  2073. });
  2074. describe('Interface extraction', () => {
  2075. it('should extract interface declarations', () => {
  2076. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2077. const result = extractFromSource('Test.pas', code);
  2078. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2079. expect(ifaceNode).toBeDefined();
  2080. expect(ifaceNode?.name).toBe('ILogger');
  2081. });
  2082. });
  2083. describe('Method extraction', () => {
  2084. it('should extract methods with visibility', () => {
  2085. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n private\n FValue: Integer;\n public\n constructor Create;\n function GetValue: Integer;\n end;\nimplementation\nend.`;
  2086. const result = extractFromSource('Test.pas', code);
  2087. const methods = result.nodes.filter((n) => n.kind === 'method');
  2088. expect(methods.length).toBe(2);
  2089. const createMethod = methods.find((m) => m.name === 'Create');
  2090. expect(createMethod?.visibility).toBe('public');
  2091. const getValue = methods.find((m) => m.name === 'GetValue');
  2092. expect(getValue?.visibility).toBe('public');
  2093. const fields = result.nodes.filter((n) => n.kind === 'field');
  2094. const fValue = fields.find((f) => f.name === 'FValue');
  2095. expect(fValue?.visibility).toBe('private');
  2096. });
  2097. it('should detect static methods (class methods)', () => {
  2098. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2099. const result = extractFromSource('Test.pas', code);
  2100. const methods = result.nodes.filter((n) => n.kind === 'method');
  2101. const staticMethod = methods.find((m) => m.name === 'Create');
  2102. expect(staticMethod?.isStatic).toBe(true);
  2103. });
  2104. });
  2105. describe('Enum extraction', () => {
  2106. it('should extract enums with members', () => {
  2107. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2108. const result = extractFromSource('Test.pas', code);
  2109. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2110. expect(enumNode).toBeDefined();
  2111. expect(enumNode?.name).toBe('TColor');
  2112. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2113. expect(members.length).toBe(3);
  2114. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2115. });
  2116. });
  2117. describe('Property extraction', () => {
  2118. it('should extract properties', () => {
  2119. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2120. const result = extractFromSource('Test.pas', code);
  2121. const propNode = result.nodes.find((n) => n.kind === 'property');
  2122. expect(propNode).toBeDefined();
  2123. expect(propNode?.name).toBe('Name');
  2124. expect(propNode?.visibility).toBe('public');
  2125. });
  2126. });
  2127. describe('Constant extraction', () => {
  2128. it('should extract constants', () => {
  2129. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2130. const result = extractFromSource('Test.pas', code);
  2131. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2132. expect(constants.length).toBe(2);
  2133. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2134. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2135. });
  2136. });
  2137. describe('Type alias extraction', () => {
  2138. it('should extract type aliases', () => {
  2139. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2140. const result = extractFromSource('Test.pas', code);
  2141. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2142. expect(aliasNode).toBeDefined();
  2143. expect(aliasNode?.name).toBe('TUserName');
  2144. });
  2145. });
  2146. describe('Call extraction', () => {
  2147. it('should extract calls from implementation bodies', () => {
  2148. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure DoWork;\n end;\nimplementation\nprocedure TObj.DoWork;\nbegin\n WriteLn('hello');\nend;\nend.`;
  2149. const result = extractFromSource('Test.pas', code);
  2150. const callRef = result.unresolvedReferences.find(
  2151. (r) => r.referenceKind === 'calls'
  2152. );
  2153. expect(callRef).toBeDefined();
  2154. expect(callRef?.referenceName).toBe('WriteLn');
  2155. });
  2156. });
  2157. describe('Containment edges', () => {
  2158. it('should create contains edges for class members', () => {
  2159. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2160. const result = extractFromSource('Test.pas', code);
  2161. const classNode = result.nodes.find((n) => n.kind === 'class');
  2162. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2163. expect(classNode).toBeDefined();
  2164. expect(methodNode).toBeDefined();
  2165. const containsEdge = result.edges.find(
  2166. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2167. );
  2168. expect(containsEdge).toBeDefined();
  2169. });
  2170. });
  2171. describe('Full fixture: UAuth.pas', () => {
  2172. const code = `unit UAuth;
  2173. interface
  2174. uses
  2175. System.SysUtils,
  2176. System.Classes;
  2177. type
  2178. ITokenValidator = interface
  2179. ['{11111111-1111-1111-1111-111111111111}']
  2180. function Validate(const AToken: string): Boolean;
  2181. end;
  2182. TAuthService = class(TInterfacedObject, ITokenValidator)
  2183. private
  2184. FToken: string;
  2185. FLoginCount: Integer;
  2186. procedure IncLoginCount;
  2187. protected
  2188. function GetToken: string;
  2189. public
  2190. constructor Create;
  2191. destructor Destroy; override;
  2192. function Validate(const AToken: string): Boolean;
  2193. function Login(const AUser, APass: string): string;
  2194. property Token: string read GetToken;
  2195. property LoginCount: Integer read FLoginCount;
  2196. end;
  2197. implementation
  2198. constructor TAuthService.Create;
  2199. begin
  2200. inherited Create;
  2201. FToken := '';
  2202. FLoginCount := 0;
  2203. end;
  2204. destructor TAuthService.Destroy;
  2205. begin
  2206. FToken := '';
  2207. inherited Destroy;
  2208. end;
  2209. procedure TAuthService.IncLoginCount;
  2210. begin
  2211. Inc(FLoginCount);
  2212. end;
  2213. function TAuthService.GetToken: string;
  2214. begin
  2215. Result := FToken;
  2216. end;
  2217. function TAuthService.Validate(const AToken: string): Boolean;
  2218. begin
  2219. Result := AToken <> '';
  2220. end;
  2221. function TAuthService.Login(const AUser, APass: string): string;
  2222. begin
  2223. IncLoginCount;
  2224. if Validate(AUser + ':' + APass) then
  2225. begin
  2226. FToken := AUser;
  2227. Result := 'ok';
  2228. end
  2229. else
  2230. Result := '';
  2231. end;
  2232. end.`;
  2233. it('should extract all expected nodes', () => {
  2234. const result = extractFromSource('UAuth.pas', code);
  2235. expect(result.errors).toHaveLength(0);
  2236. // Module
  2237. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2238. expect(moduleNode?.name).toBe('UAuth');
  2239. // Imports
  2240. const imports = result.nodes.filter((n) => n.kind === 'import');
  2241. expect(imports.length).toBe(2);
  2242. // Interface
  2243. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2244. expect(ifaceNode?.name).toBe('ITokenValidator');
  2245. // Class
  2246. const classNode = result.nodes.find((n) => n.kind === 'class');
  2247. expect(classNode?.name).toBe('TAuthService');
  2248. // Methods
  2249. const methods = result.nodes.filter((n) => n.kind === 'method');
  2250. expect(methods.length).toBeGreaterThanOrEqual(6);
  2251. expect(methods.map((m) => m.name)).toContain('Create');
  2252. expect(methods.map((m) => m.name)).toContain('Destroy');
  2253. expect(methods.map((m) => m.name)).toContain('Login');
  2254. // Fields
  2255. const fields = result.nodes.filter((n) => n.kind === 'field');
  2256. expect(fields.length).toBe(2);
  2257. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2258. // Properties
  2259. const props = result.nodes.filter((n) => n.kind === 'property');
  2260. expect(props.length).toBe(2);
  2261. expect(props.map((p) => p.name)).toContain('Token');
  2262. expect(props.map((p) => p.name)).toContain('LoginCount');
  2263. });
  2264. it('should extract inheritance and interface implementation', () => {
  2265. const result = extractFromSource('UAuth.pas', code);
  2266. const extendsRef = result.unresolvedReferences.find(
  2267. (r) => r.referenceKind === 'extends'
  2268. );
  2269. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2270. const implementsRef = result.unresolvedReferences.find(
  2271. (r) => r.referenceKind === 'implements'
  2272. );
  2273. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2274. });
  2275. it('should extract calls from implementation', () => {
  2276. const result = extractFromSource('UAuth.pas', code);
  2277. const callRefs = result.unresolvedReferences.filter(
  2278. (r) => r.referenceKind === 'calls'
  2279. );
  2280. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2281. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2282. });
  2283. });
  2284. describe('Full fixture: UTypes.pas', () => {
  2285. const code = `unit UTypes;
  2286. interface
  2287. uses
  2288. System.SysUtils;
  2289. const
  2290. C_MAX_RETRIES = 3;
  2291. C_DEFAULT_NAME = 'Guest';
  2292. type
  2293. TUserRole = (urAdmin, urEditor, urViewer);
  2294. TPoint2D = record
  2295. X: Double;
  2296. Y: Double;
  2297. end;
  2298. TUserName = string;
  2299. TUserInfo = class
  2300. public
  2301. type
  2302. TAddress = record
  2303. Street: string;
  2304. City: string;
  2305. Zip: string;
  2306. end;
  2307. private
  2308. FName: TUserName;
  2309. FRole: TUserRole;
  2310. FAddress: TAddress;
  2311. public
  2312. constructor Create(const AName: TUserName; ARole: TUserRole);
  2313. function GetDisplayName: string;
  2314. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2315. property Name: TUserName read FName write FName;
  2316. property Role: TUserRole read FRole;
  2317. property Address: TAddress read FAddress write FAddress;
  2318. end;
  2319. implementation
  2320. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2321. begin
  2322. FName := AName;
  2323. FRole := ARole;
  2324. end;
  2325. function TUserInfo.GetDisplayName: string;
  2326. begin
  2327. if FRole = urAdmin then
  2328. Result := '[Admin] ' + FName
  2329. else
  2330. Result := FName;
  2331. end;
  2332. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2333. begin
  2334. Result := TUserInfo.Create(AName, urAdmin);
  2335. end;
  2336. end.`;
  2337. it('should extract enums with members', () => {
  2338. const result = extractFromSource('UTypes.pas', code);
  2339. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2340. expect(enumNode?.name).toBe('TUserRole');
  2341. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2342. expect(members.length).toBe(3);
  2343. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2344. });
  2345. it('should extract constants', () => {
  2346. const result = extractFromSource('UTypes.pas', code);
  2347. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2348. expect(constants.length).toBe(2);
  2349. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2350. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2351. });
  2352. it('should extract type aliases', () => {
  2353. const result = extractFromSource('UTypes.pas', code);
  2354. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2355. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2356. });
  2357. it('should extract records as classes with fields', () => {
  2358. const result = extractFromSource('UTypes.pas', code);
  2359. const classes = result.nodes.filter((n) => n.kind === 'class');
  2360. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2361. // TPoint2D fields
  2362. const fields = result.nodes.filter((n) => n.kind === 'field');
  2363. expect(fields.map((f) => f.name)).toContain('X');
  2364. expect(fields.map((f) => f.name)).toContain('Y');
  2365. });
  2366. it('should extract static class methods', () => {
  2367. const result = extractFromSource('UTypes.pas', code);
  2368. const methods = result.nodes.filter((n) => n.kind === 'method');
  2369. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2370. expect(staticMethod).toBeDefined();
  2371. expect(staticMethod?.isStatic).toBe(true);
  2372. });
  2373. it('should extract nested types', () => {
  2374. const result = extractFromSource('UTypes.pas', code);
  2375. const classes = result.nodes.filter((n) => n.kind === 'class');
  2376. expect(classes.map((c) => c.name)).toContain('TAddress');
  2377. });
  2378. });
  2379. });
  2380. // =============================================================================
  2381. // DFM/FMX Extraction
  2382. // =============================================================================
  2383. describe('DFM/FMX Extraction', () => {
  2384. it('should extract components from DFM', () => {
  2385. const code = `object Form1: TForm1
  2386. Left = 0
  2387. Top = 0
  2388. Caption = 'My Form'
  2389. object Button1: TButton
  2390. Left = 10
  2391. Top = 10
  2392. Caption = 'Click Me'
  2393. end
  2394. end`;
  2395. const result = extractFromSource('Form1.dfm', code);
  2396. const components = result.nodes.filter((n) => n.kind === 'component');
  2397. expect(components.length).toBe(2);
  2398. expect(components.map((c) => c.name)).toContain('Form1');
  2399. expect(components.map((c) => c.name)).toContain('Button1');
  2400. const button = components.find((c) => c.name === 'Button1');
  2401. expect(button?.signature).toBe('TButton');
  2402. });
  2403. it('should extract nested component hierarchy', () => {
  2404. const code = `object Form1: TForm1
  2405. object Panel1: TPanel
  2406. object Label1: TLabel
  2407. Caption = 'Hello'
  2408. end
  2409. end
  2410. end`;
  2411. const result = extractFromSource('Form1.dfm', code);
  2412. const components = result.nodes.filter((n) => n.kind === 'component');
  2413. expect(components.length).toBe(3);
  2414. // Check nesting: Panel1 contains Label1
  2415. const panel = components.find((c) => c.name === 'Panel1');
  2416. const label = components.find((c) => c.name === 'Label1');
  2417. const containsEdge = result.edges.find(
  2418. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2419. );
  2420. expect(containsEdge).toBeDefined();
  2421. });
  2422. it('should extract event handler references', () => {
  2423. const code = `object Form1: TForm1
  2424. OnCreate = FormCreate
  2425. OnDestroy = FormDestroy
  2426. object Button1: TButton
  2427. OnClick = Button1Click
  2428. end
  2429. end`;
  2430. const result = extractFromSource('Form1.dfm', code);
  2431. const refs = result.unresolvedReferences;
  2432. expect(refs.length).toBe(3);
  2433. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2434. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2435. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2436. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2437. });
  2438. it('should handle multi-line properties', () => {
  2439. const code = `object Form1: TForm1
  2440. SQL.Strings = (
  2441. 'SELECT * FROM users'
  2442. 'WHERE active = 1')
  2443. object Button1: TButton
  2444. OnClick = Button1Click
  2445. end
  2446. end`;
  2447. const result = extractFromSource('Form1.dfm', code);
  2448. const components = result.nodes.filter((n) => n.kind === 'component');
  2449. expect(components.length).toBe(2);
  2450. const refs = result.unresolvedReferences;
  2451. expect(refs.length).toBe(1);
  2452. expect(refs[0]?.referenceName).toBe('Button1Click');
  2453. });
  2454. it('should handle inherited keyword', () => {
  2455. const code = `inherited Form1: TForm1
  2456. Caption = 'Inherited Form'
  2457. object Button1: TButton
  2458. OnClick = Button1Click
  2459. end
  2460. end`;
  2461. const result = extractFromSource('Form1.dfm', code);
  2462. const components = result.nodes.filter((n) => n.kind === 'component');
  2463. expect(components.length).toBe(2);
  2464. expect(components.map((c) => c.name)).toContain('Form1');
  2465. });
  2466. it('should handle item collection properties', () => {
  2467. const code = `object Form1: TForm1
  2468. object StatusBar1: TStatusBar
  2469. Panels = <
  2470. item
  2471. Width = 200
  2472. end
  2473. item
  2474. Width = 200
  2475. end>
  2476. end
  2477. end`;
  2478. const result = extractFromSource('Form1.dfm', code);
  2479. const components = result.nodes.filter((n) => n.kind === 'component');
  2480. expect(components.length).toBe(2);
  2481. });
  2482. describe('Full fixture: MainForm.dfm', () => {
  2483. const code = `object frmMain: TfrmMain
  2484. Left = 0
  2485. Top = 0
  2486. Caption = 'CodeGraph DFM Fixture'
  2487. ClientHeight = 480
  2488. ClientWidth = 640
  2489. OnCreate = FormCreate
  2490. OnDestroy = FormDestroy
  2491. object pnlTop: TPanel
  2492. Left = 0
  2493. Top = 0
  2494. Width = 640
  2495. Height = 50
  2496. object lblTitle: TLabel
  2497. Left = 16
  2498. Top = 16
  2499. Caption = 'Authentication Service'
  2500. end
  2501. object btnLogin: TButton
  2502. Left = 540
  2503. Top = 12
  2504. OnClick = btnLoginClick
  2505. end
  2506. end
  2507. object pnlContent: TPanel
  2508. Left = 0
  2509. Top = 50
  2510. object edtUsername: TEdit
  2511. Left = 16
  2512. Top = 16
  2513. OnChange = edtUsernameChange
  2514. end
  2515. object edtPassword: TEdit
  2516. Left = 16
  2517. Top = 48
  2518. OnKeyPress = edtPasswordKeyPress
  2519. end
  2520. object mmoLog: TMemo
  2521. Left = 16
  2522. Top = 88
  2523. end
  2524. end
  2525. object pnlStatus: TStatusBar
  2526. Left = 0
  2527. Top = 440
  2528. Panels = <
  2529. item
  2530. Width = 200
  2531. end
  2532. item
  2533. Width = 200
  2534. end>
  2535. end
  2536. end`;
  2537. it('should extract all components', () => {
  2538. const result = extractFromSource('MainForm.dfm', code);
  2539. const components = result.nodes.filter((n) => n.kind === 'component');
  2540. expect(components.length).toBe(9);
  2541. expect(components.map((c) => c.name)).toEqual(
  2542. expect.arrayContaining([
  2543. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2544. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2545. ])
  2546. );
  2547. });
  2548. it('should extract all event handlers', () => {
  2549. const result = extractFromSource('MainForm.dfm', code);
  2550. const refs = result.unresolvedReferences;
  2551. expect(refs.length).toBe(5);
  2552. expect(refs.map((r) => r.referenceName)).toEqual(
  2553. expect.arrayContaining([
  2554. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2555. 'edtUsernameChange', 'edtPasswordKeyPress',
  2556. ])
  2557. );
  2558. });
  2559. });
  2560. });
  2561. describe('Full Indexing', () => {
  2562. let tempDir: string;
  2563. beforeEach(() => {
  2564. tempDir = createTempDir();
  2565. });
  2566. afterEach(() => {
  2567. cleanupTempDir(tempDir);
  2568. });
  2569. it('should index a TypeScript file', async () => {
  2570. // Create test file
  2571. const srcDir = path.join(tempDir, 'src');
  2572. fs.mkdirSync(srcDir);
  2573. fs.writeFileSync(
  2574. path.join(srcDir, 'utils.ts'),
  2575. `
  2576. export function add(a: number, b: number): number {
  2577. return a + b;
  2578. }
  2579. export function multiply(a: number, b: number): number {
  2580. return a * b;
  2581. }
  2582. `
  2583. );
  2584. // Initialize and index
  2585. const cg = CodeGraph.initSync(tempDir);
  2586. const result = await cg.indexAll();
  2587. expect(result.success).toBe(true);
  2588. expect(result.filesIndexed).toBe(1);
  2589. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2590. // Check nodes were stored
  2591. const nodes = cg.getNodesInFile('src/utils.ts');
  2592. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2593. const addFunc = nodes.find((n) => n.name === 'add');
  2594. expect(addFunc).toBeDefined();
  2595. expect(addFunc?.kind).toBe('function');
  2596. cg.close();
  2597. });
  2598. it('should index multiple files', async () => {
  2599. // Create test files
  2600. const srcDir = path.join(tempDir, 'src');
  2601. fs.mkdirSync(srcDir);
  2602. fs.writeFileSync(
  2603. path.join(srcDir, 'math.ts'),
  2604. `export function add(a: number, b: number) { return a + b; }`
  2605. );
  2606. fs.writeFileSync(
  2607. path.join(srcDir, 'string.ts'),
  2608. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2609. );
  2610. // Initialize and index
  2611. const cg = CodeGraph.initSync(tempDir);
  2612. const result = await cg.indexAll();
  2613. expect(result.success).toBe(true);
  2614. expect(result.filesIndexed).toBe(2);
  2615. const files = cg.getFiles();
  2616. expect(files.length).toBe(2);
  2617. cg.close();
  2618. });
  2619. it('should track file hashes for incremental updates', async () => {
  2620. // Create initial file
  2621. const srcDir = path.join(tempDir, 'src');
  2622. fs.mkdirSync(srcDir);
  2623. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2624. // Initialize and index
  2625. const cg = CodeGraph.initSync(tempDir);
  2626. await cg.indexAll();
  2627. // Check file is tracked
  2628. const file = cg.getFile('src/main.ts');
  2629. expect(file).toBeDefined();
  2630. expect(file?.contentHash).toBeDefined();
  2631. // Modify file
  2632. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2633. // Check for changes
  2634. const changes = cg.getChangedFiles();
  2635. expect(changes.modified).toContain('src/main.ts');
  2636. cg.close();
  2637. });
  2638. it('should sync and detect changes', async () => {
  2639. // Create initial file
  2640. const srcDir = path.join(tempDir, 'src');
  2641. fs.mkdirSync(srcDir);
  2642. fs.writeFileSync(
  2643. path.join(srcDir, 'main.ts'),
  2644. `export function original() { return 1; }`
  2645. );
  2646. // Initialize and index
  2647. const cg = CodeGraph.initSync(tempDir);
  2648. await cg.indexAll();
  2649. const initialNodes = cg.getNodesInFile('src/main.ts');
  2650. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2651. // Modify file
  2652. fs.writeFileSync(
  2653. path.join(srcDir, 'main.ts'),
  2654. `export function updated() { return 2; }`
  2655. );
  2656. // Sync
  2657. const syncResult = await cg.sync();
  2658. expect(syncResult.filesModified).toBe(1);
  2659. // Check nodes were updated
  2660. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2661. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2662. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2663. cg.close();
  2664. });
  2665. it('should count file-level tracked YAML files as indexed', async () => {
  2666. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  2667. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  2668. const cg = CodeGraph.initSync(tempDir);
  2669. const result = await cg.indexAll();
  2670. expect(result.success).toBe(true);
  2671. expect(result.filesIndexed).toBe(2);
  2672. expect(result.filesSkipped).toBe(0);
  2673. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  2674. cg.close();
  2675. });
  2676. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  2677. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  2678. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  2679. const cg = CodeGraph.initSync(tempDir);
  2680. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  2681. expect(result.success).toBe(true);
  2682. expect(result.filesIndexed).toBe(2);
  2683. expect(result.filesSkipped).toBe(0);
  2684. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  2685. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  2686. cg.close();
  2687. });
  2688. it('should count file-level tracked .properties files as indexed', async () => {
  2689. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  2690. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  2691. const cg = CodeGraph.initSync(tempDir);
  2692. const result = await cg.indexAll();
  2693. expect(result.success).toBe(true);
  2694. expect(result.filesIndexed).toBe(2);
  2695. expect(result.filesSkipped).toBe(0);
  2696. cg.close();
  2697. });
  2698. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  2699. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  2700. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  2701. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  2702. const cg = CodeGraph.initSync(tempDir);
  2703. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  2704. expect(result.success).toBe(true);
  2705. expect(result.filesIndexed).toBe(3);
  2706. expect(result.filesSkipped).toBe(0);
  2707. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  2708. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  2709. cg.close();
  2710. });
  2711. });
  2712. describe('Path Normalization', () => {
  2713. it('should convert backslashes to forward slashes', () => {
  2714. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2715. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2716. });
  2717. it('should leave forward-slash paths unchanged', () => {
  2718. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2719. });
  2720. it('should handle empty string', () => {
  2721. expect(normalizePath('')).toBe('');
  2722. });
  2723. });
  2724. describe('Directory Exclusion', () => {
  2725. let tempDir: string;
  2726. beforeEach(() => {
  2727. tempDir = createTempDir();
  2728. });
  2729. afterEach(() => {
  2730. cleanupTempDir(tempDir);
  2731. });
  2732. it('should exclude directories listed in .gitignore', () => {
  2733. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  2734. const srcDir = path.join(tempDir, 'src');
  2735. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2736. fs.mkdirSync(srcDir, { recursive: true });
  2737. fs.mkdirSync(nmDir, { recursive: true });
  2738. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2739. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2740. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2741. const files = scanDirectory(tempDir);
  2742. expect(files).toContain('src/index.ts');
  2743. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2744. });
  2745. it('should exclude nested node_modules via a root .gitignore', () => {
  2746. // A trailing-slash pattern with no leading slash matches at any depth.
  2747. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2748. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2749. fs.mkdirSync(srcDir, { recursive: true });
  2750. fs.mkdirSync(nmDir, { recursive: true });
  2751. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2752. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2753. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2754. const files = scanDirectory(tempDir);
  2755. expect(files).toContain('packages/app/src/index.ts');
  2756. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2757. });
  2758. it('should apply a nested .gitignore only to its own subtree', () => {
  2759. const appSrc = path.join(tempDir, 'app', 'src');
  2760. fs.mkdirSync(appSrc, { recursive: true });
  2761. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  2762. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  2763. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  2764. // A sibling with the same name outside app/ must NOT be ignored.
  2765. const otherDir = path.join(tempDir, 'other', 'src');
  2766. fs.mkdirSync(otherDir, { recursive: true });
  2767. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  2768. const files = scanDirectory(tempDir);
  2769. expect(files).toContain('app/src/keep.ts');
  2770. expect(files).not.toContain('app/src/skip.ts');
  2771. expect(files).toContain('other/src/skip.ts');
  2772. });
  2773. it('should always skip .git directories', () => {
  2774. const srcDir = path.join(tempDir, 'src');
  2775. const gitDir = path.join(tempDir, '.git', 'objects');
  2776. fs.mkdirSync(srcDir, { recursive: true });
  2777. fs.mkdirSync(gitDir, { recursive: true });
  2778. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2779. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2780. const files = scanDirectory(tempDir);
  2781. expect(files).toContain('src/index.ts');
  2782. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2783. });
  2784. it('should return forward-slash paths on all platforms', () => {
  2785. const srcDir = path.join(tempDir, 'src', 'components');
  2786. fs.mkdirSync(srcDir, { recursive: true });
  2787. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2788. const files = scanDirectory(tempDir);
  2789. expect(files.length).toBe(1);
  2790. expect(files[0]).toBe('src/components/Button.tsx');
  2791. expect(files[0]).not.toContain('\\');
  2792. });
  2793. });
  2794. describe('Git Submodules', () => {
  2795. let tempDir: string;
  2796. beforeEach(() => {
  2797. tempDir = createTempDir();
  2798. });
  2799. afterEach(() => {
  2800. cleanupTempDir(tempDir);
  2801. });
  2802. it('should index files inside git submodules (issue #147)', async () => {
  2803. const { execFileSync } = await import('child_process');
  2804. const git = (cwd: string, ...args: string[]) =>
  2805. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2806. // Build a separate "library" repo to use as a submodule source.
  2807. const libDir = path.join(tempDir, '_lib');
  2808. fs.mkdirSync(libDir, { recursive: true });
  2809. git(libDir, 'init', '-q');
  2810. git(libDir, 'config', 'user.email', 'test@test.com');
  2811. git(libDir, 'config', 'user.name', 'Test');
  2812. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  2813. git(libDir, 'add', '-A');
  2814. git(libDir, 'commit', '-q', '-m', 'lib init');
  2815. // Build the main repo and add the lib repo as a submodule.
  2816. const mainDir = path.join(tempDir, 'main');
  2817. fs.mkdirSync(mainDir, { recursive: true });
  2818. git(mainDir, 'init', '-q');
  2819. git(mainDir, 'config', 'user.email', 'test@test.com');
  2820. git(mainDir, 'config', 'user.name', 'Test');
  2821. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  2822. git(mainDir, 'add', '-A');
  2823. git(mainDir, 'commit', '-q', '-m', 'app init');
  2824. // protocol.file.allow=always is required to add a local-path submodule on
  2825. // recent git versions (CVE-2022-39253 mitigation).
  2826. execFileSync(
  2827. 'git',
  2828. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  2829. { cwd: mainDir, stdio: 'pipe' }
  2830. );
  2831. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  2832. const files = scanDirectory(mainDir);
  2833. expect(files).toContain('app.ts');
  2834. expect(files).toContain('libs/lib/lib.ts');
  2835. });
  2836. });
  2837. describe('Nested non-submodule git repos', () => {
  2838. let tempDir: string;
  2839. beforeEach(() => {
  2840. tempDir = createTempDir();
  2841. });
  2842. afterEach(() => {
  2843. cleanupTempDir(tempDir);
  2844. });
  2845. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  2846. const { execFileSync } = await import('child_process');
  2847. const git = (cwd: string, ...args: string[]) =>
  2848. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2849. // Top-level workspace is itself a git repo, holding no source directly —
  2850. // the CMake "super-repo" layout from the issue.
  2851. const root = path.join(tempDir, 'root');
  2852. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  2853. git(root, 'init', '-q');
  2854. git(root, 'config', 'user.email', 'test@test.com');
  2855. git(root, 'config', 'user.name', 'Test');
  2856. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  2857. // Two independent clones living inside the workspace (NOT submodules):
  2858. // one with committed source, one with only untracked source.
  2859. const sub1 = path.join(root, 'sub_repo1', 'src');
  2860. fs.mkdirSync(sub1, { recursive: true });
  2861. git(path.join(root, 'sub_repo1'), 'init', '-q');
  2862. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  2863. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  2864. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  2865. git(path.join(root, 'sub_repo1'), 'add', '-A');
  2866. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  2867. const sub2 = path.join(root, 'sub_repo2', 'src');
  2868. fs.mkdirSync(sub2, { recursive: true });
  2869. git(path.join(root, 'sub_repo2'), 'init', '-q');
  2870. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  2871. const files = scanDirectory(root);
  2872. // Both committed and untracked source from the nested repos must be found.
  2873. expect(files).toContain('sub_repo1/src/one.ts');
  2874. expect(files).toContain('sub_repo2/src/two.ts');
  2875. });
  2876. it('should respect each embedded repo\'s own .gitignore', async () => {
  2877. const { execFileSync } = await import('child_process');
  2878. const git = (cwd: string, ...args: string[]) =>
  2879. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2880. const root = path.join(tempDir, 'root');
  2881. fs.mkdirSync(root, { recursive: true });
  2882. git(root, 'init', '-q');
  2883. const sub = path.join(root, 'sub_repo', 'src');
  2884. fs.mkdirSync(sub, { recursive: true });
  2885. git(path.join(root, 'sub_repo'), 'init', '-q');
  2886. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  2887. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  2888. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  2889. const files = scanDirectory(root);
  2890. expect(files).toContain('sub_repo/src/real.ts');
  2891. expect(files).not.toContain('sub_repo/src/generated.ts');
  2892. });
  2893. });
  2894. // =============================================================================
  2895. // Scala
  2896. // =============================================================================
  2897. describe('Scala Extraction', () => {
  2898. describe('Language detection', () => {
  2899. it('should detect Scala files', () => {
  2900. expect(detectLanguage('Main.scala')).toBe('scala');
  2901. expect(detectLanguage('script.sc')).toBe('scala');
  2902. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  2903. });
  2904. it('should report Scala as supported', () => {
  2905. expect(isLanguageSupported('scala')).toBe(true);
  2906. expect(getSupportedLanguages()).toContain('scala');
  2907. });
  2908. });
  2909. describe('Class extraction', () => {
  2910. it('should extract class definitions', () => {
  2911. const code = `
  2912. class UserService(private val repo: UserRepository) {
  2913. def findUser(id: String): Option[String] = Some(id)
  2914. }
  2915. `;
  2916. const result = extractFromSource('UserService.scala', code);
  2917. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  2918. expect(cls).toBeDefined();
  2919. expect(cls?.language).toBe('scala');
  2920. });
  2921. it('should extract object definitions as class kind', () => {
  2922. const code = `
  2923. object DatabaseConfig {
  2924. val url = "jdbc:postgresql://localhost/mydb"
  2925. }
  2926. `;
  2927. const result = extractFromSource('Config.scala', code);
  2928. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  2929. expect(obj).toBeDefined();
  2930. });
  2931. it('should extract trait definitions as trait kind', () => {
  2932. const code = `
  2933. trait Repository[A] {
  2934. def findById(id: String): Option[A]
  2935. def save(entity: A): Unit
  2936. }
  2937. `;
  2938. const result = extractFromSource('Repository.scala', code);
  2939. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  2940. expect(trait_).toBeDefined();
  2941. });
  2942. });
  2943. describe('Method and function extraction', () => {
  2944. it('should extract method definitions inside a class', () => {
  2945. const code = `
  2946. class Calculator {
  2947. def add(a: Int, b: Int): Int = a + b
  2948. def divide(a: Double, b: Double): Double = a / b
  2949. }
  2950. `;
  2951. const result = extractFromSource('Calculator.scala', code);
  2952. const methods = result.nodes.filter((n) => n.kind === 'method');
  2953. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  2954. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  2955. });
  2956. it('should extract method signatures', () => {
  2957. const code = `
  2958. class Greeter {
  2959. def greet(name: String): String = s"Hello, \${name}!"
  2960. }
  2961. `;
  2962. const result = extractFromSource('Greeter.scala', code);
  2963. const method = result.nodes.find((n) => n.name === 'greet');
  2964. expect(method?.signature).toContain('name: String');
  2965. expect(method?.signature).toContain('String');
  2966. });
  2967. it('should extract top-level function definitions as functions', () => {
  2968. const code = `
  2969. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  2970. def greet(name: String): String = s"Hello, \${name}!"
  2971. `;
  2972. const result = extractFromSource('utils.scala', code);
  2973. const fns = result.nodes.filter((n) => n.kind === 'function');
  2974. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  2975. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  2976. });
  2977. });
  2978. describe('Val and var extraction', () => {
  2979. it('should extract val inside a class as field', () => {
  2980. const code = `
  2981. class Config {
  2982. val timeout: Int = 30
  2983. val host: String = "localhost"
  2984. }
  2985. `;
  2986. const result = extractFromSource('Config.scala', code);
  2987. const fields = result.nodes.filter((n) => n.kind === 'field');
  2988. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  2989. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  2990. });
  2991. it('should extract var inside a class as field', () => {
  2992. const code = `
  2993. class Counter {
  2994. var count: Int = 0
  2995. }
  2996. `;
  2997. const result = extractFromSource('Counter.scala', code);
  2998. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  2999. expect(field).toBeDefined();
  3000. });
  3001. it('should extract top-level val as constant', () => {
  3002. const code = `
  3003. val MaxConnections: Int = 100
  3004. val DefaultTimeout = 30
  3005. `;
  3006. const result = extractFromSource('constants.scala', code);
  3007. const consts = result.nodes.filter((n) => n.kind === 'constant');
  3008. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  3009. });
  3010. it('should extract top-level var as variable', () => {
  3011. const code = `
  3012. var retries: Int = 3
  3013. `;
  3014. const result = extractFromSource('state.scala', code);
  3015. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  3016. expect(v).toBeDefined();
  3017. });
  3018. it('should include type in val/var signature', () => {
  3019. const code = `
  3020. class Service {
  3021. val timeout: Int = 30
  3022. }
  3023. `;
  3024. const result = extractFromSource('Service.scala', code);
  3025. const field = result.nodes.find((n) => n.name === 'timeout');
  3026. expect(field?.signature).toContain('timeout');
  3027. expect(field?.signature).toContain('Int');
  3028. });
  3029. });
  3030. describe('Enum extraction', () => {
  3031. it('should extract enum definitions', () => {
  3032. const code = `
  3033. enum Color:
  3034. case Red
  3035. case Green
  3036. case Blue
  3037. `;
  3038. const result = extractFromSource('Color.scala', code);
  3039. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  3040. expect(enumNode).toBeDefined();
  3041. });
  3042. it('should extract enum cases as enum_member', () => {
  3043. const code = `
  3044. enum Direction:
  3045. case North
  3046. case South
  3047. case East
  3048. case West
  3049. `;
  3050. const result = extractFromSource('Direction.scala', code);
  3051. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3052. expect(members.find((m) => m.name === 'North')).toBeDefined();
  3053. expect(members.find((m) => m.name === 'South')).toBeDefined();
  3054. expect(members.length).toBeGreaterThanOrEqual(4);
  3055. });
  3056. });
  3057. describe('Type alias extraction', () => {
  3058. it('should extract type aliases', () => {
  3059. const code = `
  3060. type UserId = String
  3061. type UserMap = Map[String, String]
  3062. `;
  3063. const result = extractFromSource('types.scala', code);
  3064. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3065. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  3066. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  3067. });
  3068. });
  3069. describe('Import extraction', () => {
  3070. it('should extract import declarations', () => {
  3071. const code = `
  3072. import scala.collection.mutable.ListBuffer
  3073. import scala.concurrent.Future
  3074. `;
  3075. const result = extractFromSource('imports.scala', code);
  3076. const imports = result.nodes.filter((n) => n.kind === 'import');
  3077. expect(imports.length).toBeGreaterThanOrEqual(2);
  3078. });
  3079. });
  3080. describe('Visibility modifiers', () => {
  3081. it('should extract private visibility', () => {
  3082. const code = `
  3083. class Service {
  3084. private val secret: String = "abc"
  3085. private def helper(): Unit = {}
  3086. }
  3087. `;
  3088. const result = extractFromSource('Service.scala', code);
  3089. const secretField = result.nodes.find((n) => n.name === 'secret');
  3090. expect(secretField?.visibility).toBe('private');
  3091. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  3092. expect(helperMethod?.visibility).toBe('private');
  3093. });
  3094. it('should extract protected visibility', () => {
  3095. const code = `
  3096. class Base {
  3097. protected def helperMethod(): Unit = {}
  3098. }
  3099. `;
  3100. const result = extractFromSource('Base.scala', code);
  3101. const method = result.nodes.find((n) => n.name === 'helperMethod');
  3102. expect(method?.visibility).toBe('protected');
  3103. });
  3104. it('should default to public visibility', () => {
  3105. const code = `
  3106. class Greeter {
  3107. def hello(): Unit = {}
  3108. }
  3109. `;
  3110. const result = extractFromSource('Greeter.scala', code);
  3111. const method = result.nodes.find((n) => n.name === 'hello');
  3112. expect(method?.visibility).toBe('public');
  3113. });
  3114. });
  3115. describe('Inheritance', () => {
  3116. it('should extract extends relationships', () => {
  3117. const code = `
  3118. class AdminUser extends User {
  3119. def adminAction(): Unit = {}
  3120. }
  3121. `;
  3122. const result = extractFromSource('AdminUser.scala', code);
  3123. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3124. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  3125. });
  3126. });
  3127. describe('Call extraction', () => {
  3128. it('should extract function call expressions', () => {
  3129. const code = `
  3130. def processData(): Unit = {
  3131. val result = computeResult()
  3132. println(result)
  3133. }
  3134. `;
  3135. const result = extractFromSource('processor.scala', code);
  3136. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  3137. expect(calls.length).toBeGreaterThan(0);
  3138. });
  3139. });
  3140. });
  3141. describe('Vue Extraction', () => {
  3142. it('should detect Vue files', () => {
  3143. expect(detectLanguage('App.vue')).toBe('vue');
  3144. expect(detectLanguage('components/Button.vue')).toBe('vue');
  3145. expect(isLanguageSupported('vue')).toBe(true);
  3146. });
  3147. it('should extract component node from a Vue SFC', () => {
  3148. const code = `<template>
  3149. <div>{{ message }}</div>
  3150. </template>
  3151. <script>
  3152. export default {
  3153. data() {
  3154. return { message: 'Hello' };
  3155. }
  3156. }
  3157. </script>
  3158. `;
  3159. const result = extractFromSource('HelloWorld.vue', code);
  3160. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3161. expect(componentNode).toBeDefined();
  3162. expect(componentNode?.name).toBe('HelloWorld');
  3163. expect(componentNode?.language).toBe('vue');
  3164. expect(componentNode?.isExported).toBe(true);
  3165. });
  3166. it('should extract functions from <script> block', () => {
  3167. const code = `<template>
  3168. <button @click="handleClick">Click</button>
  3169. </template>
  3170. <script>
  3171. function handleClick() {
  3172. console.log('clicked');
  3173. }
  3174. const count = 0;
  3175. </script>
  3176. `;
  3177. const result = extractFromSource('Button.vue', code);
  3178. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3179. expect(componentNode).toBeDefined();
  3180. expect(componentNode?.name).toBe('Button');
  3181. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  3182. expect(funcNode).toBeDefined();
  3183. expect(funcNode?.language).toBe('vue');
  3184. });
  3185. it('should extract from <script setup lang="ts"> block', () => {
  3186. const code = `<template>
  3187. <div>{{ count }}</div>
  3188. </template>
  3189. <script setup lang="ts">
  3190. import { ref } from 'vue';
  3191. const count = ref(0);
  3192. function increment(): void {
  3193. count.value++;
  3194. }
  3195. </script>
  3196. `;
  3197. const result = extractFromSource('Counter.vue', code);
  3198. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3199. expect(componentNode).toBeDefined();
  3200. expect(componentNode?.name).toBe('Counter');
  3201. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  3202. expect(funcNode).toBeDefined();
  3203. expect(funcNode?.language).toBe('vue');
  3204. // All nodes should be marked as vue language
  3205. for (const node of result.nodes) {
  3206. expect(node.language).toBe('vue');
  3207. }
  3208. });
  3209. it('should extract calls from top-level <script setup> initializers', () => {
  3210. const code = `<template>
  3211. <div>{{ token }}</div>
  3212. </template>
  3213. <script setup lang="ts">
  3214. import { getTokenMp } from './api/upload';
  3215. const token = getTokenMp();
  3216. </script>
  3217. `;
  3218. const result = extractFromSource('Issue425Setup.vue', code);
  3219. const call = result.unresolvedReferences.find(
  3220. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3221. );
  3222. expect(call).toBeDefined();
  3223. });
  3224. it('should extract calls from Vue Options API object methods', () => {
  3225. const code = `<template>
  3226. <button @click="save">Save</button>
  3227. </template>
  3228. <script>
  3229. import { getTokenMp } from './api/upload';
  3230. export default {
  3231. methods: {
  3232. save() {
  3233. return getTokenMp();
  3234. }
  3235. },
  3236. setup() {
  3237. return getTokenMp();
  3238. }
  3239. }
  3240. </script>
  3241. `;
  3242. const result = extractFromSource('Issue425Options.vue', code);
  3243. const calls = result.unresolvedReferences.filter(
  3244. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3245. );
  3246. expect(calls).toHaveLength(2);
  3247. });
  3248. it('should extract from both <script> and <script setup> blocks', () => {
  3249. const code = `<template>
  3250. <div>{{ msg }}</div>
  3251. </template>
  3252. <script>
  3253. export default {
  3254. name: 'DualScript'
  3255. }
  3256. </script>
  3257. <script setup>
  3258. const msg = 'hello';
  3259. function greet() {
  3260. return msg;
  3261. }
  3262. </script>
  3263. `;
  3264. const result = extractFromSource('DualScript.vue', code);
  3265. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3266. expect(componentNode).toBeDefined();
  3267. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  3268. expect(greetFunc).toBeDefined();
  3269. });
  3270. it('should create component node for template-only Vue file', () => {
  3271. const code = `<template>
  3272. <div>Static content</div>
  3273. </template>
  3274. `;
  3275. const result = extractFromSource('Static.vue', code);
  3276. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3277. expect(componentNode).toBeDefined();
  3278. expect(componentNode?.name).toBe('Static');
  3279. expect(componentNode?.language).toBe('vue');
  3280. // Only the component node should exist (no script nodes)
  3281. expect(result.nodes.length).toBe(1);
  3282. });
  3283. it('should create containment edges from component to script nodes', () => {
  3284. const code = `<template>
  3285. <div>{{ value }}</div>
  3286. </template>
  3287. <script setup lang="ts">
  3288. const value = 42;
  3289. </script>
  3290. `;
  3291. const result = extractFromSource('Contained.vue', code);
  3292. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3293. expect(componentNode).toBeDefined();
  3294. // Should have containment edges from component to child nodes
  3295. const containEdges = result.edges.filter(
  3296. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3297. );
  3298. expect(containEdges.length).toBeGreaterThan(0);
  3299. });
  3300. });
  3301. describe('Instantiates + Decorates edge extraction', () => {
  3302. it('emits an instantiates ref for `new Foo()`', () => {
  3303. const code = `
  3304. class Foo {}
  3305. function bootstrap() { return new Foo(); }
  3306. `;
  3307. const result = extractFromSource('app.ts', code);
  3308. const ref = result.unresolvedReferences.find(
  3309. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3310. );
  3311. expect(ref).toBeDefined();
  3312. });
  3313. it('strips type-argument suffix from generic constructors', () => {
  3314. const code = `
  3315. class Container<T> { constructor(_: T) {} }
  3316. function go() { return new Container<string>('x'); }
  3317. `;
  3318. const result = extractFromSource('app.ts', code);
  3319. const ref = result.unresolvedReferences.find(
  3320. (r) => r.referenceKind === 'instantiates'
  3321. );
  3322. expect(ref).toBeDefined();
  3323. // Container<string> must be normalised to "Container" — otherwise
  3324. // resolution can never match the class node.
  3325. expect(ref!.referenceName).toBe('Container');
  3326. });
  3327. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3328. const code = `
  3329. const ns = { Foo: class {} };
  3330. function go() { return new ns.Foo(); }
  3331. `;
  3332. const result = extractFromSource('app.ts', code);
  3333. const ref = result.unresolvedReferences.find(
  3334. (r) => r.referenceKind === 'instantiates'
  3335. );
  3336. // We can't always resolve which Foo, but the name should be the
  3337. // simple identifier so name-matching has a chance.
  3338. expect(ref?.referenceName).toBe('Foo');
  3339. });
  3340. it('emits a decorates ref for `@Foo class X {}`', () => {
  3341. const code = `
  3342. function Foo(_arg: string) { return (cls: any) => cls; }
  3343. @Foo('x')
  3344. class X {}
  3345. `;
  3346. const result = extractFromSource('app.ts', code);
  3347. const decorClass = result.unresolvedReferences.find(
  3348. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3349. );
  3350. expect(decorClass).toBeDefined();
  3351. });
  3352. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3353. // Regression: the sibling-walk must stop at the first non-
  3354. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3355. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3356. // `decorates(Bar, A)`.
  3357. const code = `
  3358. function A(cls: any) { return cls; }
  3359. function B(cls: any) { return cls; }
  3360. @A
  3361. class Foo {}
  3362. @B
  3363. class Bar {}
  3364. `;
  3365. const result = extractFromSource('app.ts', code);
  3366. const decoratesEdges = result.unresolvedReferences.filter(
  3367. (r) => r.referenceKind === 'decorates'
  3368. );
  3369. // Exactly one decorates ref per decorated class, no cross-attribution.
  3370. const fromBar = decoratesEdges.filter((r) =>
  3371. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3372. );
  3373. expect(fromBar.length).toBe(1);
  3374. expect(fromBar[0]!.referenceName).toBe('B');
  3375. });
  3376. it('emits a decorates ref for `@Foo method() {}`', () => {
  3377. const code = `
  3378. function Get(p: string) { return (t: any, k: string) => t; }
  3379. class Svc {
  3380. @Get('/x') method() { return 1; }
  3381. }
  3382. `;
  3383. const result = extractFromSource('app.ts', code);
  3384. const decorMethod = result.unresolvedReferences.find(
  3385. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3386. );
  3387. expect(decorMethod).toBeDefined();
  3388. // The decorated symbol must be `method`, not the constructor or class.
  3389. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3390. expect(decoratedNode?.name).toBe('method');
  3391. });
  3392. });
  3393. // =============================================================================
  3394. // Lua
  3395. // =============================================================================
  3396. describe('Lua Extraction', () => {
  3397. describe('Language detection', () => {
  3398. it('should detect Lua files', () => {
  3399. expect(detectLanguage('init.lua')).toBe('lua');
  3400. expect(detectLanguage('src/util.lua')).toBe('lua');
  3401. });
  3402. it('should report Lua as supported', () => {
  3403. expect(isLanguageSupported('lua')).toBe(true);
  3404. expect(getSupportedLanguages()).toContain('lua');
  3405. });
  3406. });
  3407. describe('Function extraction', () => {
  3408. it('should extract global and local functions', () => {
  3409. const code = `
  3410. function configure(opts) return opts end
  3411. local function helper(x) return x * 2 end
  3412. `;
  3413. const result = extractFromSource('init.lua', code);
  3414. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3415. expect(funcs).toContain('configure');
  3416. expect(funcs).toContain('helper');
  3417. const configure = result.nodes.find((n) => n.name === 'configure');
  3418. expect(configure?.language).toBe('lua');
  3419. expect(configure?.signature).toBe('(opts)');
  3420. });
  3421. it('should split table/method functions into a receiver and method name', () => {
  3422. const code = `
  3423. function M.connect(host, port) return host end
  3424. function M:send(data) return self end
  3425. `;
  3426. const result = extractFromSource('init.lua', code);
  3427. const methods = result.nodes.filter((n) => n.kind === 'method');
  3428. const connect = methods.find((m) => m.name === 'connect');
  3429. expect(connect?.qualifiedName).toBe('M::connect');
  3430. const send = methods.find((m) => m.name === 'send');
  3431. expect(send?.qualifiedName).toBe('M::send');
  3432. });
  3433. });
  3434. describe('Variable extraction', () => {
  3435. it('should extract local variable declarations', () => {
  3436. const code = `
  3437. local M = {}
  3438. local count = 0
  3439. `;
  3440. const result = extractFromSource('mod.lua', code);
  3441. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3442. expect(vars).toContain('M');
  3443. expect(vars).toContain('count');
  3444. });
  3445. });
  3446. describe('Import extraction (require)', () => {
  3447. it('should extract require() in local declarations and bare calls', () => {
  3448. const code = `
  3449. local socket = require("socket")
  3450. local http = require "resty.http"
  3451. require("side.effect")
  3452. `;
  3453. const result = extractFromSource('net.lua', code);
  3454. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3455. expect(imports).toContain('socket');
  3456. expect(imports).toContain('resty.http');
  3457. expect(imports).toContain('side.effect');
  3458. const ref = result.unresolvedReferences.find(
  3459. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3460. );
  3461. expect(ref).toBeDefined();
  3462. });
  3463. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3464. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3465. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3466. // by extracting several sources in sequence and asserting the LAST still works.
  3467. it('should keep extracting require across many sequential parses', () => {
  3468. let last;
  3469. for (let i = 0; i < 8; i++) {
  3470. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3471. }
  3472. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3473. expect(imports).toContain('module.7');
  3474. });
  3475. });
  3476. describe('Call extraction', () => {
  3477. it('should record intra-file calls as resolvable references', () => {
  3478. const code = `
  3479. local function helper(x) return x end
  3480. local function run(y) return helper(y) end
  3481. `;
  3482. const result = extractFromSource('calls.lua', code);
  3483. const call = result.unresolvedReferences.find(
  3484. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3485. );
  3486. expect(call).toBeDefined();
  3487. });
  3488. });
  3489. });
  3490. // =============================================================================
  3491. // Luau (typed superset of Lua — https://luau.org)
  3492. // =============================================================================
  3493. describe('Luau Extraction', () => {
  3494. describe('Language detection', () => {
  3495. it('should detect Luau files', () => {
  3496. expect(detectLanguage('init.luau')).toBe('luau');
  3497. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3498. });
  3499. it('should report Luau as supported', () => {
  3500. expect(isLanguageSupported('luau')).toBe(true);
  3501. expect(getSupportedLanguages()).toContain('luau');
  3502. });
  3503. });
  3504. describe('Type aliases', () => {
  3505. it('should extract `type` and `export type` definitions', () => {
  3506. const code = `
  3507. export type Vector = { x: number, y: number }
  3508. type Handler = (msg: string) -> boolean
  3509. `;
  3510. const result = extractFromSource('types.luau', code);
  3511. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3512. const vector = aliases.find((a) => a.name === 'Vector');
  3513. expect(vector).toBeDefined();
  3514. expect(vector?.isExported).toBe(true);
  3515. const handler = aliases.find((a) => a.name === 'Handler');
  3516. expect(handler).toBeDefined();
  3517. expect(handler?.isExported).toBe(false);
  3518. });
  3519. });
  3520. describe('Typed functions and methods', () => {
  3521. it('should capture typed signatures and split methods by receiver', () => {
  3522. const code = `
  3523. function configure(opts: { debug: boolean }): boolean
  3524. return opts.debug
  3525. end
  3526. function Client:fetch(path: string): Response
  3527. return path
  3528. end
  3529. `;
  3530. const result = extractFromSource('client.luau', code);
  3531. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3532. expect(configure?.language).toBe('luau');
  3533. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3534. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3535. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3536. });
  3537. });
  3538. describe('Imports and variables', () => {
  3539. it('should extract string and Roblox instance-path require imports', () => {
  3540. const code = `
  3541. local http = require("http")
  3542. local Signal = require(script.Parent.Signal)
  3543. local count = 0
  3544. `;
  3545. const result = extractFromSource('mod.luau', code);
  3546. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3547. expect(imports).toContain('http'); // string require
  3548. expect(imports).toContain('Signal'); // Roblox instance-path require
  3549. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3550. expect(vars).toContain('count');
  3551. });
  3552. });
  3553. });
  3554. // =============================================================================
  3555. // Objective-C
  3556. // =============================================================================
  3557. describe('Objective-C Extraction', () => {
  3558. const sample = `
  3559. #import <Foundation/Foundation.h>
  3560. #import "MyClass.h"
  3561. @interface MyClass : NSObject <NSCopying>
  3562. @property (nonatomic, copy) NSString *name;
  3563. - (void)greet;
  3564. - (void)doThing:(id)x with:(id)y;
  3565. + (instancetype)shared;
  3566. @end
  3567. @implementation MyClass
  3568. - (void)greet {
  3569. NSLog(@"Hello");
  3570. [self doWork];
  3571. }
  3572. - (void)doThing:(id)x with:(id)y {
  3573. [self notify:x];
  3574. }
  3575. + (instancetype)shared {
  3576. return [[MyClass alloc] init];
  3577. }
  3578. @end
  3579. void helperFunction(int count) {
  3580. MyClass *obj = [MyClass shared];
  3581. [obj greet];
  3582. }
  3583. `;
  3584. it('should extract classes, methods, functions, and imports', () => {
  3585. const result = extractFromSource('App.m', sample);
  3586. const classes = result.nodes.filter((n) => n.kind === 'class');
  3587. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  3588. const methods = result.nodes.filter((n) => n.kind === 'method');
  3589. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  3590. const shared = methods.find((m) => m.name === 'shared');
  3591. expect(shared?.isStatic).toBe(true);
  3592. const properties = result.nodes.filter((n) => n.kind === 'property');
  3593. expect(properties.some((p) => p.name === 'name')).toBe(true);
  3594. const functions = result.nodes.filter((n) => n.kind === 'function');
  3595. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  3596. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3597. expect(imports).toContain('Foundation/Foundation.h');
  3598. expect(imports).toContain('MyClass.h');
  3599. });
  3600. it('should record inheritance and protocol conformance', () => {
  3601. const result = extractFromSource('App.m', sample);
  3602. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3603. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  3604. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  3605. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  3606. });
  3607. it('should record message sends and C calls', () => {
  3608. const result = extractFromSource('App.m', sample);
  3609. const calls = result.unresolvedReferences
  3610. .filter((r) => r.referenceKind === 'calls')
  3611. .map((r) => r.referenceName);
  3612. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  3613. });
  3614. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  3615. // Regression for the gap discovered post-#165: message_expression's
  3616. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  3617. // so calls never resolved to multi-part method definitions like
  3618. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  3619. // must match the method-definition name with full keywords + trailing colons.
  3620. const code = `
  3621. @implementation Caller
  3622. - (void)demo {
  3623. NSMutableDictionary *d = [NSMutableDictionary new];
  3624. [d setObject:@"v" forKey:@"k"];
  3625. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  3626. [self touchesBegan:nil withEvent:nil];
  3627. }
  3628. @end
  3629. `;
  3630. const result = extractFromSource('Caller.m', code);
  3631. const calls = result.unresolvedReferences
  3632. .filter((r) => r.referenceKind === 'calls')
  3633. .map((r) => r.referenceName);
  3634. expect(calls).toEqual(
  3635. expect.arrayContaining([
  3636. 'd.setObject:forKey:',
  3637. 'd.setObject:forKey:withRetry:',
  3638. 'touchesBegan:withEvent:',
  3639. ])
  3640. );
  3641. });
  3642. it('should not classify pure C headers with @end in comments as objc', () => {
  3643. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  3644. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  3645. });
  3646. it('should extract protocol declarations', () => {
  3647. const code = `
  3648. @protocol DataSource <NSObject>
  3649. - (NSInteger)numberOfItems;
  3650. @end
  3651. `;
  3652. const result = extractFromSource('DataSource.h', code);
  3653. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  3654. expect(protocol).toBeDefined();
  3655. });
  3656. it('should report Objective-C as supported', () => {
  3657. expect(isLanguageSupported('objc')).toBe(true);
  3658. expect(getSupportedLanguages()).toContain('objc');
  3659. });
  3660. });