extraction.test.ts 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894
  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, isSourceFile } 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('extracts type references from in-body local variable annotations', () => {
  200. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  201. // still depends on Foo. The body walker used to capture calls but never type
  202. // annotations, so impact / `affected` missed the dependency. Must cover
  203. // function, class-method, and object-literal-method bodies — and must NOT
  204. // turn the locals themselves into graph nodes (that would explode the graph).
  205. const code = `
  206. import { Foo } from './types';
  207. export function build(): void {
  208. const items: Foo[] = [];
  209. void items;
  210. }
  211. export class K {
  212. run(): void {
  213. const a: Foo = { x: 1 };
  214. void a;
  215. }
  216. }
  217. export const handler = {
  218. handle(): void {
  219. const b: Foo = { x: 1 };
  220. void b;
  221. },
  222. };
  223. `;
  224. const result = extractFromSource('inbody.ts', code);
  225. const fooRefs = result.unresolvedReferences.filter(
  226. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  227. );
  228. // One per body scope: build(), K.run(), handler.handle().
  229. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  230. // Each reference is attributed to its enclosing function/method node — never
  231. // to a local-variable node, because locals are intentionally not extracted.
  232. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  233. for (const ref of fooRefs) {
  234. const owner = byId.get(ref.fromNodeId);
  235. expect(owner).toBeDefined();
  236. expect(['function', 'method']).toContain(owner!.kind);
  237. }
  238. // The locals (items/a/b) must not leak in as symbols.
  239. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  240. });
  241. it('should track function calls', () => {
  242. const code = `
  243. function main() {
  244. const result = processData();
  245. console.log(result);
  246. }
  247. `;
  248. const result = extractFromSource('main.ts', code);
  249. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  250. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  251. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  252. });
  253. });
  254. describe('Arrow Function Export Extraction', () => {
  255. it('should extract exported arrow functions assigned to const', () => {
  256. const code = `
  257. export const useAuth = (): AuthContextValue => {
  258. return useContext(AuthContext);
  259. };
  260. `;
  261. const result = extractFromSource('hooks.ts', code);
  262. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  263. expect(funcNode).toBeDefined();
  264. expect(funcNode).toMatchObject({
  265. kind: 'function',
  266. name: 'useAuth',
  267. isExported: true,
  268. });
  269. });
  270. it('should extract exported function expressions assigned to const', () => {
  271. const code = `
  272. export const processData = function(input: string): string {
  273. return input.trim();
  274. };
  275. `;
  276. const result = extractFromSource('utils.ts', code);
  277. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  278. expect(funcNode).toBeDefined();
  279. expect(funcNode).toMatchObject({
  280. kind: 'function',
  281. name: 'processData',
  282. isExported: true,
  283. });
  284. });
  285. it('should not extract non-exported arrow functions as exported', () => {
  286. const code = `
  287. const internalHelper = () => {
  288. return 42;
  289. };
  290. `;
  291. const result = extractFromSource('internal.ts', code);
  292. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  293. expect(helperNode).toBeDefined();
  294. expect(helperNode?.isExported).toBeFalsy();
  295. });
  296. it('should still skip truly anonymous arrow functions', () => {
  297. const code = `
  298. const items = [1, 2, 3].map((x) => x * 2);
  299. `;
  300. const result = extractFromSource('anon.ts', code);
  301. // The inline arrow function passed to .map() has no variable_declarator parent
  302. // and should remain anonymous (skipped)
  303. const anonFunctions = result.nodes.filter(
  304. (n) => n.kind === 'function' && n.name === '<anonymous>'
  305. );
  306. expect(anonFunctions).toHaveLength(0);
  307. });
  308. it('should extract multiple exported arrow functions from the same file', () => {
  309. const code = `
  310. export const add = (a: number, b: number): number => a + b;
  311. export const subtract = (a: number, b: number): number => a - b;
  312. const internal = () => 'not exported';
  313. `;
  314. const result = extractFromSource('math.ts', code);
  315. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  316. expect(exported).toHaveLength(2);
  317. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  318. const internalNode = result.nodes.find((n) => n.name === 'internal');
  319. expect(internalNode).toBeDefined();
  320. expect(internalNode?.isExported).toBeFalsy();
  321. });
  322. it('should extract arrow functions in JavaScript files', () => {
  323. const code = `
  324. export const fetchData = async () => {
  325. const response = await fetch('/api/data');
  326. return response.json();
  327. };
  328. `;
  329. const result = extractFromSource('api.js', code);
  330. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  331. expect(funcNode).toBeDefined();
  332. expect(funcNode).toMatchObject({
  333. kind: 'function',
  334. name: 'fetchData',
  335. isExported: true,
  336. });
  337. });
  338. });
  339. describe('Type Alias Extraction', () => {
  340. it('should extract exported type aliases in TypeScript', () => {
  341. const code = `
  342. export type AuthContextValue = {
  343. user: User | null;
  344. login: () => void;
  345. logout: () => void;
  346. };
  347. `;
  348. const result = extractFromSource('types.ts', code);
  349. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  350. expect(typeNode).toMatchObject({
  351. kind: 'type_alias',
  352. name: 'AuthContextValue',
  353. isExported: true,
  354. });
  355. });
  356. it('should extract non-exported type aliases', () => {
  357. const code = `
  358. type InternalState = {
  359. loading: boolean;
  360. error: string | null;
  361. };
  362. `;
  363. const result = extractFromSource('internal.ts', code);
  364. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  365. expect(typeNode).toMatchObject({
  366. kind: 'type_alias',
  367. name: 'InternalState',
  368. isExported: false,
  369. });
  370. });
  371. it('should extract multiple type aliases from the same file', () => {
  372. const code = `
  373. export type UnitSystem = 'metric' | 'imperial';
  374. export type DateFormat = 'ISO' | 'US' | 'EU';
  375. type Internal = string;
  376. `;
  377. const result = extractFromSource('config.ts', code);
  378. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  379. expect(typeAliases).toHaveLength(3);
  380. const exported = typeAliases.filter((n) => n.isExported);
  381. expect(exported).toHaveLength(2);
  382. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  383. });
  384. });
  385. describe('Exported Variable Extraction', () => {
  386. it('should extract exported const with call expression (Zustand store)', () => {
  387. const code = `
  388. export const useUIStore = create<UIState>((set) => ({
  389. isOpen: false,
  390. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  391. }));
  392. `;
  393. const result = extractFromSource('store.ts', code);
  394. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  395. expect(varNode).toBeDefined();
  396. expect(varNode?.isExported).toBe(true);
  397. });
  398. it('should extract exported const with object literal', () => {
  399. const code = `
  400. export const config = {
  401. apiUrl: 'https://api.example.com',
  402. timeout: 5000,
  403. };
  404. `;
  405. const result = extractFromSource('config.ts', code);
  406. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  407. expect(varNode).toBeDefined();
  408. expect(varNode?.isExported).toBe(true);
  409. });
  410. it('should extract exported const with array literal', () => {
  411. const code = `
  412. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  413. `;
  414. const result = extractFromSource('constants.ts', code);
  415. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  416. expect(varNode).toBeDefined();
  417. expect(varNode?.isExported).toBe(true);
  418. });
  419. it('should extract exported const with primitive value', () => {
  420. const code = `
  421. export const MAX_RETRIES = 3;
  422. export const API_VERSION = "v2";
  423. `;
  424. const result = extractFromSource('constants.ts', code);
  425. const variables = result.nodes.filter((n) => n.kind === 'constant');
  426. expect(variables).toHaveLength(2);
  427. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  428. });
  429. it('should NOT duplicate arrow functions as both function and variable', () => {
  430. const code = `
  431. export const useAuth = () => {
  432. return useContext(AuthContext);
  433. };
  434. `;
  435. const result = extractFromSource('hooks.ts', code);
  436. // Should be extracted as function (from arrow function handler), NOT as variable
  437. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  438. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  439. expect(funcNodes).toHaveLength(1);
  440. expect(varNodes).toHaveLength(0);
  441. });
  442. it('should extract non-exported const as non-exported variable', () => {
  443. const code = `
  444. const internalConfig = {
  445. debug: true,
  446. };
  447. `;
  448. const result = extractFromSource('internal.ts', code);
  449. // Non-exported const at file level should be extracted as a constant (not exported)
  450. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  451. expect(varNodes).toHaveLength(1);
  452. expect(varNodes[0]?.isExported).toBeFalsy();
  453. });
  454. it('should extract Zod schema exports', () => {
  455. const code = `
  456. export const userSchema = z.object({
  457. id: z.string(),
  458. name: z.string(),
  459. email: z.string().email(),
  460. });
  461. `;
  462. const result = extractFromSource('schemas.ts', code);
  463. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  464. expect(varNode).toBeDefined();
  465. expect(varNode?.isExported).toBe(true);
  466. });
  467. it('should extract XState machine exports', () => {
  468. const code = `
  469. export const authMachine = createMachine({
  470. id: "auth",
  471. initial: "idle",
  472. states: {
  473. idle: {},
  474. authenticated: {},
  475. },
  476. });
  477. `;
  478. const result = extractFromSource('machine.ts', code);
  479. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  480. expect(varNode).toBeDefined();
  481. expect(varNode?.isExported).toBe(true);
  482. });
  483. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  484. const code = `
  485. import { getTokenMp } from './api/upload';
  486. const token = getTokenMp();
  487. `;
  488. const result = extractFromSource('app.ts', code);
  489. const call = result.unresolvedReferences.find(
  490. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  491. );
  492. expect(call).toBeDefined();
  493. });
  494. });
  495. describe('File Node Extraction', () => {
  496. it('should create a file-kind node for each parsed file', () => {
  497. const code = `
  498. export function greet(name: string): string {
  499. return "Hello " + name;
  500. }
  501. `;
  502. const result = extractFromSource('greeter.ts', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. expect(fileNode?.name).toBe('greeter.ts');
  506. expect(fileNode?.filePath).toBe('greeter.ts');
  507. expect(fileNode?.language).toBe('typescript');
  508. expect(fileNode?.startLine).toBe(1);
  509. });
  510. it('should create file nodes for Python files', () => {
  511. const code = `
  512. def main():
  513. pass
  514. `;
  515. const result = extractFromSource('main.py', code);
  516. const fileNode = result.nodes.find((n) => n.kind === 'file');
  517. expect(fileNode).toBeDefined();
  518. expect(fileNode?.name).toBe('main.py');
  519. expect(fileNode?.language).toBe('python');
  520. });
  521. it('should create containment edges from file node to top-level declarations', () => {
  522. const code = `
  523. export function foo() {}
  524. export function bar() {}
  525. `;
  526. const result = extractFromSource('fns.ts', code);
  527. const fileNode = result.nodes.find((n) => n.kind === 'file');
  528. expect(fileNode).toBeDefined();
  529. // There should be contains edges from the file node to each function
  530. const containsEdges = result.edges.filter(
  531. (e) => e.source === fileNode?.id && e.kind === 'contains'
  532. );
  533. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  534. });
  535. });
  536. describe('Python Extraction', () => {
  537. it('should extract function definitions', () => {
  538. const code = `
  539. def calculate_total(items: list, tax_rate: float) -> float:
  540. """Calculate total with tax."""
  541. subtotal = sum(item.price for item in items)
  542. return subtotal * (1 + tax_rate)
  543. `;
  544. const result = extractFromSource('calc.py', code);
  545. const fileNode = result.nodes.find((n) => n.kind === 'file');
  546. expect(fileNode).toBeDefined();
  547. const funcNode = result.nodes.find((n) => n.kind === 'function');
  548. expect(funcNode).toMatchObject({
  549. kind: 'function',
  550. name: 'calculate_total',
  551. language: 'python',
  552. });
  553. });
  554. it('should extract class definitions', () => {
  555. const code = `
  556. class UserService:
  557. """Service for managing users."""
  558. def __init__(self, db):
  559. self.db = db
  560. def get_user(self, user_id: str) -> User:
  561. return self.db.find_user(user_id)
  562. `;
  563. const result = extractFromSource('service.py', code);
  564. const classNode = result.nodes.find((n) => n.kind === 'class');
  565. expect(classNode).toBeDefined();
  566. expect(classNode?.name).toBe('UserService');
  567. });
  568. });
  569. describe('Go Extraction', () => {
  570. it('should extract function declarations', () => {
  571. const code = `
  572. package main
  573. func ProcessOrder(order Order) (Receipt, error) {
  574. // Process the order
  575. return Receipt{}, nil
  576. }
  577. `;
  578. const result = extractFromSource('main.go', code);
  579. const funcNode = result.nodes.find((n) => n.kind === 'function');
  580. expect(funcNode).toBeDefined();
  581. expect(funcNode?.name).toBe('ProcessOrder');
  582. });
  583. it('should extract method declarations', () => {
  584. const code = `
  585. package main
  586. type Service struct {
  587. db *Database
  588. }
  589. func (s *Service) GetUser(id string) (*User, error) {
  590. return s.db.FindUser(id)
  591. }
  592. `;
  593. const result = extractFromSource('service.go', code);
  594. const methodNode = result.nodes.find((n) => n.kind === 'method');
  595. expect(methodNode).toBeDefined();
  596. expect(methodNode?.name).toBe('GetUser');
  597. });
  598. });
  599. describe('Rust Extraction', () => {
  600. it('should extract function declarations', () => {
  601. const code = `
  602. pub fn process_data(input: &str) -> Result<Output, Error> {
  603. // Process data
  604. Ok(Output::new())
  605. }
  606. `;
  607. const result = extractFromSource('lib.rs', code);
  608. const funcNode = result.nodes.find((n) => n.kind === 'function');
  609. expect(funcNode).toBeDefined();
  610. expect(funcNode?.name).toBe('process_data');
  611. expect(funcNode?.visibility).toBe('public');
  612. });
  613. it('should extract struct declarations', () => {
  614. const code = `
  615. pub struct User {
  616. pub id: String,
  617. pub name: String,
  618. email: String,
  619. }
  620. `;
  621. const result = extractFromSource('models.rs', code);
  622. const structNode = result.nodes.find((n) => n.kind === 'struct');
  623. expect(structNode).toBeDefined();
  624. expect(structNode?.name).toBe('User');
  625. });
  626. it('should extract trait declarations', () => {
  627. const code = `
  628. pub trait Repository {
  629. fn find(&self, id: &str) -> Option<Entity>;
  630. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  631. }
  632. `;
  633. const result = extractFromSource('traits.rs', code);
  634. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  635. expect(traitNode).toBeDefined();
  636. expect(traitNode?.name).toBe('Repository');
  637. });
  638. it('should extract impl Trait for Type as implements edges', () => {
  639. const code = `
  640. pub struct MyCache {}
  641. pub trait Cache {
  642. fn get(&self, key: &str) -> Option<String>;
  643. }
  644. impl Cache for MyCache {
  645. fn get(&self, key: &str) -> Option<String> {
  646. None
  647. }
  648. }
  649. `;
  650. const result = extractFromSource('cache.rs', code);
  651. // Should have an unresolved reference for implements
  652. const implRef = result.unresolvedReferences.find(
  653. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  654. );
  655. expect(implRef).toBeDefined();
  656. // The struct MyCache should be the source
  657. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  658. expect(myCacheNode).toBeDefined();
  659. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  660. });
  661. it('should extract trait supertraits as extends references', () => {
  662. const code = `
  663. pub trait Display {}
  664. pub trait Error: Display {
  665. fn description(&self) -> &str;
  666. }
  667. `;
  668. const result = extractFromSource('error.rs', code);
  669. const extendsRef = result.unresolvedReferences.find(
  670. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  671. );
  672. expect(extendsRef).toBeDefined();
  673. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  674. expect(errorTrait).toBeDefined();
  675. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  676. });
  677. it('should not create implements edges for plain impl blocks', () => {
  678. const code = `
  679. pub struct Counter {
  680. count: u32,
  681. }
  682. impl Counter {
  683. pub fn new() -> Counter {
  684. Counter { count: 0 }
  685. }
  686. pub fn increment(&mut self) {
  687. self.count += 1;
  688. }
  689. }
  690. `;
  691. const result = extractFromSource('counter.rs', code);
  692. // Should have no implements references (no trait involved)
  693. const implRefs = result.unresolvedReferences.filter(
  694. (r) => r.referenceKind === 'implements'
  695. );
  696. expect(implRefs).toHaveLength(0);
  697. });
  698. });
  699. describe('Java Extraction', () => {
  700. it('should extract class declarations', () => {
  701. const code = `
  702. public class UserService {
  703. private final UserRepository repository;
  704. public UserService(UserRepository repository) {
  705. this.repository = repository;
  706. }
  707. public User getUser(String id) {
  708. return repository.findById(id);
  709. }
  710. }
  711. `;
  712. const result = extractFromSource('UserService.java', code);
  713. const classNode = result.nodes.find((n) => n.kind === 'class');
  714. expect(classNode).toBeDefined();
  715. expect(classNode?.name).toBe('UserService');
  716. expect(classNode?.visibility).toBe('public');
  717. });
  718. it('should extract method declarations', () => {
  719. const code = `
  720. public class Calculator {
  721. public static int add(int a, int b) {
  722. return a + b;
  723. }
  724. }
  725. `;
  726. const result = extractFromSource('Calculator.java', code);
  727. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  728. expect(methodNode).toBeDefined();
  729. expect(methodNode?.isStatic).toBe(true);
  730. });
  731. it('wraps top-level declarations in a namespace from package_declaration', () => {
  732. const code = `
  733. package com.example.foo;
  734. public class Bar {
  735. public String greet() { return "hi"; }
  736. }
  737. `;
  738. const result = extractFromSource('Bar.java', code);
  739. const ns = result.nodes.find((n) => n.kind === 'namespace');
  740. expect(ns?.name).toBe('com.example.foo');
  741. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  742. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  743. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  744. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  745. });
  746. it('does not wrap when no package is declared', () => {
  747. const code = `
  748. public class Bar {
  749. public String greet() { return "hi"; }
  750. }
  751. `;
  752. const result = extractFromSource('Bar.java', code);
  753. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  754. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  755. expect(cls?.qualifiedName).toBe('Bar');
  756. });
  757. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  758. // The pattern that breaks the trace through `strategy.foo()` in
  759. // libraries like guava's Splitter: the lambda-returned anonymous
  760. // class overrides abstract methods on the base, but without
  761. // extracting those overrides the interface→impl synthesizer has
  762. // nothing to bridge.
  763. const code = `
  764. package com.example;
  765. abstract class Base {
  766. abstract int compute(int x);
  767. }
  768. public class Factory {
  769. public Base make() {
  770. return new Base() {
  771. @Override
  772. int compute(int x) { return x + 1; }
  773. };
  774. }
  775. }
  776. `;
  777. const result = extractFromSource('Factory.java', code);
  778. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  779. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  780. const compute = result.nodes.find(
  781. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  782. );
  783. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  784. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  785. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  786. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  787. const extendsRef = result.unresolvedReferences.find(
  788. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  789. );
  790. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  791. // The enclosing `make` method still emits an instantiates edge to Base —
  792. // anon extraction must not swallow that signal.
  793. const instantiatesRef = result.unresolvedReferences.find(
  794. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  795. );
  796. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  797. });
  798. it('extracts anonymous-class overrides inside a lambda body', () => {
  799. // The exact guava pattern: a lambda is passed to a constructor, and the
  800. // lambda body returns `new T() { @Override ... }`. The anon class must
  801. // still surface even though it sits inside a lambda_expression node.
  802. const code = `
  803. package com.example;
  804. interface Strategy {
  805. java.util.Iterator<String> iterator(String s);
  806. }
  807. abstract class BaseIter implements java.util.Iterator<String> {
  808. abstract int separatorStart(int start);
  809. }
  810. public class Splitter {
  811. private final Strategy strategy;
  812. public Splitter(Strategy s) { this.strategy = s; }
  813. public static Splitter on(char c) {
  814. return new Splitter((seq) ->
  815. new BaseIter() {
  816. @Override
  817. int separatorStart(int start) { return start + 1; }
  818. @Override public boolean hasNext() { return false; }
  819. @Override public String next() { return null; }
  820. });
  821. }
  822. }
  823. `;
  824. const result = extractFromSource('Splitter.java', code);
  825. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  826. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  827. const sepStart = result.nodes.find(
  828. (n) =>
  829. n.kind === 'method' &&
  830. n.name === 'separatorStart' &&
  831. n.qualifiedName.includes('$anon@')
  832. );
  833. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  834. });
  835. });
  836. describe('C# Extraction', () => {
  837. it('should extract class declarations', () => {
  838. const code = `
  839. public class OrderService
  840. {
  841. private readonly IOrderRepository _repository;
  842. public OrderService(IOrderRepository repository)
  843. {
  844. _repository = repository;
  845. }
  846. public async Task<Order> GetOrderAsync(string id)
  847. {
  848. return await _repository.FindByIdAsync(id);
  849. }
  850. }
  851. `;
  852. const result = extractFromSource('OrderService.cs', code);
  853. const classNode = result.nodes.find((n) => n.kind === 'class');
  854. expect(classNode).toBeDefined();
  855. expect(classNode?.name).toBe('OrderService');
  856. expect(classNode?.visibility).toBe('public');
  857. });
  858. });
  859. describe('PHP Extraction', () => {
  860. it('should extract class declarations', () => {
  861. const code = `<?php
  862. class UserController
  863. {
  864. private UserService $userService;
  865. public function __construct(UserService $userService)
  866. {
  867. $this->userService = $userService;
  868. }
  869. public function show(string $id): User
  870. {
  871. return $this->userService->find($id);
  872. }
  873. }
  874. `;
  875. const result = extractFromSource('UserController.php', code);
  876. const classNode = result.nodes.find((n) => n.kind === 'class');
  877. expect(classNode).toBeDefined();
  878. expect(classNode?.name).toBe('UserController');
  879. });
  880. it('should extract class inheritance (extends) and interface implementation', () => {
  881. const code = `<?php
  882. class ChildController extends BaseController implements Serializable, JsonSerializable
  883. {
  884. public function serialize(): string
  885. {
  886. return json_encode($this);
  887. }
  888. }
  889. `;
  890. const result = extractFromSource('ChildController.php', code);
  891. const classNode = result.nodes.find((n) => n.kind === 'class');
  892. expect(classNode).toBeDefined();
  893. expect(classNode?.name).toBe('ChildController');
  894. const extendsRef = result.unresolvedReferences.find(
  895. (r) => r.referenceKind === 'extends'
  896. );
  897. expect(extendsRef).toBeDefined();
  898. expect(extendsRef?.referenceName).toBe('BaseController');
  899. const implementsRefs = result.unresolvedReferences.filter(
  900. (r) => r.referenceKind === 'implements'
  901. );
  902. expect(implementsRefs.length).toBe(2);
  903. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  904. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  905. });
  906. });
  907. describe('Swift Extraction', () => {
  908. it('should extract class declarations', () => {
  909. const code = `
  910. public class NetworkManager {
  911. private let session: URLSession
  912. public init(session: URLSession = .shared) {
  913. self.session = session
  914. }
  915. public func fetchData(from url: URL) async throws -> Data {
  916. let (data, _) = try await session.data(from: url)
  917. return data
  918. }
  919. }
  920. `;
  921. const result = extractFromSource('NetworkManager.swift', code);
  922. const classNode = result.nodes.find((n) => n.kind === 'class');
  923. expect(classNode).toBeDefined();
  924. expect(classNode?.name).toBe('NetworkManager');
  925. });
  926. it('should extract function declarations', () => {
  927. const code = `
  928. func calculateSum(_ numbers: [Int]) -> Int {
  929. return numbers.reduce(0, +)
  930. }
  931. public func formatCurrency(amount: Double) -> String {
  932. return String(format: "$%.2f", amount)
  933. }
  934. `;
  935. const result = extractFromSource('utils.swift', code);
  936. const functions = result.nodes.filter((n) => n.kind === 'function');
  937. expect(functions.length).toBeGreaterThanOrEqual(1);
  938. });
  939. it('should extract struct declarations', () => {
  940. const code = `
  941. public struct User {
  942. let id: UUID
  943. var name: String
  944. var email: String
  945. func displayName() -> String {
  946. return name
  947. }
  948. }
  949. `;
  950. const result = extractFromSource('User.swift', code);
  951. const structNode = result.nodes.find((n) => n.kind === 'struct');
  952. expect(structNode).toBeDefined();
  953. expect(structNode?.name).toBe('User');
  954. });
  955. it('should extract protocol declarations', () => {
  956. const code = `
  957. public protocol Repository {
  958. associatedtype Entity
  959. func find(id: String) async throws -> Entity?
  960. func save(_ entity: Entity) async throws
  961. }
  962. `;
  963. const result = extractFromSource('Repository.swift', code);
  964. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  965. expect(protocolNode).toBeDefined();
  966. expect(protocolNode?.name).toBe('Repository');
  967. });
  968. it('should extract class inheritance and protocol conformance', () => {
  969. const code = `
  970. class DataRequest: Request {
  971. func validate() {}
  972. }
  973. class UploadRequest: DataRequest, Sendable {
  974. func upload() {}
  975. }
  976. enum AFError: Error {
  977. case invalidURL
  978. }
  979. struct HTTPMethod: RawRepresentable {
  980. let rawValue: String
  981. }
  982. protocol UploadConvertible: URLRequestConvertible {
  983. func asURLRequest() throws -> URLRequest
  984. }
  985. `;
  986. const result = extractFromSource('Inheritance.swift', code);
  987. const extendsRefs = result.unresolvedReferences.filter(
  988. (r) => r.referenceKind === 'extends'
  989. );
  990. // DataRequest extends Request
  991. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  992. // UploadRequest extends DataRequest and Sendable
  993. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  994. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  995. // AFError extends Error
  996. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  997. // HTTPMethod extends RawRepresentable
  998. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  999. // UploadConvertible extends URLRequestConvertible
  1000. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1001. });
  1002. });
  1003. describe('Kotlin Extraction', () => {
  1004. it('should extract class declarations', () => {
  1005. const code = `
  1006. class UserRepository(private val database: Database) {
  1007. fun findById(id: String): User? {
  1008. return database.query("SELECT * FROM users WHERE id = ?", id)
  1009. }
  1010. suspend fun save(user: User) {
  1011. database.insert(user)
  1012. }
  1013. }
  1014. `;
  1015. const result = extractFromSource('UserRepository.kt', code);
  1016. const classNode = result.nodes.find((n) => n.kind === 'class');
  1017. expect(classNode).toBeDefined();
  1018. expect(classNode?.name).toBe('UserRepository');
  1019. });
  1020. it('should extract function declarations', () => {
  1021. const code = `
  1022. fun calculateTotal(items: List<Item>): Double {
  1023. return items.sumOf { it.price }
  1024. }
  1025. suspend fun fetchUserData(userId: String): User {
  1026. return api.getUser(userId)
  1027. }
  1028. `;
  1029. const result = extractFromSource('utils.kt', code);
  1030. const functions = result.nodes.filter((n) => n.kind === 'function');
  1031. expect(functions.length).toBeGreaterThanOrEqual(1);
  1032. });
  1033. it('should detect suspend functions as async', () => {
  1034. const code = `
  1035. suspend fun loadData(): List<String> {
  1036. delay(1000)
  1037. return listOf("a", "b", "c")
  1038. }
  1039. `;
  1040. const result = extractFromSource('loader.kt', code);
  1041. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1042. expect(funcNode).toBeDefined();
  1043. expect(funcNode?.isAsync).toBe(true);
  1044. });
  1045. it('should extract fun interface declarations', () => {
  1046. const code = `
  1047. fun interface OnObjectRetainedListener {
  1048. fun onObjectRetained()
  1049. }
  1050. `;
  1051. const result = extractFromSource('listener.kt', code);
  1052. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1053. expect(ifaceNode).toBeDefined();
  1054. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1055. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1056. expect(methodNode).toBeDefined();
  1057. expect(methodNode?.name).toBe('onObjectRetained');
  1058. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1059. });
  1060. it('should extract complex fun interface with nested classes', () => {
  1061. const code = `
  1062. fun interface EventListener {
  1063. fun onEvent(event: Event)
  1064. sealed class Event {
  1065. class DumpingHeap : Event()
  1066. }
  1067. }
  1068. `;
  1069. const result = extractFromSource('events.kt', code);
  1070. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1071. expect(ifaceNode).toBeDefined();
  1072. expect(ifaceNode?.name).toBe('EventListener');
  1073. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1074. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1075. expect(eventClass).toBeDefined();
  1076. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1077. expect(dumpingHeap).toBeDefined();
  1078. });
  1079. it('should not affect regular function declarations', () => {
  1080. const code = `
  1081. fun interface MyCallback {
  1082. fun invoke(value: Int)
  1083. }
  1084. fun regularFunction(): String {
  1085. return "hello"
  1086. }
  1087. `;
  1088. const result = extractFromSource('mixed.kt', code);
  1089. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1090. expect(ifaceNode).toBeDefined();
  1091. expect(ifaceNode?.name).toBe('MyCallback');
  1092. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1093. expect(funcNode).toBeDefined();
  1094. expect(funcNode?.name).toBe('regularFunction');
  1095. });
  1096. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1097. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1098. // misparse: function_declaration > ERROR("interface Name {") instead of
  1099. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1100. const code = `
  1101. import java.io.IOException
  1102. fun interface Interceptor {
  1103. @Throws(IOException::class)
  1104. fun intercept(chain: Chain): Response
  1105. }
  1106. `;
  1107. const result = extractFromSource('interceptor.kt', code);
  1108. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1109. expect(ifaceNode).toBeDefined();
  1110. expect(ifaceNode?.name).toBe('Interceptor');
  1111. });
  1112. it('should extract methods from interface with nested fun interface', () => {
  1113. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1114. // the parent body as ERROR. Methods inside should still be extracted.
  1115. const code = `
  1116. interface WebSocket {
  1117. fun request(): Request
  1118. fun send(text: String): Boolean
  1119. fun cancel()
  1120. fun interface Factory {
  1121. fun newWebSocket(request: Request): WebSocket
  1122. }
  1123. }
  1124. `;
  1125. const result = extractFromSource('websocket.kt', code);
  1126. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1127. expect(wsIface).toBeDefined();
  1128. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1129. const methodNames = methods.map((m) => m.name);
  1130. expect(methodNames).toContain('request');
  1131. expect(methodNames).toContain('send');
  1132. expect(methodNames).toContain('cancel');
  1133. });
  1134. it('wraps top-level declarations in a namespace from package_header', () => {
  1135. const code = `
  1136. package com.example.foo
  1137. class Bar {
  1138. fun greet(): String = "hi"
  1139. }
  1140. fun util(): Int = 42
  1141. `;
  1142. const result = extractFromSource('Bar.kt', code);
  1143. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1144. expect(ns?.name).toBe('com.example.foo');
  1145. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1146. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1147. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1148. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1149. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1150. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1151. });
  1152. it('handles a single-segment package', () => {
  1153. const code = `
  1154. package foo
  1155. class Bar
  1156. `;
  1157. const result = extractFromSource('Bar.kt', code);
  1158. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1159. expect(cls?.qualifiedName).toBe('foo::Bar');
  1160. });
  1161. it('does not wrap when no package is declared', () => {
  1162. const code = `
  1163. class Bar {
  1164. fun greet() = "hi"
  1165. }
  1166. `;
  1167. const result = extractFromSource('Bar.kt', code);
  1168. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1169. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1170. expect(cls?.qualifiedName).toBe('Bar');
  1171. });
  1172. });
  1173. describe('Dart Extraction', () => {
  1174. it('should extract class declarations', () => {
  1175. const code = `
  1176. class UserService {
  1177. final Database _db;
  1178. Future<User> findById(String id) async {
  1179. return await _db.query(id);
  1180. }
  1181. void _privateMethod() {}
  1182. }
  1183. `;
  1184. const result = extractFromSource('service.dart', code);
  1185. const classNode = result.nodes.find((n) => n.kind === 'class');
  1186. expect(classNode).toBeDefined();
  1187. expect(classNode?.name).toBe('UserService');
  1188. expect(classNode?.visibility).toBe('public');
  1189. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1190. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1191. const findById = methodNodes.find((m) => m.name === 'findById');
  1192. expect(findById).toBeDefined();
  1193. expect(findById?.isAsync).toBe(true);
  1194. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1195. expect(privateMethod).toBeDefined();
  1196. expect(privateMethod?.visibility).toBe('private');
  1197. // Dart models a method body as a SIBLING of the signature, so the method
  1198. // node must be extended to span its body (not just the signature line) —
  1199. // required for body-level analysis (callees, the callback synthesizer).
  1200. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1201. });
  1202. it('should extract top-level function declarations', () => {
  1203. const code = `
  1204. void topLevelFunction(String name) {
  1205. print(name);
  1206. }
  1207. `;
  1208. const result = extractFromSource('utils.dart', code);
  1209. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1210. expect(funcNode).toBeDefined();
  1211. expect(funcNode?.name).toBe('topLevelFunction');
  1212. expect(funcNode?.language).toBe('dart');
  1213. });
  1214. it('should extract enum declarations', () => {
  1215. const code = `
  1216. enum Status { active, inactive, pending }
  1217. `;
  1218. const result = extractFromSource('models.dart', code);
  1219. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1220. expect(enumNode).toBeDefined();
  1221. expect(enumNode?.name).toBe('Status');
  1222. });
  1223. it('should extract mixin declarations', () => {
  1224. const code = `
  1225. mixin LoggerMixin {
  1226. void log(String message) {}
  1227. }
  1228. `;
  1229. const result = extractFromSource('mixins.dart', code);
  1230. const classNode = result.nodes.find((n) => n.kind === 'class');
  1231. expect(classNode).toBeDefined();
  1232. expect(classNode?.name).toBe('LoggerMixin');
  1233. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1234. expect(methodNode).toBeDefined();
  1235. expect(methodNode?.name).toBe('log');
  1236. });
  1237. it('should extract extension declarations', () => {
  1238. const code = `
  1239. extension StringExt on String {
  1240. bool get isBlank => trim().isEmpty;
  1241. }
  1242. `;
  1243. const result = extractFromSource('extensions.dart', code);
  1244. const classNode = result.nodes.find((n) => n.kind === 'class');
  1245. expect(classNode).toBeDefined();
  1246. expect(classNode?.name).toBe('StringExt');
  1247. });
  1248. it('should detect static methods', () => {
  1249. const code = `
  1250. class Utils {
  1251. static void doWork() {}
  1252. }
  1253. `;
  1254. const result = extractFromSource('utils.dart', code);
  1255. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1256. expect(methodNode).toBeDefined();
  1257. expect(methodNode?.name).toBe('doWork');
  1258. expect(methodNode?.isStatic).toBe(true);
  1259. });
  1260. it('should detect async functions', () => {
  1261. const code = `
  1262. Future<String> fetchData() async {
  1263. return await http.get('/data');
  1264. }
  1265. `;
  1266. const result = extractFromSource('api.dart', code);
  1267. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1268. expect(funcNode).toBeDefined();
  1269. expect(funcNode?.name).toBe('fetchData');
  1270. expect(funcNode?.isAsync).toBe(true);
  1271. });
  1272. it('should detect private visibility via underscore convention', () => {
  1273. const code = `
  1274. void _privateHelper() {}
  1275. void publicFunction() {}
  1276. `;
  1277. const result = extractFromSource('helpers.dart', code);
  1278. const functions = result.nodes.filter((n) => n.kind === 'function');
  1279. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1280. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1281. expect(privateFunc?.visibility).toBe('private');
  1282. expect(publicFunc?.visibility).toBe('public');
  1283. });
  1284. });
  1285. describe('Import Extraction', () => {
  1286. describe('TypeScript/JavaScript imports', () => {
  1287. it('should extract default imports', () => {
  1288. const code = `import React from 'react';`;
  1289. const result = extractFromSource('app.tsx', code);
  1290. const importNode = result.nodes.find((n) => n.kind === 'import');
  1291. expect(importNode).toBeDefined();
  1292. expect(importNode?.name).toBe('react');
  1293. expect(importNode?.signature).toBe("import React from 'react';");
  1294. });
  1295. it('should extract named imports', () => {
  1296. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1297. const result = extractFromSource('icons.tsx', code);
  1298. const importNode = result.nodes.find((n) => n.kind === 'import');
  1299. expect(importNode).toBeDefined();
  1300. expect(importNode?.name).toBe('@phosphor-icons/react');
  1301. expect(importNode?.signature).toContain('Bug');
  1302. expect(importNode?.signature).toContain('Database');
  1303. });
  1304. it('should extract namespace imports', () => {
  1305. const code = `import * as Icons from '@phosphor-icons/react';`;
  1306. const result = extractFromSource('icons.tsx', code);
  1307. const importNode = result.nodes.find((n) => n.kind === 'import');
  1308. expect(importNode).toBeDefined();
  1309. expect(importNode?.name).toBe('@phosphor-icons/react');
  1310. expect(importNode?.signature).toContain('* as Icons');
  1311. });
  1312. it('should extract side-effect imports', () => {
  1313. const code = `import './styles.css';`;
  1314. const result = extractFromSource('app.tsx', code);
  1315. const importNode = result.nodes.find((n) => n.kind === 'import');
  1316. expect(importNode).toBeDefined();
  1317. expect(importNode?.name).toBe('./styles.css');
  1318. });
  1319. it('should extract mixed imports (default + named)', () => {
  1320. const code = `import React, { useState, useEffect } from 'react';`;
  1321. const result = extractFromSource('app.tsx', code);
  1322. const importNode = result.nodes.find((n) => n.kind === 'import');
  1323. expect(importNode).toBeDefined();
  1324. expect(importNode?.name).toBe('react');
  1325. expect(importNode?.signature).toContain('React');
  1326. expect(importNode?.signature).toContain('useState');
  1327. expect(importNode?.signature).toContain('useEffect');
  1328. });
  1329. it('should extract multiple import statements', () => {
  1330. const code = `
  1331. import React from 'react';
  1332. import { Button } from './components';
  1333. import './styles.css';
  1334. `;
  1335. const result = extractFromSource('app.tsx', code);
  1336. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1337. expect(importNodes.length).toBe(3);
  1338. const names = importNodes.map((n) => n.name);
  1339. expect(names).toContain('react');
  1340. expect(names).toContain('./components');
  1341. expect(names).toContain('./styles.css');
  1342. });
  1343. it('should extract type imports', () => {
  1344. const code = `import type { FC, ReactNode } from 'react';`;
  1345. const result = extractFromSource('types.ts', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('react');
  1349. expect(importNode?.signature).toContain('type');
  1350. expect(importNode?.signature).toContain('FC');
  1351. });
  1352. it('should extract aliased named imports', () => {
  1353. const code = `import { useState as useStateAlias } from 'react';`;
  1354. const result = extractFromSource('hooks.ts', code);
  1355. const importNode = result.nodes.find((n) => n.kind === 'import');
  1356. expect(importNode).toBeDefined();
  1357. expect(importNode?.name).toBe('react');
  1358. expect(importNode?.signature).toContain('useState');
  1359. expect(importNode?.signature).toContain('useStateAlias');
  1360. });
  1361. it('should extract relative path imports', () => {
  1362. const code = `import { helper } from '../utils/helper';`;
  1363. const result = extractFromSource('components/Button.tsx', code);
  1364. const importNode = result.nodes.find((n) => n.kind === 'import');
  1365. expect(importNode).toBeDefined();
  1366. expect(importNode?.name).toBe('../utils/helper');
  1367. expect(importNode?.signature).toContain('helper');
  1368. });
  1369. });
  1370. describe('Python imports', () => {
  1371. it('should extract simple import statement', () => {
  1372. const code = `import json`;
  1373. const result = extractFromSource('utils.py', code);
  1374. const importNode = result.nodes.find((n) => n.kind === 'import');
  1375. expect(importNode).toBeDefined();
  1376. expect(importNode?.name).toBe('json');
  1377. });
  1378. it('should extract from import statement', () => {
  1379. const code = `from os import path`;
  1380. const result = extractFromSource('utils.py', code);
  1381. const importNode = result.nodes.find((n) => n.kind === 'import');
  1382. expect(importNode).toBeDefined();
  1383. expect(importNode?.name).toBe('os');
  1384. expect(importNode?.signature).toContain('path');
  1385. });
  1386. it('should extract multiple imports from same module', () => {
  1387. const code = `from typing import List, Dict, Optional`;
  1388. const result = extractFromSource('types.py', code);
  1389. const importNode = result.nodes.find((n) => n.kind === 'import');
  1390. expect(importNode).toBeDefined();
  1391. expect(importNode?.name).toBe('typing');
  1392. expect(importNode?.signature).toContain('List');
  1393. expect(importNode?.signature).toContain('Dict');
  1394. });
  1395. it('should extract multiple import statements', () => {
  1396. const code = `
  1397. import os
  1398. import sys
  1399. `;
  1400. const result = extractFromSource('main.py', code);
  1401. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1402. expect(importNodes.length).toBe(2);
  1403. const names = importNodes.map((n) => n.name);
  1404. expect(names).toContain('os');
  1405. expect(names).toContain('sys');
  1406. });
  1407. it('should extract aliased import', () => {
  1408. const code = `import numpy as np`;
  1409. const result = extractFromSource('data.py', code);
  1410. const importNode = result.nodes.find((n) => n.kind === 'import');
  1411. expect(importNode).toBeDefined();
  1412. expect(importNode?.name).toBe('numpy');
  1413. expect(importNode?.signature).toContain('as np');
  1414. });
  1415. it('should extract relative import', () => {
  1416. const code = `from .utils import helper`;
  1417. const result = extractFromSource('module.py', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('.utils');
  1421. expect(importNode?.signature).toContain('helper');
  1422. });
  1423. it('should extract wildcard import', () => {
  1424. const code = `from typing import *`;
  1425. const result = extractFromSource('types.py', code);
  1426. const importNode = result.nodes.find((n) => n.kind === 'import');
  1427. expect(importNode).toBeDefined();
  1428. expect(importNode?.name).toBe('typing');
  1429. expect(importNode?.signature).toContain('*');
  1430. });
  1431. });
  1432. describe('Rust imports', () => {
  1433. it('should extract simple use declaration', () => {
  1434. const code = `use std::io;`;
  1435. const result = extractFromSource('main.rs', code);
  1436. const importNode = result.nodes.find((n) => n.kind === 'import');
  1437. expect(importNode).toBeDefined();
  1438. expect(importNode?.name).toBe('std');
  1439. expect(importNode?.signature).toBe('use std::io;');
  1440. });
  1441. it('should extract scoped use list', () => {
  1442. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1443. const result = extractFromSource('main.rs', code);
  1444. const importNode = result.nodes.find((n) => n.kind === 'import');
  1445. expect(importNode).toBeDefined();
  1446. expect(importNode?.name).toBe('std');
  1447. expect(importNode?.signature).toContain('ffi::OsStr');
  1448. expect(importNode?.signature).toContain('path::Path');
  1449. });
  1450. it('should extract crate imports', () => {
  1451. const code = `use crate::error::Error;`;
  1452. const result = extractFromSource('lib.rs', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('crate');
  1456. });
  1457. it('should extract super imports', () => {
  1458. const code = `use super::utils;`;
  1459. const result = extractFromSource('submod.rs', code);
  1460. const importNode = result.nodes.find((n) => n.kind === 'import');
  1461. expect(importNode).toBeDefined();
  1462. expect(importNode?.name).toBe('super');
  1463. });
  1464. it('should extract external crate imports', () => {
  1465. const code = `use serde::{Serialize, Deserialize};`;
  1466. const result = extractFromSource('types.rs', code);
  1467. const importNode = result.nodes.find((n) => n.kind === 'import');
  1468. expect(importNode).toBeDefined();
  1469. expect(importNode?.name).toBe('serde');
  1470. expect(importNode?.signature).toContain('Serialize');
  1471. expect(importNode?.signature).toContain('Deserialize');
  1472. });
  1473. });
  1474. describe('Go imports', () => {
  1475. it('should extract single import', () => {
  1476. const code = `
  1477. package main
  1478. import "fmt"
  1479. `;
  1480. const result = extractFromSource('main.go', code);
  1481. const importNode = result.nodes.find((n) => n.kind === 'import');
  1482. expect(importNode).toBeDefined();
  1483. expect(importNode?.name).toBe('fmt');
  1484. });
  1485. it('should extract grouped imports', () => {
  1486. const code = `
  1487. package main
  1488. import (
  1489. "fmt"
  1490. "os"
  1491. "encoding/json"
  1492. )
  1493. `;
  1494. const result = extractFromSource('main.go', code);
  1495. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1496. expect(importNodes.length).toBe(3);
  1497. const names = importNodes.map((n) => n.name);
  1498. expect(names).toContain('fmt');
  1499. expect(names).toContain('os');
  1500. expect(names).toContain('encoding/json');
  1501. });
  1502. it('should extract aliased import', () => {
  1503. const code = `
  1504. package main
  1505. import f "fmt"
  1506. `;
  1507. const result = extractFromSource('main.go', code);
  1508. const importNode = result.nodes.find((n) => n.kind === 'import');
  1509. expect(importNode).toBeDefined();
  1510. expect(importNode?.name).toBe('fmt');
  1511. expect(importNode?.signature).toContain('f');
  1512. });
  1513. it('should extract dot import', () => {
  1514. const code = `
  1515. package main
  1516. import . "math"
  1517. `;
  1518. const result = extractFromSource('main.go', code);
  1519. const importNode = result.nodes.find((n) => n.kind === 'import');
  1520. expect(importNode).toBeDefined();
  1521. expect(importNode?.name).toBe('math');
  1522. expect(importNode?.signature).toContain('.');
  1523. });
  1524. it('should extract blank import', () => {
  1525. const code = `
  1526. package main
  1527. import _ "github.com/go-sql-driver/mysql"
  1528. `;
  1529. const result = extractFromSource('main.go', code);
  1530. const importNode = result.nodes.find((n) => n.kind === 'import');
  1531. expect(importNode).toBeDefined();
  1532. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1533. expect(importNode?.signature).toContain('_');
  1534. });
  1535. });
  1536. describe('Swift imports', () => {
  1537. it('should extract simple import', () => {
  1538. const code = `import Foundation`;
  1539. const result = extractFromSource('main.swift', code);
  1540. const importNode = result.nodes.find((n) => n.kind === 'import');
  1541. expect(importNode).toBeDefined();
  1542. expect(importNode?.name).toBe('Foundation');
  1543. expect(importNode?.signature).toBe('import Foundation');
  1544. });
  1545. it('should extract @testable import', () => {
  1546. const code = `@testable import Alamofire`;
  1547. const result = extractFromSource('Tests.swift', code);
  1548. const importNode = result.nodes.find((n) => n.kind === 'import');
  1549. expect(importNode).toBeDefined();
  1550. expect(importNode?.name).toBe('Alamofire');
  1551. expect(importNode?.signature).toContain('@testable');
  1552. });
  1553. it('should extract @preconcurrency import', () => {
  1554. const code = `@preconcurrency import Security`;
  1555. const result = extractFromSource('Auth.swift', code);
  1556. const importNode = result.nodes.find((n) => n.kind === 'import');
  1557. expect(importNode).toBeDefined();
  1558. expect(importNode?.name).toBe('Security');
  1559. });
  1560. it('should extract multiple imports', () => {
  1561. const code = `
  1562. import Foundation
  1563. import UIKit
  1564. import Alamofire
  1565. `;
  1566. const result = extractFromSource('App.swift', code);
  1567. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1568. expect(importNodes.length).toBe(3);
  1569. const names = importNodes.map((n) => n.name);
  1570. expect(names).toContain('Foundation');
  1571. expect(names).toContain('UIKit');
  1572. expect(names).toContain('Alamofire');
  1573. });
  1574. });
  1575. describe('Kotlin imports', () => {
  1576. it('should extract simple import', () => {
  1577. const code = `import java.io.IOException`;
  1578. const result = extractFromSource('Main.kt', code);
  1579. const importNode = result.nodes.find((n) => n.kind === 'import');
  1580. expect(importNode).toBeDefined();
  1581. expect(importNode?.name).toBe('java.io.IOException');
  1582. expect(importNode?.signature).toBe('import java.io.IOException');
  1583. });
  1584. it('should extract aliased import', () => {
  1585. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1586. const result = extractFromSource('Utils.kt', code);
  1587. const importNode = result.nodes.find((n) => n.kind === 'import');
  1588. expect(importNode).toBeDefined();
  1589. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1590. expect(importNode?.signature).toContain('as RequestBuilder');
  1591. });
  1592. it('should extract wildcard import', () => {
  1593. const code = `import java.util.concurrent.TimeUnit.*`;
  1594. const result = extractFromSource('Time.kt', code);
  1595. const importNode = result.nodes.find((n) => n.kind === 'import');
  1596. expect(importNode).toBeDefined();
  1597. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1598. expect(importNode?.signature).toContain('.*');
  1599. });
  1600. it('should extract multiple imports', () => {
  1601. const code = `
  1602. import java.io.IOException
  1603. import kotlin.test.assertFailsWith
  1604. import okhttp3.OkHttpClient
  1605. `;
  1606. const result = extractFromSource('Test.kt', code);
  1607. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1608. expect(importNodes.length).toBe(3);
  1609. const names = importNodes.map((n) => n.name);
  1610. expect(names).toContain('java.io.IOException');
  1611. expect(names).toContain('kotlin.test.assertFailsWith');
  1612. expect(names).toContain('okhttp3.OkHttpClient');
  1613. });
  1614. });
  1615. describe('Java imports', () => {
  1616. it('should extract simple import', () => {
  1617. const code = `import java.util.List;`;
  1618. const result = extractFromSource('Main.java', code);
  1619. const importNode = result.nodes.find((n) => n.kind === 'import');
  1620. expect(importNode).toBeDefined();
  1621. expect(importNode?.name).toBe('java.util.List');
  1622. expect(importNode?.signature).toBe('import java.util.List;');
  1623. });
  1624. it('should extract static import', () => {
  1625. const code = `import static java.util.Collections.emptyList;`;
  1626. const result = extractFromSource('Utils.java', code);
  1627. const importNode = result.nodes.find((n) => n.kind === 'import');
  1628. expect(importNode).toBeDefined();
  1629. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1630. expect(importNode?.signature).toContain('static');
  1631. });
  1632. it('should extract wildcard import', () => {
  1633. const code = `import java.util.*;`;
  1634. const result = extractFromSource('App.java', code);
  1635. const importNode = result.nodes.find((n) => n.kind === 'import');
  1636. expect(importNode).toBeDefined();
  1637. expect(importNode?.name).toBe('java.util');
  1638. expect(importNode?.signature).toContain('.*');
  1639. });
  1640. it('should extract nested class import', () => {
  1641. const code = `import java.util.Map.Entry;`;
  1642. const result = extractFromSource('MapUtil.java', code);
  1643. const importNode = result.nodes.find((n) => n.kind === 'import');
  1644. expect(importNode).toBeDefined();
  1645. expect(importNode?.name).toBe('java.util.Map.Entry');
  1646. });
  1647. it('should extract multiple imports', () => {
  1648. const code = `
  1649. import java.util.List;
  1650. import java.util.Map;
  1651. import java.io.IOException;
  1652. `;
  1653. const result = extractFromSource('Service.java', code);
  1654. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1655. expect(importNodes.length).toBe(3);
  1656. const names = importNodes.map((n) => n.name);
  1657. expect(names).toContain('java.util.List');
  1658. expect(names).toContain('java.util.Map');
  1659. expect(names).toContain('java.io.IOException');
  1660. });
  1661. });
  1662. describe('C# imports', () => {
  1663. it('should extract simple using', () => {
  1664. const code = `using System;`;
  1665. const result = extractFromSource('Program.cs', code);
  1666. const importNode = result.nodes.find((n) => n.kind === 'import');
  1667. expect(importNode).toBeDefined();
  1668. expect(importNode?.name).toBe('System');
  1669. expect(importNode?.signature).toBe('using System;');
  1670. });
  1671. it('should extract qualified using', () => {
  1672. const code = `using System.Collections.Generic;`;
  1673. const result = extractFromSource('Utils.cs', code);
  1674. const importNode = result.nodes.find((n) => n.kind === 'import');
  1675. expect(importNode).toBeDefined();
  1676. expect(importNode?.name).toBe('System.Collections.Generic');
  1677. });
  1678. it('should extract static using', () => {
  1679. const code = `using static System.Console;`;
  1680. const result = extractFromSource('App.cs', code);
  1681. const importNode = result.nodes.find((n) => n.kind === 'import');
  1682. expect(importNode).toBeDefined();
  1683. expect(importNode?.name).toBe('System.Console');
  1684. expect(importNode?.signature).toContain('static');
  1685. });
  1686. it('should extract alias using', () => {
  1687. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1688. const result = extractFromSource('Types.cs', code);
  1689. const importNode = result.nodes.find((n) => n.kind === 'import');
  1690. expect(importNode).toBeDefined();
  1691. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1692. expect(importNode?.signature).toContain('MyList =');
  1693. });
  1694. it('should extract multiple usings', () => {
  1695. const code = `
  1696. using System;
  1697. using System.Threading.Tasks;
  1698. using Microsoft.Extensions.DependencyInjection;
  1699. `;
  1700. const result = extractFromSource('Service.cs', code);
  1701. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1702. expect(importNodes.length).toBe(3);
  1703. const names = importNodes.map((n) => n.name);
  1704. expect(names).toContain('System');
  1705. expect(names).toContain('System.Threading.Tasks');
  1706. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1707. });
  1708. });
  1709. describe('PHP imports', () => {
  1710. it('should extract simple use', () => {
  1711. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1712. const result = extractFromSource('Test.php', code);
  1713. const importNode = result.nodes.find((n) => n.kind === 'import');
  1714. expect(importNode).toBeDefined();
  1715. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1716. });
  1717. it('should extract aliased use', () => {
  1718. const code = `<?php use Mockery as m;`;
  1719. const result = extractFromSource('Test.php', code);
  1720. const importNode = result.nodes.find((n) => n.kind === 'import');
  1721. expect(importNode).toBeDefined();
  1722. expect(importNode?.name).toBe('Mockery');
  1723. expect(importNode?.signature).toContain('as m');
  1724. });
  1725. it('should extract function use', () => {
  1726. const code = `<?php use function Illuminate\\Support\\env;`;
  1727. const result = extractFromSource('helpers.php', code);
  1728. const importNode = result.nodes.find((n) => n.kind === 'import');
  1729. expect(importNode).toBeDefined();
  1730. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1731. expect(importNode?.signature).toContain('function');
  1732. });
  1733. it('should extract grouped use', () => {
  1734. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1735. const result = extractFromSource('Models.php', code);
  1736. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1737. expect(importNodes.length).toBe(2);
  1738. const names = importNodes.map((n) => n.name);
  1739. expect(names).toContain('Illuminate\\Database\\Model');
  1740. expect(names).toContain('Illuminate\\Database\\Builder');
  1741. });
  1742. it('should extract multiple uses', () => {
  1743. const code = `<?php
  1744. use Illuminate\\Support\\Collection;
  1745. use Illuminate\\Support\\Str;
  1746. use Closure;
  1747. `;
  1748. const result = extractFromSource('Service.php', code);
  1749. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1750. expect(importNodes.length).toBe(3);
  1751. const names = importNodes.map((n) => n.name);
  1752. expect(names).toContain('Illuminate\\Support\\Collection');
  1753. expect(names).toContain('Illuminate\\Support\\Str');
  1754. expect(names).toContain('Closure');
  1755. });
  1756. });
  1757. describe('Ruby imports', () => {
  1758. it('should extract require', () => {
  1759. const code = `require 'json'`;
  1760. const result = extractFromSource('app.rb', code);
  1761. const importNode = result.nodes.find((n) => n.kind === 'import');
  1762. expect(importNode).toBeDefined();
  1763. expect(importNode?.name).toBe('json');
  1764. expect(importNode?.signature).toBe("require 'json'");
  1765. });
  1766. it('should extract require with path', () => {
  1767. const code = `require 'active_support/core_ext/string'`;
  1768. const result = extractFromSource('config.rb', code);
  1769. const importNode = result.nodes.find((n) => n.kind === 'import');
  1770. expect(importNode).toBeDefined();
  1771. expect(importNode?.name).toBe('active_support/core_ext/string');
  1772. });
  1773. it('should extract require_relative', () => {
  1774. const code = `require_relative '../test_helper'`;
  1775. const result = extractFromSource('test/my_test.rb', code);
  1776. const importNode = result.nodes.find((n) => n.kind === 'import');
  1777. expect(importNode).toBeDefined();
  1778. expect(importNode?.name).toBe('../test_helper');
  1779. expect(importNode?.signature).toContain('require_relative');
  1780. });
  1781. it('should not extract non-require calls', () => {
  1782. const code = `puts 'hello'`;
  1783. const result = extractFromSource('app.rb', code);
  1784. const importNode = result.nodes.find((n) => n.kind === 'import');
  1785. expect(importNode).toBeUndefined();
  1786. });
  1787. it('should extract multiple requires', () => {
  1788. const code = `
  1789. require 'json'
  1790. require 'yaml'
  1791. require_relative 'helper'
  1792. `;
  1793. const result = extractFromSource('lib.rb', code);
  1794. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1795. expect(importNodes.length).toBe(3);
  1796. const names = importNodes.map((n) => n.name);
  1797. expect(names).toContain('json');
  1798. expect(names).toContain('yaml');
  1799. expect(names).toContain('helper');
  1800. });
  1801. });
  1802. describe('Ruby modules', () => {
  1803. it('should extract module as module node with containment', () => {
  1804. const code = `
  1805. module CachedCounting
  1806. def self.disable
  1807. @enabled = false
  1808. end
  1809. def perform_increment!(key, count)
  1810. write_cache!(key, count)
  1811. end
  1812. end
  1813. `;
  1814. const result = extractFromSource('concerns/cached_counting.rb', code);
  1815. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1816. expect(moduleNode).toBeDefined();
  1817. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1818. // Methods inside module should have module-qualified names
  1819. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1820. expect(disableMethod).toBeDefined();
  1821. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1822. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1823. expect(incrementMethod).toBeDefined();
  1824. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1825. // Containment edge from module to methods
  1826. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1827. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1828. });
  1829. it('should handle nested modules with classes', () => {
  1830. const code = `
  1831. module Discourse
  1832. module Auth
  1833. class AuthProvider
  1834. def authenticate(params)
  1835. validate(params)
  1836. end
  1837. end
  1838. end
  1839. end
  1840. `;
  1841. const result = extractFromSource('lib/auth.rb', code);
  1842. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1843. expect(discourseModule).toBeDefined();
  1844. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1845. expect(authModule).toBeDefined();
  1846. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1847. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1848. expect(authProvider).toBeDefined();
  1849. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1850. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1851. expect(authMethod).toBeDefined();
  1852. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1853. });
  1854. });
  1855. describe('C/C++ imports', () => {
  1856. it('should extract system include', () => {
  1857. const code = `#include <iostream>`;
  1858. const result = extractFromSource('main.cpp', code);
  1859. const importNode = result.nodes.find((n) => n.kind === 'import');
  1860. expect(importNode).toBeDefined();
  1861. expect(importNode?.name).toBe('iostream');
  1862. expect(importNode?.signature).toBe('#include <iostream>');
  1863. });
  1864. it('should extract system include with path', () => {
  1865. const code = `#include <nlohmann/json.hpp>`;
  1866. const result = extractFromSource('app.cpp', code);
  1867. const importNode = result.nodes.find((n) => n.kind === 'import');
  1868. expect(importNode).toBeDefined();
  1869. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1870. });
  1871. it('should extract local include', () => {
  1872. const code = `#include "myheader.h"`;
  1873. const result = extractFromSource('main.cpp', code);
  1874. const importNode = result.nodes.find((n) => n.kind === 'import');
  1875. expect(importNode).toBeDefined();
  1876. expect(importNode?.name).toBe('myheader.h');
  1877. });
  1878. it('should extract C header', () => {
  1879. const code = `#include <stdio.h>`;
  1880. const result = extractFromSource('main.c', code);
  1881. const importNode = result.nodes.find((n) => n.kind === 'import');
  1882. expect(importNode).toBeDefined();
  1883. expect(importNode?.name).toBe('stdio.h');
  1884. });
  1885. it('should extract multiple includes', () => {
  1886. const code = `
  1887. #include <iostream>
  1888. #include <vector>
  1889. #include "config.h"
  1890. `;
  1891. const result = extractFromSource('app.cpp', code);
  1892. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1893. expect(importNodes.length).toBe(3);
  1894. const names = importNodes.map((n) => n.name);
  1895. expect(names).toContain('iostream');
  1896. expect(names).toContain('vector');
  1897. expect(names).toContain('config.h');
  1898. });
  1899. it('should create unresolved references for local includes', () => {
  1900. const code = `#include "myheader.h"`;
  1901. const result = extractFromSource('main.cpp', code);
  1902. const importRef = result.unresolvedReferences.find(
  1903. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1904. );
  1905. expect(importRef).toBeDefined();
  1906. expect(importRef?.line).toBe(1);
  1907. });
  1908. it('should create unresolved references for system includes', () => {
  1909. const code = `#include <iostream>`;
  1910. const result = extractFromSource('main.cpp', code);
  1911. const importRef = result.unresolvedReferences.find(
  1912. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1913. );
  1914. expect(importRef).toBeDefined();
  1915. });
  1916. });
  1917. describe('Dart imports', () => {
  1918. it('should extract dart: import', () => {
  1919. const code = `import 'dart:async';`;
  1920. const result = extractFromSource('main.dart', code);
  1921. const importNode = result.nodes.find((n) => n.kind === 'import');
  1922. expect(importNode).toBeDefined();
  1923. expect(importNode?.name).toBe('dart:async');
  1924. expect(importNode?.signature).toBe("import 'dart:async';");
  1925. });
  1926. it('should extract package import', () => {
  1927. const code = `import 'package:flutter/material.dart';`;
  1928. const result = extractFromSource('app.dart', code);
  1929. const importNode = result.nodes.find((n) => n.kind === 'import');
  1930. expect(importNode).toBeDefined();
  1931. expect(importNode?.name).toBe('package:flutter/material.dart');
  1932. });
  1933. it('should extract aliased import', () => {
  1934. const code = `import 'package:http/http.dart' as http;`;
  1935. const result = extractFromSource('api.dart', code);
  1936. const importNode = result.nodes.find((n) => n.kind === 'import');
  1937. expect(importNode).toBeDefined();
  1938. expect(importNode?.name).toBe('package:http/http.dart');
  1939. expect(importNode?.signature).toContain('as http');
  1940. });
  1941. it('should extract multiple imports', () => {
  1942. const code = `
  1943. import 'dart:async';
  1944. import 'dart:convert';
  1945. import 'package:flutter/material.dart';
  1946. `;
  1947. const result = extractFromSource('main.dart', code);
  1948. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1949. expect(importNodes.length).toBe(3);
  1950. const names = importNodes.map((n) => n.name);
  1951. expect(names).toContain('dart:async');
  1952. expect(names).toContain('dart:convert');
  1953. expect(names).toContain('package:flutter/material.dart');
  1954. });
  1955. it('should extract relative import', () => {
  1956. const code = `import '../utils/helpers.dart';`;
  1957. const result = extractFromSource('lib/main.dart', code);
  1958. const importNode = result.nodes.find((n) => n.kind === 'import');
  1959. expect(importNode).toBeDefined();
  1960. expect(importNode?.name).toBe('../utils/helpers.dart');
  1961. });
  1962. });
  1963. describe('Liquid imports', () => {
  1964. it('should extract render tag', () => {
  1965. const code = `{% render 'loading-spinner' %}`;
  1966. const result = extractFromSource('template.liquid', code);
  1967. const importNode = result.nodes.find((n) => n.kind === 'import');
  1968. expect(importNode).toBeDefined();
  1969. expect(importNode?.name).toBe('loading-spinner');
  1970. expect(importNode?.signature).toContain('render');
  1971. });
  1972. it('should extract section tag', () => {
  1973. const code = `{% section 'header' %}`;
  1974. const result = extractFromSource('layout/theme.liquid', code);
  1975. const importNode = result.nodes.find((n) => n.kind === 'import');
  1976. expect(importNode).toBeDefined();
  1977. expect(importNode?.name).toBe('header');
  1978. expect(importNode?.signature).toContain('section');
  1979. });
  1980. it('should extract include tag', () => {
  1981. const code = `{% include 'icon-cart' %}`;
  1982. const result = extractFromSource('snippets/header.liquid', code);
  1983. const importNode = result.nodes.find((n) => n.kind === 'import');
  1984. expect(importNode).toBeDefined();
  1985. expect(importNode?.name).toBe('icon-cart');
  1986. expect(importNode?.signature).toContain('include');
  1987. });
  1988. it('should extract render with whitespace control', () => {
  1989. const code = `{%- render 'price' -%}`;
  1990. const result = extractFromSource('snippets/product.liquid', code);
  1991. const importNode = result.nodes.find((n) => n.kind === 'import');
  1992. expect(importNode).toBeDefined();
  1993. expect(importNode?.name).toBe('price');
  1994. });
  1995. it('should extract multiple imports', () => {
  1996. const code = `
  1997. {% section 'header' %}
  1998. {% render 'loading-spinner' %}
  1999. {% render 'cart-drawer' %}
  2000. `;
  2001. const result = extractFromSource('layout/theme.liquid', code);
  2002. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2003. expect(importNodes.length).toBe(3);
  2004. const names = importNodes.map((n) => n.name);
  2005. expect(names).toContain('header');
  2006. expect(names).toContain('loading-spinner');
  2007. expect(names).toContain('cart-drawer');
  2008. });
  2009. });
  2010. });
  2011. // =============================================================================
  2012. // Pascal / Delphi Extraction
  2013. // =============================================================================
  2014. describe('Pascal / Delphi Extraction', () => {
  2015. describe('Language detection', () => {
  2016. it('should detect Pascal files', () => {
  2017. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2018. expect(detectLanguage('App.dpr')).toBe('pascal');
  2019. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2020. expect(detectLanguage('App.lpr')).toBe('pascal');
  2021. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2022. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2023. });
  2024. it('should report Pascal as supported', () => {
  2025. expect(isLanguageSupported('pascal')).toBe(true);
  2026. expect(getSupportedLanguages()).toContain('pascal');
  2027. });
  2028. });
  2029. describe('Unit extraction', () => {
  2030. it('should extract unit as module', () => {
  2031. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2032. const result = extractFromSource('MyUnit.pas', code);
  2033. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2034. expect(moduleNode).toBeDefined();
  2035. expect(moduleNode?.name).toBe('MyUnit');
  2036. expect(moduleNode?.language).toBe('pascal');
  2037. });
  2038. it('should extract program as module', () => {
  2039. const code = `program MyApp;\nbegin\nend.`;
  2040. const result = extractFromSource('MyApp.dpr', code);
  2041. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2042. expect(moduleNode).toBeDefined();
  2043. expect(moduleNode?.name).toBe('MyApp');
  2044. });
  2045. it('should fallback to filename when module name is empty', () => {
  2046. // Some .dpr templates use "program;" without a name
  2047. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2048. const result = extractFromSource('Console.dpr', code);
  2049. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2050. expect(moduleNode).toBeDefined();
  2051. expect(moduleNode?.name).toBe('Console');
  2052. });
  2053. });
  2054. describe('Uses clause (imports)', () => {
  2055. it('should extract uses as individual imports', () => {
  2056. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2057. const result = extractFromSource('Test.pas', code);
  2058. const imports = result.nodes.filter((n) => n.kind === 'import');
  2059. expect(imports.length).toBe(2);
  2060. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2061. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2062. });
  2063. it('should create unresolved references for imports', () => {
  2064. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2065. const result = extractFromSource('Test.pas', code);
  2066. const importRef = result.unresolvedReferences.find(
  2067. (r) => r.referenceKind === 'imports'
  2068. );
  2069. expect(importRef).toBeDefined();
  2070. expect(importRef?.referenceName).toBe('UAuth');
  2071. });
  2072. });
  2073. describe('Class extraction', () => {
  2074. it('should extract class declarations', () => {
  2075. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2076. const result = extractFromSource('Test.pas', code);
  2077. const classNode = result.nodes.find((n) => n.kind === 'class');
  2078. expect(classNode).toBeDefined();
  2079. expect(classNode?.name).toBe('TMyClass');
  2080. });
  2081. it('should extract class with inheritance', () => {
  2082. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2083. const result = extractFromSource('Test.pas', code);
  2084. const extendsRef = result.unresolvedReferences.find(
  2085. (r) => r.referenceKind === 'extends'
  2086. );
  2087. expect(extendsRef).toBeDefined();
  2088. expect(extendsRef?.referenceName).toBe('TParent');
  2089. });
  2090. it('should extract class with interface implementation', () => {
  2091. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2092. const result = extractFromSource('Test.pas', code);
  2093. const extendsRef = result.unresolvedReferences.find(
  2094. (r) => r.referenceKind === 'extends'
  2095. );
  2096. const implementsRef = result.unresolvedReferences.find(
  2097. (r) => r.referenceKind === 'implements'
  2098. );
  2099. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2100. expect(implementsRef?.referenceName).toBe('ILogger');
  2101. });
  2102. });
  2103. describe('Record extraction', () => {
  2104. it('should extract records as class nodes', () => {
  2105. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2106. const result = extractFromSource('Test.pas', code);
  2107. const classNode = result.nodes.find((n) => n.kind === 'class');
  2108. expect(classNode).toBeDefined();
  2109. expect(classNode?.name).toBe('TPoint');
  2110. const fields = result.nodes.filter((n) => n.kind === 'field');
  2111. expect(fields.length).toBe(2);
  2112. expect(fields.map((f) => f.name)).toContain('X');
  2113. expect(fields.map((f) => f.name)).toContain('Y');
  2114. });
  2115. });
  2116. describe('Interface extraction', () => {
  2117. it('should extract interface declarations', () => {
  2118. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2119. const result = extractFromSource('Test.pas', code);
  2120. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2121. expect(ifaceNode).toBeDefined();
  2122. expect(ifaceNode?.name).toBe('ILogger');
  2123. });
  2124. });
  2125. describe('Method extraction', () => {
  2126. it('should extract methods with visibility', () => {
  2127. 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.`;
  2128. const result = extractFromSource('Test.pas', code);
  2129. const methods = result.nodes.filter((n) => n.kind === 'method');
  2130. expect(methods.length).toBe(2);
  2131. const createMethod = methods.find((m) => m.name === 'Create');
  2132. expect(createMethod?.visibility).toBe('public');
  2133. const getValue = methods.find((m) => m.name === 'GetValue');
  2134. expect(getValue?.visibility).toBe('public');
  2135. const fields = result.nodes.filter((n) => n.kind === 'field');
  2136. const fValue = fields.find((f) => f.name === 'FValue');
  2137. expect(fValue?.visibility).toBe('private');
  2138. });
  2139. it('should detect static methods (class methods)', () => {
  2140. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2141. const result = extractFromSource('Test.pas', code);
  2142. const methods = result.nodes.filter((n) => n.kind === 'method');
  2143. const staticMethod = methods.find((m) => m.name === 'Create');
  2144. expect(staticMethod?.isStatic).toBe(true);
  2145. });
  2146. });
  2147. describe('Enum extraction', () => {
  2148. it('should extract enums with members', () => {
  2149. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2150. const result = extractFromSource('Test.pas', code);
  2151. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2152. expect(enumNode).toBeDefined();
  2153. expect(enumNode?.name).toBe('TColor');
  2154. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2155. expect(members.length).toBe(3);
  2156. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2157. });
  2158. });
  2159. describe('Property extraction', () => {
  2160. it('should extract properties', () => {
  2161. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2162. const result = extractFromSource('Test.pas', code);
  2163. const propNode = result.nodes.find((n) => n.kind === 'property');
  2164. expect(propNode).toBeDefined();
  2165. expect(propNode?.name).toBe('Name');
  2166. expect(propNode?.visibility).toBe('public');
  2167. });
  2168. });
  2169. describe('Constant extraction', () => {
  2170. it('should extract constants', () => {
  2171. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2172. const result = extractFromSource('Test.pas', code);
  2173. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2174. expect(constants.length).toBe(2);
  2175. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2176. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2177. });
  2178. });
  2179. describe('Type alias extraction', () => {
  2180. it('should extract type aliases', () => {
  2181. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2182. const result = extractFromSource('Test.pas', code);
  2183. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2184. expect(aliasNode).toBeDefined();
  2185. expect(aliasNode?.name).toBe('TUserName');
  2186. });
  2187. });
  2188. describe('Call extraction', () => {
  2189. it('should extract calls from implementation bodies', () => {
  2190. 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.`;
  2191. const result = extractFromSource('Test.pas', code);
  2192. const callRef = result.unresolvedReferences.find(
  2193. (r) => r.referenceKind === 'calls'
  2194. );
  2195. expect(callRef).toBeDefined();
  2196. expect(callRef?.referenceName).toBe('WriteLn');
  2197. });
  2198. });
  2199. describe('Containment edges', () => {
  2200. it('should create contains edges for class members', () => {
  2201. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2202. const result = extractFromSource('Test.pas', code);
  2203. const classNode = result.nodes.find((n) => n.kind === 'class');
  2204. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2205. expect(classNode).toBeDefined();
  2206. expect(methodNode).toBeDefined();
  2207. const containsEdge = result.edges.find(
  2208. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2209. );
  2210. expect(containsEdge).toBeDefined();
  2211. });
  2212. });
  2213. describe('Full fixture: UAuth.pas', () => {
  2214. const code = `unit UAuth;
  2215. interface
  2216. uses
  2217. System.SysUtils,
  2218. System.Classes;
  2219. type
  2220. ITokenValidator = interface
  2221. ['{11111111-1111-1111-1111-111111111111}']
  2222. function Validate(const AToken: string): Boolean;
  2223. end;
  2224. TAuthService = class(TInterfacedObject, ITokenValidator)
  2225. private
  2226. FToken: string;
  2227. FLoginCount: Integer;
  2228. procedure IncLoginCount;
  2229. protected
  2230. function GetToken: string;
  2231. public
  2232. constructor Create;
  2233. destructor Destroy; override;
  2234. function Validate(const AToken: string): Boolean;
  2235. function Login(const AUser, APass: string): string;
  2236. property Token: string read GetToken;
  2237. property LoginCount: Integer read FLoginCount;
  2238. end;
  2239. implementation
  2240. constructor TAuthService.Create;
  2241. begin
  2242. inherited Create;
  2243. FToken := '';
  2244. FLoginCount := 0;
  2245. end;
  2246. destructor TAuthService.Destroy;
  2247. begin
  2248. FToken := '';
  2249. inherited Destroy;
  2250. end;
  2251. procedure TAuthService.IncLoginCount;
  2252. begin
  2253. Inc(FLoginCount);
  2254. end;
  2255. function TAuthService.GetToken: string;
  2256. begin
  2257. Result := FToken;
  2258. end;
  2259. function TAuthService.Validate(const AToken: string): Boolean;
  2260. begin
  2261. Result := AToken <> '';
  2262. end;
  2263. function TAuthService.Login(const AUser, APass: string): string;
  2264. begin
  2265. IncLoginCount;
  2266. if Validate(AUser + ':' + APass) then
  2267. begin
  2268. FToken := AUser;
  2269. Result := 'ok';
  2270. end
  2271. else
  2272. Result := '';
  2273. end;
  2274. end.`;
  2275. it('should extract all expected nodes', () => {
  2276. const result = extractFromSource('UAuth.pas', code);
  2277. expect(result.errors).toHaveLength(0);
  2278. // Module
  2279. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2280. expect(moduleNode?.name).toBe('UAuth');
  2281. // Imports
  2282. const imports = result.nodes.filter((n) => n.kind === 'import');
  2283. expect(imports.length).toBe(2);
  2284. // Interface
  2285. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2286. expect(ifaceNode?.name).toBe('ITokenValidator');
  2287. // Class
  2288. const classNode = result.nodes.find((n) => n.kind === 'class');
  2289. expect(classNode?.name).toBe('TAuthService');
  2290. // Methods
  2291. const methods = result.nodes.filter((n) => n.kind === 'method');
  2292. expect(methods.length).toBeGreaterThanOrEqual(6);
  2293. expect(methods.map((m) => m.name)).toContain('Create');
  2294. expect(methods.map((m) => m.name)).toContain('Destroy');
  2295. expect(methods.map((m) => m.name)).toContain('Login');
  2296. // Fields
  2297. const fields = result.nodes.filter((n) => n.kind === 'field');
  2298. expect(fields.length).toBe(2);
  2299. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2300. // Properties
  2301. const props = result.nodes.filter((n) => n.kind === 'property');
  2302. expect(props.length).toBe(2);
  2303. expect(props.map((p) => p.name)).toContain('Token');
  2304. expect(props.map((p) => p.name)).toContain('LoginCount');
  2305. });
  2306. it('should extract inheritance and interface implementation', () => {
  2307. const result = extractFromSource('UAuth.pas', code);
  2308. const extendsRef = result.unresolvedReferences.find(
  2309. (r) => r.referenceKind === 'extends'
  2310. );
  2311. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2312. const implementsRef = result.unresolvedReferences.find(
  2313. (r) => r.referenceKind === 'implements'
  2314. );
  2315. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2316. });
  2317. it('should extract calls from implementation', () => {
  2318. const result = extractFromSource('UAuth.pas', code);
  2319. const callRefs = result.unresolvedReferences.filter(
  2320. (r) => r.referenceKind === 'calls'
  2321. );
  2322. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2323. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2324. });
  2325. });
  2326. describe('Full fixture: UTypes.pas', () => {
  2327. const code = `unit UTypes;
  2328. interface
  2329. uses
  2330. System.SysUtils;
  2331. const
  2332. C_MAX_RETRIES = 3;
  2333. C_DEFAULT_NAME = 'Guest';
  2334. type
  2335. TUserRole = (urAdmin, urEditor, urViewer);
  2336. TPoint2D = record
  2337. X: Double;
  2338. Y: Double;
  2339. end;
  2340. TUserName = string;
  2341. TUserInfo = class
  2342. public
  2343. type
  2344. TAddress = record
  2345. Street: string;
  2346. City: string;
  2347. Zip: string;
  2348. end;
  2349. private
  2350. FName: TUserName;
  2351. FRole: TUserRole;
  2352. FAddress: TAddress;
  2353. public
  2354. constructor Create(const AName: TUserName; ARole: TUserRole);
  2355. function GetDisplayName: string;
  2356. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2357. property Name: TUserName read FName write FName;
  2358. property Role: TUserRole read FRole;
  2359. property Address: TAddress read FAddress write FAddress;
  2360. end;
  2361. implementation
  2362. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2363. begin
  2364. FName := AName;
  2365. FRole := ARole;
  2366. end;
  2367. function TUserInfo.GetDisplayName: string;
  2368. begin
  2369. if FRole = urAdmin then
  2370. Result := '[Admin] ' + FName
  2371. else
  2372. Result := FName;
  2373. end;
  2374. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2375. begin
  2376. Result := TUserInfo.Create(AName, urAdmin);
  2377. end;
  2378. end.`;
  2379. it('should extract enums with members', () => {
  2380. const result = extractFromSource('UTypes.pas', code);
  2381. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2382. expect(enumNode?.name).toBe('TUserRole');
  2383. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2384. expect(members.length).toBe(3);
  2385. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2386. });
  2387. it('should extract constants', () => {
  2388. const result = extractFromSource('UTypes.pas', code);
  2389. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2390. expect(constants.length).toBe(2);
  2391. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2392. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2393. });
  2394. it('should extract type aliases', () => {
  2395. const result = extractFromSource('UTypes.pas', code);
  2396. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2397. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2398. });
  2399. it('should extract records as classes with fields', () => {
  2400. const result = extractFromSource('UTypes.pas', code);
  2401. const classes = result.nodes.filter((n) => n.kind === 'class');
  2402. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2403. // TPoint2D fields
  2404. const fields = result.nodes.filter((n) => n.kind === 'field');
  2405. expect(fields.map((f) => f.name)).toContain('X');
  2406. expect(fields.map((f) => f.name)).toContain('Y');
  2407. });
  2408. it('should extract static class methods', () => {
  2409. const result = extractFromSource('UTypes.pas', code);
  2410. const methods = result.nodes.filter((n) => n.kind === 'method');
  2411. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2412. expect(staticMethod).toBeDefined();
  2413. expect(staticMethod?.isStatic).toBe(true);
  2414. });
  2415. it('should extract nested types', () => {
  2416. const result = extractFromSource('UTypes.pas', code);
  2417. const classes = result.nodes.filter((n) => n.kind === 'class');
  2418. expect(classes.map((c) => c.name)).toContain('TAddress');
  2419. });
  2420. });
  2421. });
  2422. // =============================================================================
  2423. // DFM/FMX Extraction
  2424. // =============================================================================
  2425. describe('DFM/FMX Extraction', () => {
  2426. it('should extract components from DFM', () => {
  2427. const code = `object Form1: TForm1
  2428. Left = 0
  2429. Top = 0
  2430. Caption = 'My Form'
  2431. object Button1: TButton
  2432. Left = 10
  2433. Top = 10
  2434. Caption = 'Click Me'
  2435. end
  2436. end`;
  2437. const result = extractFromSource('Form1.dfm', code);
  2438. const components = result.nodes.filter((n) => n.kind === 'component');
  2439. expect(components.length).toBe(2);
  2440. expect(components.map((c) => c.name)).toContain('Form1');
  2441. expect(components.map((c) => c.name)).toContain('Button1');
  2442. const button = components.find((c) => c.name === 'Button1');
  2443. expect(button?.signature).toBe('TButton');
  2444. });
  2445. it('should extract nested component hierarchy', () => {
  2446. const code = `object Form1: TForm1
  2447. object Panel1: TPanel
  2448. object Label1: TLabel
  2449. Caption = 'Hello'
  2450. end
  2451. end
  2452. end`;
  2453. const result = extractFromSource('Form1.dfm', code);
  2454. const components = result.nodes.filter((n) => n.kind === 'component');
  2455. expect(components.length).toBe(3);
  2456. // Check nesting: Panel1 contains Label1
  2457. const panel = components.find((c) => c.name === 'Panel1');
  2458. const label = components.find((c) => c.name === 'Label1');
  2459. const containsEdge = result.edges.find(
  2460. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2461. );
  2462. expect(containsEdge).toBeDefined();
  2463. });
  2464. it('should extract event handler references', () => {
  2465. const code = `object Form1: TForm1
  2466. OnCreate = FormCreate
  2467. OnDestroy = FormDestroy
  2468. object Button1: TButton
  2469. OnClick = Button1Click
  2470. end
  2471. end`;
  2472. const result = extractFromSource('Form1.dfm', code);
  2473. const refs = result.unresolvedReferences;
  2474. expect(refs.length).toBe(3);
  2475. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2476. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2477. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2478. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2479. });
  2480. it('should handle multi-line properties', () => {
  2481. const code = `object Form1: TForm1
  2482. SQL.Strings = (
  2483. 'SELECT * FROM users'
  2484. 'WHERE active = 1')
  2485. object Button1: TButton
  2486. OnClick = Button1Click
  2487. end
  2488. end`;
  2489. const result = extractFromSource('Form1.dfm', code);
  2490. const components = result.nodes.filter((n) => n.kind === 'component');
  2491. expect(components.length).toBe(2);
  2492. const refs = result.unresolvedReferences;
  2493. expect(refs.length).toBe(1);
  2494. expect(refs[0]?.referenceName).toBe('Button1Click');
  2495. });
  2496. it('should handle inherited keyword', () => {
  2497. const code = `inherited Form1: TForm1
  2498. Caption = 'Inherited Form'
  2499. object Button1: TButton
  2500. OnClick = Button1Click
  2501. end
  2502. end`;
  2503. const result = extractFromSource('Form1.dfm', code);
  2504. const components = result.nodes.filter((n) => n.kind === 'component');
  2505. expect(components.length).toBe(2);
  2506. expect(components.map((c) => c.name)).toContain('Form1');
  2507. });
  2508. it('should handle item collection properties', () => {
  2509. const code = `object Form1: TForm1
  2510. object StatusBar1: TStatusBar
  2511. Panels = <
  2512. item
  2513. Width = 200
  2514. end
  2515. item
  2516. Width = 200
  2517. end>
  2518. end
  2519. end`;
  2520. const result = extractFromSource('Form1.dfm', code);
  2521. const components = result.nodes.filter((n) => n.kind === 'component');
  2522. expect(components.length).toBe(2);
  2523. });
  2524. describe('Full fixture: MainForm.dfm', () => {
  2525. const code = `object frmMain: TfrmMain
  2526. Left = 0
  2527. Top = 0
  2528. Caption = 'CodeGraph DFM Fixture'
  2529. ClientHeight = 480
  2530. ClientWidth = 640
  2531. OnCreate = FormCreate
  2532. OnDestroy = FormDestroy
  2533. object pnlTop: TPanel
  2534. Left = 0
  2535. Top = 0
  2536. Width = 640
  2537. Height = 50
  2538. object lblTitle: TLabel
  2539. Left = 16
  2540. Top = 16
  2541. Caption = 'Authentication Service'
  2542. end
  2543. object btnLogin: TButton
  2544. Left = 540
  2545. Top = 12
  2546. OnClick = btnLoginClick
  2547. end
  2548. end
  2549. object pnlContent: TPanel
  2550. Left = 0
  2551. Top = 50
  2552. object edtUsername: TEdit
  2553. Left = 16
  2554. Top = 16
  2555. OnChange = edtUsernameChange
  2556. end
  2557. object edtPassword: TEdit
  2558. Left = 16
  2559. Top = 48
  2560. OnKeyPress = edtPasswordKeyPress
  2561. end
  2562. object mmoLog: TMemo
  2563. Left = 16
  2564. Top = 88
  2565. end
  2566. end
  2567. object pnlStatus: TStatusBar
  2568. Left = 0
  2569. Top = 440
  2570. Panels = <
  2571. item
  2572. Width = 200
  2573. end
  2574. item
  2575. Width = 200
  2576. end>
  2577. end
  2578. end`;
  2579. it('should extract all components', () => {
  2580. const result = extractFromSource('MainForm.dfm', code);
  2581. const components = result.nodes.filter((n) => n.kind === 'component');
  2582. expect(components.length).toBe(9);
  2583. expect(components.map((c) => c.name)).toEqual(
  2584. expect.arrayContaining([
  2585. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2586. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2587. ])
  2588. );
  2589. });
  2590. it('should extract all event handlers', () => {
  2591. const result = extractFromSource('MainForm.dfm', code);
  2592. const refs = result.unresolvedReferences;
  2593. expect(refs.length).toBe(5);
  2594. expect(refs.map((r) => r.referenceName)).toEqual(
  2595. expect.arrayContaining([
  2596. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2597. 'edtUsernameChange', 'edtPasswordKeyPress',
  2598. ])
  2599. );
  2600. });
  2601. });
  2602. });
  2603. describe('Kotlin Multiplatform expect/actual', () => {
  2604. let tempDir: string;
  2605. let cg: CodeGraph;
  2606. beforeEach(() => {
  2607. tempDir = createTempDir();
  2608. });
  2609. afterEach(() => {
  2610. if (cg) cg.close();
  2611. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2612. });
  2613. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  2614. const common = path.join(tempDir, 'src', 'commonMain');
  2615. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2616. fs.mkdirSync(common, { recursive: true });
  2617. fs.mkdirSync(jvm, { recursive: true });
  2618. // common source set: expect declarations + a caller that uses them
  2619. fs.writeFileSync(
  2620. path.join(common, 'SystemProps.kt'),
  2621. `package demo.internal
  2622. expect fun systemProp(name: String): String?
  2623. expect class Platform {
  2624. fun describe(): String
  2625. }
  2626. `
  2627. );
  2628. fs.writeFileSync(
  2629. path.join(common, 'Caller.kt'),
  2630. `package demo
  2631. import demo.internal.systemProp
  2632. import demo.internal.Platform
  2633. fun useIt(): String {
  2634. val v = systemProp("os.name")
  2635. return Platform().describe() + v
  2636. }
  2637. `
  2638. );
  2639. // jvm source set: actual implementations
  2640. fs.writeFileSync(
  2641. path.join(jvm, 'SystemProps.kt'),
  2642. `package demo.internal
  2643. actual fun systemProp(name: String): String? = System.getProperty(name)
  2644. actual class Platform {
  2645. actual fun describe(): String = "JVM"
  2646. }
  2647. `
  2648. );
  2649. cg = CodeGraph.initSync(tempDir);
  2650. await cg.indexAll();
  2651. cg.resolveReferences();
  2652. // The expect/actual markers are captured onto the node's decorators.
  2653. const fns = cg.getNodesByKind('function');
  2654. const actualFn = fns.find(
  2655. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  2656. );
  2657. const expectFn = fns.find(
  2658. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  2659. );
  2660. expect(actualFn).toBeDefined();
  2661. expect(expectFn).toBeDefined();
  2662. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  2663. // Editing the JVM actual must surface the common expect AND its caller —
  2664. // before the expect/actual bridge the actual had zero dependents.
  2665. const impact = cg.getImpactRadius(actualFn!.id, 3);
  2666. const impacted = [...impact.nodes.values()].map((n) => n.name);
  2667. expect(impacted).toContain('systemProp'); // the common expect
  2668. expect(impacted).toContain('useIt'); // the caller, reached transitively
  2669. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  2670. const bridge = impact.edges.find(
  2671. (e) =>
  2672. e.target === actualFn!.id &&
  2673. e.provenance === 'heuristic' &&
  2674. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2675. 'kotlin-expect-actual'
  2676. );
  2677. expect(bridge).toBeDefined();
  2678. expect(bridge!.source).toBe(expectFn!.id);
  2679. });
  2680. it('links an expect class to an actual typealias (different node kinds)', async () => {
  2681. const common = path.join(tempDir, 'src', 'commonMain');
  2682. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2683. fs.mkdirSync(common, { recursive: true });
  2684. fs.mkdirSync(jvm, { recursive: true });
  2685. fs.writeFileSync(
  2686. path.join(common, 'Lock.kt'),
  2687. `package demo
  2688. expect class Lock {
  2689. fun acquire()
  2690. }
  2691. `
  2692. );
  2693. fs.writeFileSync(
  2694. path.join(jvm, 'Lock.kt'),
  2695. `package demo
  2696. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  2697. `
  2698. );
  2699. cg = CodeGraph.initSync(tempDir);
  2700. await cg.indexAll();
  2701. cg.resolveReferences();
  2702. const aliasNode = cg
  2703. .getNodesByKind('type_alias')
  2704. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  2705. expect(aliasNode).toBeDefined();
  2706. // The actual typealias is now a cross-file dependency target (linked from
  2707. // the expect class), so it participates in impact rather than being orphaned.
  2708. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  2709. const bridge = impact.edges.find(
  2710. (e) =>
  2711. e.target === aliasNode!.id &&
  2712. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2713. 'kotlin-expect-actual'
  2714. );
  2715. expect(bridge).toBeDefined();
  2716. });
  2717. });
  2718. describe('Scala cross-file dependencies', () => {
  2719. let tempDir: string;
  2720. let cg: CodeGraph;
  2721. beforeEach(() => {
  2722. tempDir = createTempDir();
  2723. });
  2724. afterEach(() => {
  2725. if (cg) cg.close();
  2726. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2727. });
  2728. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  2729. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  2730. fs.mkdirSync(src, { recursive: true });
  2731. fs.writeFileSync(
  2732. path.join(src, 'Semigroup.scala'),
  2733. `package demo
  2734. trait Semigroup[A] {
  2735. def combine(x: A, y: A): A
  2736. }
  2737. `
  2738. );
  2739. fs.writeFileSync(
  2740. path.join(src, 'Monoid.scala'),
  2741. `package demo
  2742. trait Monoid[A] extends Semigroup[A] {
  2743. def empty: A
  2744. }
  2745. `
  2746. );
  2747. fs.writeFileSync(
  2748. path.join(src, 'Instances.scala'),
  2749. `package demo
  2750. object Instances {
  2751. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  2752. def empty: Int = 0
  2753. def combine(x: Int, y: Int): Int = x + y
  2754. }
  2755. }
  2756. `
  2757. );
  2758. fs.writeFileSync(
  2759. path.join(src, 'Folding.scala'),
  2760. `package demo
  2761. object Folding {
  2762. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  2763. xs.foldLeft(M.empty)(M.combine)
  2764. }
  2765. `
  2766. );
  2767. cg = CodeGraph.initSync(tempDir);
  2768. await cg.indexAll();
  2769. cg.resolveReferences();
  2770. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  2771. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  2772. expect(monoid).toBeDefined();
  2773. expect(semigroup).toBeDefined();
  2774. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  2775. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  2776. // the whole point of the fix (the `[A]` used to defeat name matching).
  2777. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  2778. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  2779. // Editing Monoid surfaces the cross-file users: the instance val typed
  2780. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  2781. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  2782. expect(impacted).toContain('intMonoid'); // field type annotation
  2783. expect(impacted).toContain('fold'); // trailing implicit parameter list
  2784. });
  2785. });
  2786. describe('PHP namespace + import resolution', () => {
  2787. let tempDir: string;
  2788. let cg: CodeGraph;
  2789. beforeEach(() => {
  2790. tempDir = createTempDir();
  2791. });
  2792. afterEach(() => {
  2793. if (cg) cg.close();
  2794. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2795. });
  2796. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  2797. const src = path.join(tempDir, 'src');
  2798. // Two interfaces with the SAME simple name in different namespaces — the
  2799. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  2800. // resolve. The namespace qualifies them; the `use` import disambiguates.
  2801. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  2802. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  2803. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  2804. fs.writeFileSync(
  2805. path.join(src, 'Cache', 'Factory.php'),
  2806. `<?php
  2807. namespace Contracts\\Cache;
  2808. interface Factory {
  2809. public function store(): object;
  2810. }
  2811. `
  2812. );
  2813. fs.writeFileSync(
  2814. path.join(src, 'Mail', 'Factory.php'),
  2815. `<?php
  2816. namespace Contracts\\Mail;
  2817. interface Factory {
  2818. public function mailer(): object;
  2819. }
  2820. `
  2821. );
  2822. fs.writeFileSync(
  2823. path.join(src, 'App', 'Service.php'),
  2824. `<?php
  2825. namespace App;
  2826. use Contracts\\Cache\\Factory;
  2827. class Service {
  2828. public function make(): Factory {
  2829. return resolve(Factory::class);
  2830. }
  2831. }
  2832. `
  2833. );
  2834. cg = CodeGraph.initSync(tempDir);
  2835. await cg.indexAll();
  2836. cg.resolveReferences();
  2837. // The PHP namespace is captured into the qualified name, so the two
  2838. // same-named interfaces are distinguishable.
  2839. const cacheFactory = cg
  2840. .getNodesByKind('interface')
  2841. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  2842. const mailFactory = cg
  2843. .getNodesByKind('interface')
  2844. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  2845. expect(cacheFactory).toBeDefined();
  2846. expect(mailFactory).toBeDefined();
  2847. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  2848. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  2849. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  2850. const serviceFile = 'src/App/Service.php';
  2851. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  2852. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2853. );
  2854. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  2855. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2856. );
  2857. expect(cacheReaches).toBe(true);
  2858. expect(mailReaches).toBe(false);
  2859. });
  2860. });
  2861. describe('Ruby mixins (include/extend/prepend)', () => {
  2862. let tempDir: string;
  2863. let cg: CodeGraph;
  2864. beforeEach(() => {
  2865. tempDir = createTempDir();
  2866. });
  2867. afterEach(() => {
  2868. if (cg) cg.close();
  2869. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2870. });
  2871. it('links include/extend/prepend to the mixed-in module across files', async () => {
  2872. const lib = path.join(tempDir, 'lib');
  2873. fs.mkdirSync(lib, { recursive: true });
  2874. fs.writeFileSync(
  2875. path.join(lib, 'concerns.rb'),
  2876. `module Trackable
  2877. def track; end
  2878. end
  2879. module Cacheable
  2880. def cache; end
  2881. end
  2882. module Loggable
  2883. def log; end
  2884. end
  2885. `
  2886. );
  2887. fs.writeFileSync(
  2888. path.join(lib, 'model.rb'),
  2889. `class Model
  2890. include Trackable
  2891. prepend Cacheable
  2892. extend Loggable
  2893. end
  2894. `
  2895. );
  2896. cg = CodeGraph.initSync(tempDir);
  2897. await cg.indexAll();
  2898. cg.resolveReferences();
  2899. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  2900. expect(model).toBeDefined();
  2901. // All three mixin forms create an `implements` edge Model → module, so
  2902. // editing a concern surfaces every class that mixes it in (across files).
  2903. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  2904. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  2905. expect(mod, moduleName).toBeDefined();
  2906. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  2907. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  2908. }
  2909. });
  2910. it('resolves require / require_relative to the required file', async () => {
  2911. const lib = path.join(tempDir, 'lib');
  2912. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  2913. // A leaf file whose class is referenced only dynamically — so without
  2914. // require resolution it would look like nothing depends on it.
  2915. fs.writeFileSync(
  2916. path.join(lib, 'app', 'fetcher.rb'),
  2917. `module App
  2918. class Fetcher
  2919. def fetch; end
  2920. end
  2921. end
  2922. `
  2923. );
  2924. // Pulled in by a load-path `require` …
  2925. fs.writeFileSync(
  2926. path.join(lib, 'app', 'worker.rb'),
  2927. `require "app/fetcher"
  2928. module App
  2929. class Worker; end
  2930. end
  2931. `
  2932. );
  2933. // … and a sibling pulled in by `require_relative`.
  2934. fs.writeFileSync(
  2935. path.join(lib, 'app', 'boot.rb'),
  2936. `require_relative "fetcher"
  2937. `
  2938. );
  2939. cg = CodeGraph.initSync(tempDir);
  2940. await cg.indexAll();
  2941. cg.resolveReferences();
  2942. // The require edges target fetcher.rb's FILE node. Editing it should reach
  2943. // BOTH the load-path requirer (worker.rb) and the require_relative one
  2944. // (boot.rb) — without require resolution its file would have no dependents.
  2945. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  2946. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  2947. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  2948. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  2949. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  2950. });
  2951. });
  2952. describe('C++ free-function name extraction', () => {
  2953. let tempDir: string;
  2954. let cg: CodeGraph;
  2955. beforeEach(() => {
  2956. tempDir = createTempDir();
  2957. });
  2958. afterEach(() => {
  2959. if (cg) cg.close();
  2960. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2961. });
  2962. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  2963. const src = path.join(tempDir, 'src');
  2964. fs.mkdirSync(src, { recursive: true });
  2965. // TableFileName has a `const std::string&` parameter; BuildName uses an
  2966. // `auto … -> std::string` trailing return type. Both used to be named
  2967. // `string` (picked up from the parameter / return type), so callers never
  2968. // resolved and the defining file looked like nothing depended on it.
  2969. fs.writeFileSync(
  2970. path.join(src, 'names.cc'),
  2971. `#include <string>
  2972. std::string TableFileName(const std::string& dbname, int number) {
  2973. return dbname;
  2974. }
  2975. auto BuildName(const std::string& a) -> std::string {
  2976. return a;
  2977. }
  2978. `
  2979. );
  2980. fs.writeFileSync(
  2981. path.join(src, 'user.cc'),
  2982. `#include <string>
  2983. std::string use() {
  2984. return TableFileName("db", 1) + BuildName("x");
  2985. }
  2986. `
  2987. );
  2988. cg = CodeGraph.initSync(tempDir);
  2989. await cg.indexAll();
  2990. cg.resolveReferences();
  2991. // The functions are extracted under their real names, not `string`.
  2992. const fns = cg.getNodesByKind('function');
  2993. const tableFn = fns.find((n) => n.name === 'TableFileName');
  2994. const buildFn = fns.find((n) => n.name === 'BuildName');
  2995. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  2996. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  2997. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  2998. for (const fn of [tableFn!, buildFn!]) {
  2999. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3000. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3001. }
  3002. });
  3003. });
  3004. describe('Dart mixins and type references', () => {
  3005. let tempDir: string;
  3006. let cg: CodeGraph;
  3007. beforeEach(() => {
  3008. tempDir = createTempDir();
  3009. });
  3010. afterEach(() => {
  3011. if (cg) cg.close();
  3012. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3013. });
  3014. it('links `with` mixins and method parameter/return types across files', async () => {
  3015. const lib = path.join(tempDir, 'lib');
  3016. fs.mkdirSync(lib, { recursive: true });
  3017. fs.writeFileSync(
  3018. path.join(lib, 'models.dart'),
  3019. `class User {
  3020. final String name;
  3021. User(this.name);
  3022. }
  3023. mixin Loggable {
  3024. void log() {}
  3025. }
  3026. abstract class Repository {
  3027. User find(int id);
  3028. }
  3029. `
  3030. );
  3031. fs.writeFileSync(
  3032. path.join(lib, 'service.dart'),
  3033. `import 'models.dart';
  3034. class UserService extends Repository with Loggable {
  3035. @override
  3036. User find(int id) => User('x');
  3037. List<User> all() => [];
  3038. }
  3039. `
  3040. );
  3041. cg = CodeGraph.initSync(tempDir);
  3042. await cg.indexAll();
  3043. cg.resolveReferences();
  3044. const inModels = (name: string) =>
  3045. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3046. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3047. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3048. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3049. // as a class-like node.
  3050. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3051. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3052. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3053. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3054. expect(mixinUsers).toContain('UserService');
  3055. // `User` is used only as a method parameter/return type in service.dart —
  3056. // editing it must still surface service.dart via the type references.
  3057. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3058. expect(user, 'User indexed').toBeDefined();
  3059. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3060. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3061. });
  3062. });
  3063. describe('Static-member / value-read references', () => {
  3064. let tempDir: string;
  3065. let cg: CodeGraph;
  3066. beforeEach(() => {
  3067. tempDir = createTempDir();
  3068. });
  3069. afterEach(() => {
  3070. if (cg) cg.close();
  3071. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3072. });
  3073. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3074. fs.writeFileSync(
  3075. path.join(tempDir, 'JsonScope.java'),
  3076. `class JsonScope {
  3077. static final int EMPTY_DOCUMENT = 1;
  3078. }
  3079. `
  3080. );
  3081. fs.writeFileSync(
  3082. path.join(tempDir, 'Reader.java'),
  3083. `class Reader {
  3084. private int helper;
  3085. int peek() {
  3086. return JsonScope.EMPTY_DOCUMENT;
  3087. }
  3088. int noop() {
  3089. return this.helper;
  3090. }
  3091. }
  3092. `
  3093. );
  3094. cg = CodeGraph.initSync(tempDir);
  3095. await cg.indexAll();
  3096. cg.resolveReferences();
  3097. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3098. // read — never constructed or called), so before the static-member pass it
  3099. // had no dependents. Editing it now surfaces Reader.java.
  3100. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3101. expect(scope, 'JsonScope indexed').toBeDefined();
  3102. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3103. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3104. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3105. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3106. // should appear as a reference target from peek/noop beyond JsonScope.
  3107. const refTargets = cg
  3108. .getNodesByKind('class')
  3109. .filter((n) => n.name === 'this' || n.name === 'helper');
  3110. expect(refTargets.length).toBe(0);
  3111. });
  3112. it('does not link a static-member read across language families (coincidental name)', async () => {
  3113. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3114. // NOT link to a coincidentally same-named TS class (the cross-language false
  3115. // positive that name-matching produces; `references` edges are language-local).
  3116. fs.writeFileSync(
  3117. path.join(tempDir, 'Build.ts'),
  3118. `export class Build {\n static version = 1;\n}\n`
  3119. );
  3120. fs.writeFileSync(
  3121. path.join(tempDir, 'Device.kt'),
  3122. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3123. );
  3124. cg = CodeGraph.initSync(tempDir);
  3125. await cg.indexAll();
  3126. cg.resolveReferences();
  3127. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3128. expect(tsBuild).toBeDefined();
  3129. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3130. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3131. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3132. });
  3133. });
  3134. describe('Cross-language type/import gate (RN name collisions)', () => {
  3135. let tempDir: string;
  3136. let cg: CodeGraph;
  3137. beforeEach(() => {
  3138. tempDir = createTempDir();
  3139. });
  3140. afterEach(() => {
  3141. if (cg) cg.close();
  3142. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3143. });
  3144. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3145. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3146. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3147. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3148. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3149. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3150. // is intentionally NOT imported: a clean relative import would mask the bug
  3151. // by resolving via the import map before the framework strategy can win.
  3152. fs.writeFileSync(
  3153. path.join(tempDir, 'package.json'),
  3154. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3155. );
  3156. fs.writeFileSync(
  3157. path.join(tempDir, 'useTests.ts'),
  3158. `export type TestRunner = { run: () => void };\n`
  3159. );
  3160. fs.writeFileSync(
  3161. path.join(tempDir, 'basic.tsx'),
  3162. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3163. );
  3164. fs.writeFileSync(
  3165. path.join(tempDir, 'TestUtils.kt'),
  3166. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3167. );
  3168. cg = CodeGraph.initSync(tempDir);
  3169. await cg.indexAll();
  3170. cg.resolveReferences();
  3171. const ktRunner = cg
  3172. .getNodesByKind('class')
  3173. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3174. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3175. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3176. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3177. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3178. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3179. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3180. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3181. });
  3182. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3183. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3184. // create a web→apple dependency — but a sibling TS module imported by
  3185. // another TS file (same family) must still resolve (no over-gating).
  3186. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3187. fs.writeFileSync(
  3188. path.join(tempDir, 'widget.ts'),
  3189. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3190. );
  3191. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3192. fs.writeFileSync(
  3193. path.join(tempDir, 'app.ts'),
  3194. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3195. );
  3196. cg = CodeGraph.initSync(tempDir);
  3197. await cg.indexAll();
  3198. cg.resolveReferences();
  3199. const swiftWidget = cg
  3200. .getNodesByKind('class')
  3201. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3202. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3203. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3204. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3205. // Same-family control — the TS Helper must still see its TS dependent.
  3206. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3207. expect(helper, 'TS Helper class').toBeDefined();
  3208. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3209. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3210. });
  3211. });
  3212. describe('Python absolute module import resolution', () => {
  3213. let tempDir: string;
  3214. let cg: CodeGraph;
  3215. beforeEach(() => {
  3216. tempDir = createTempDir();
  3217. });
  3218. afterEach(() => {
  3219. if (cg) cg.close();
  3220. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3221. });
  3222. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3223. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3224. // dotted absolute module import) had no edge to the module file — only
  3225. // `from x import y` was linked — so a module imported by its dotted path
  3226. // looked like nothing depended on it.
  3227. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3228. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3229. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3230. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3231. fs.writeFileSync(
  3232. path.join(tempDir, 'conduit/apps/app.py'),
  3233. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3234. );
  3235. cg = CodeGraph.initSync(tempDir);
  3236. await cg.indexAll();
  3237. cg.resolveReferences();
  3238. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3239. expect(signals, 'signals.py indexed').toBeDefined();
  3240. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3241. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3242. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3243. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3244. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3245. });
  3246. it('Django include() links the root URLconf to the included app urls module', async () => {
  3247. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3248. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3249. // surfaces the project urlconf that mounts them.
  3250. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3251. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3252. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3253. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3254. fs.writeFileSync(
  3255. path.join(tempDir, 'app/urls.py'),
  3256. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3257. );
  3258. fs.writeFileSync(
  3259. path.join(tempDir, 'urls.py'),
  3260. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3261. );
  3262. cg = CodeGraph.initSync(tempDir);
  3263. await cg.indexAll();
  3264. cg.resolveReferences();
  3265. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3266. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3267. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3268. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3269. });
  3270. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3271. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3272. // with same-named modules in sibling packages must resolve via the import's
  3273. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3274. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3275. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3276. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3277. fs.writeFileSync(path.join(tempDir, p), '');
  3278. }
  3279. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3280. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3281. fs.writeFileSync(
  3282. path.join(tempDir, 'app/api/routes/api.py'),
  3283. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3284. );
  3285. cg = CodeGraph.initSync(tempDir);
  3286. await cg.indexAll();
  3287. cg.resolveReferences();
  3288. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3289. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3290. expect(routesAuth && depsAuth).toBeTruthy();
  3291. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3292. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3293. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3294. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3295. });
  3296. });
  3297. describe('Chained method-call resolution (C# extension methods)', () => {
  3298. let tempDir: string;
  3299. let cg: CodeGraph;
  3300. beforeEach(() => {
  3301. tempDir = createTempDir();
  3302. });
  3303. afterEach(() => {
  3304. if (cg) cg.close();
  3305. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3306. });
  3307. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  3308. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  3309. // static extension method elsewhere. A multi-dot receiver chain matched no
  3310. // method-call pattern before, so the extension method had no caller.
  3311. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  3312. fs.writeFileSync(
  3313. path.join(tempDir, 'cfg/Ext.cs'),
  3314. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  3315. );
  3316. fs.writeFileSync(
  3317. path.join(tempDir, 'Program.cs'),
  3318. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  3319. );
  3320. cg = CodeGraph.initSync(tempDir);
  3321. await cg.indexAll();
  3322. cg.resolveReferences();
  3323. const ext = cg
  3324. .getNodesByKind('method')
  3325. .find((n) => n.name === 'AddCoreServices')
  3326. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  3327. expect(ext, 'AddCoreServices defined').toBeDefined();
  3328. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3329. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  3330. });
  3331. });
  3332. describe('Same-directory include + KMP import resolution', () => {
  3333. let tempDir: string;
  3334. let cg: CodeGraph;
  3335. beforeEach(() => {
  3336. tempDir = createTempDir();
  3337. });
  3338. afterEach(() => {
  3339. if (cg) cg.close();
  3340. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3341. });
  3342. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  3343. // A multi-platform native module has a header of the same basename per
  3344. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  3345. // sibling header — not `apple/Storage.h` (which sorts first and so was
  3346. // picked arbitrarily before, leaving the real local header with 0 deps).
  3347. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  3348. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  3349. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3350. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3351. fs.writeFileSync(
  3352. path.join(tempDir, 'windows', 'Provider.cpp'),
  3353. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  3354. );
  3355. cg = CodeGraph.initSync(tempDir);
  3356. await cg.indexAll();
  3357. cg.resolveReferences();
  3358. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  3359. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  3360. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  3361. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  3362. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3363. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3364. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  3365. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  3366. });
  3367. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  3368. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  3369. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  3370. fs.mkdirSync(common, { recursive: true });
  3371. fs.mkdirSync(android, { recursive: true });
  3372. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  3373. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  3374. fs.writeFileSync(
  3375. path.join(common, 'Db.kt'),
  3376. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  3377. );
  3378. cg = CodeGraph.initSync(tempDir);
  3379. await cg.indexAll();
  3380. cg.resolveReferences();
  3381. const expectCtx = cg
  3382. .getNodesByKind('class')
  3383. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  3384. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  3385. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3386. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  3387. });
  3388. });
  3389. describe('Objective-C messages, class receivers, and #import', () => {
  3390. let tempDir: string;
  3391. let cg: CodeGraph;
  3392. beforeEach(() => {
  3393. tempDir = createTempDir();
  3394. });
  3395. afterEach(() => {
  3396. if (cg) cg.close();
  3397. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3398. });
  3399. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  3400. fs.writeFileSync(
  3401. path.join(tempDir, 'SDImageCache.h'),
  3402. `#import <Foundation/Foundation.h>
  3403. @interface SDImageCache : NSObject
  3404. + (instancetype)sharedCache;
  3405. + (void)storeImage:(NSString *)key;
  3406. @end
  3407. `
  3408. );
  3409. fs.writeFileSync(
  3410. path.join(tempDir, 'SDImageCache.m'),
  3411. `#import "SDImageCache.h"
  3412. @implementation SDImageCache
  3413. + (instancetype)sharedCache { return nil; }
  3414. + (void)storeImage:(NSString *)key { }
  3415. @end
  3416. `
  3417. );
  3418. fs.writeFileSync(
  3419. path.join(tempDir, 'SDManager.m'),
  3420. `#import "SDImageCache.h"
  3421. @interface SDManager : NSObject
  3422. @end
  3423. @implementation SDManager
  3424. - (void)run {
  3425. [SDImageCache sharedCache];
  3426. [SDImageCache storeImage:@"k"];
  3427. }
  3428. @end
  3429. `
  3430. );
  3431. cg = CodeGraph.initSync(tempDir);
  3432. await cg.indexAll();
  3433. cg.resolveReferences();
  3434. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  3435. // to the `storeImage:` method — named WITH its colon both at the call site
  3436. // and the definition (before the fix the call site dropped the colon).
  3437. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  3438. expect(storeImage, 'storeImage: method').toBeDefined();
  3439. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3440. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3441. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  3442. // SDImageCache class (whose @interface lives in the header).
  3443. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  3444. expect(cache, 'SDImageCache class').toBeDefined();
  3445. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3446. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3447. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  3448. // surfaces both importers.
  3449. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  3450. expect(header, 'SDImageCache.h indexed').toBeDefined();
  3451. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3452. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3453. });
  3454. });
  3455. describe('Full Indexing', () => {
  3456. let tempDir: string;
  3457. beforeEach(() => {
  3458. tempDir = createTempDir();
  3459. });
  3460. afterEach(() => {
  3461. cleanupTempDir(tempDir);
  3462. });
  3463. it('should index a TypeScript file', async () => {
  3464. // Create test file
  3465. const srcDir = path.join(tempDir, 'src');
  3466. fs.mkdirSync(srcDir);
  3467. fs.writeFileSync(
  3468. path.join(srcDir, 'utils.ts'),
  3469. `
  3470. export function add(a: number, b: number): number {
  3471. return a + b;
  3472. }
  3473. export function multiply(a: number, b: number): number {
  3474. return a * b;
  3475. }
  3476. `
  3477. );
  3478. // Initialize and index
  3479. const cg = CodeGraph.initSync(tempDir);
  3480. const result = await cg.indexAll();
  3481. expect(result.success).toBe(true);
  3482. expect(result.filesIndexed).toBe(1);
  3483. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  3484. // Check nodes were stored
  3485. const nodes = cg.getNodesInFile('src/utils.ts');
  3486. expect(nodes.length).toBeGreaterThanOrEqual(2);
  3487. const addFunc = nodes.find((n) => n.name === 'add');
  3488. expect(addFunc).toBeDefined();
  3489. expect(addFunc?.kind).toBe('function');
  3490. cg.close();
  3491. });
  3492. it('should index multiple files', async () => {
  3493. // Create test files
  3494. const srcDir = path.join(tempDir, 'src');
  3495. fs.mkdirSync(srcDir);
  3496. fs.writeFileSync(
  3497. path.join(srcDir, 'math.ts'),
  3498. `export function add(a: number, b: number) { return a + b; }`
  3499. );
  3500. fs.writeFileSync(
  3501. path.join(srcDir, 'string.ts'),
  3502. `export function capitalize(s: string) { return s.toUpperCase(); }`
  3503. );
  3504. // Initialize and index
  3505. const cg = CodeGraph.initSync(tempDir);
  3506. const result = await cg.indexAll();
  3507. expect(result.success).toBe(true);
  3508. expect(result.filesIndexed).toBe(2);
  3509. const files = cg.getFiles();
  3510. expect(files.length).toBe(2);
  3511. cg.close();
  3512. });
  3513. it('should track file hashes for incremental updates', async () => {
  3514. // Create initial file
  3515. const srcDir = path.join(tempDir, 'src');
  3516. fs.mkdirSync(srcDir);
  3517. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  3518. // Initialize and index
  3519. const cg = CodeGraph.initSync(tempDir);
  3520. await cg.indexAll();
  3521. // Check file is tracked
  3522. const file = cg.getFile('src/main.ts');
  3523. expect(file).toBeDefined();
  3524. expect(file?.contentHash).toBeDefined();
  3525. // Modify file
  3526. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  3527. // Check for changes
  3528. const changes = cg.getChangedFiles();
  3529. expect(changes.modified).toContain('src/main.ts');
  3530. cg.close();
  3531. });
  3532. it('should sync and detect changes', async () => {
  3533. // Create initial file
  3534. const srcDir = path.join(tempDir, 'src');
  3535. fs.mkdirSync(srcDir);
  3536. fs.writeFileSync(
  3537. path.join(srcDir, 'main.ts'),
  3538. `export function original() { return 1; }`
  3539. );
  3540. // Initialize and index
  3541. const cg = CodeGraph.initSync(tempDir);
  3542. await cg.indexAll();
  3543. const initialNodes = cg.getNodesInFile('src/main.ts');
  3544. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  3545. // Modify file
  3546. fs.writeFileSync(
  3547. path.join(srcDir, 'main.ts'),
  3548. `export function updated() { return 2; }`
  3549. );
  3550. // Sync
  3551. const syncResult = await cg.sync();
  3552. expect(syncResult.filesModified).toBe(1);
  3553. // Check nodes were updated
  3554. const updatedNodes = cg.getNodesInFile('src/main.ts');
  3555. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  3556. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  3557. cg.close();
  3558. });
  3559. it('should count file-level tracked YAML files as indexed', async () => {
  3560. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3561. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  3562. const cg = CodeGraph.initSync(tempDir);
  3563. const result = await cg.indexAll();
  3564. expect(result.success).toBe(true);
  3565. expect(result.filesIndexed).toBe(2);
  3566. expect(result.filesSkipped).toBe(0);
  3567. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  3568. cg.close();
  3569. });
  3570. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  3571. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3572. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3573. const cg = CodeGraph.initSync(tempDir);
  3574. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  3575. expect(result.success).toBe(true);
  3576. expect(result.filesIndexed).toBe(2);
  3577. expect(result.filesSkipped).toBe(0);
  3578. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3579. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  3580. cg.close();
  3581. });
  3582. it('should count file-level tracked .properties files as indexed', async () => {
  3583. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3584. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  3585. const cg = CodeGraph.initSync(tempDir);
  3586. const result = await cg.indexAll();
  3587. expect(result.success).toBe(true);
  3588. expect(result.filesIndexed).toBe(2);
  3589. expect(result.filesSkipped).toBe(0);
  3590. cg.close();
  3591. });
  3592. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  3593. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3594. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3595. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3596. const cg = CodeGraph.initSync(tempDir);
  3597. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  3598. expect(result.success).toBe(true);
  3599. expect(result.filesIndexed).toBe(3);
  3600. expect(result.filesSkipped).toBe(0);
  3601. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3602. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  3603. cg.close();
  3604. });
  3605. });
  3606. describe('Path Normalization', () => {
  3607. it('should convert backslashes to forward slashes', () => {
  3608. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  3609. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  3610. });
  3611. it('should leave forward-slash paths unchanged', () => {
  3612. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  3613. });
  3614. it('should handle empty string', () => {
  3615. expect(normalizePath('')).toBe('');
  3616. });
  3617. });
  3618. describe('Directory Exclusion', () => {
  3619. let tempDir: string;
  3620. beforeEach(() => {
  3621. tempDir = createTempDir();
  3622. });
  3623. afterEach(() => {
  3624. cleanupTempDir(tempDir);
  3625. });
  3626. it('should exclude directories listed in .gitignore', () => {
  3627. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  3628. const srcDir = path.join(tempDir, 'src');
  3629. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  3630. fs.mkdirSync(srcDir, { recursive: true });
  3631. fs.mkdirSync(nmDir, { recursive: true });
  3632. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3633. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3634. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3635. const files = scanDirectory(tempDir);
  3636. expect(files).toContain('src/index.ts');
  3637. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3638. });
  3639. it('should exclude nested node_modules via a root .gitignore', () => {
  3640. // A trailing-slash pattern with no leading slash matches at any depth.
  3641. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  3642. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  3643. fs.mkdirSync(srcDir, { recursive: true });
  3644. fs.mkdirSync(nmDir, { recursive: true });
  3645. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3646. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3647. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3648. const files = scanDirectory(tempDir);
  3649. expect(files).toContain('packages/app/src/index.ts');
  3650. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3651. });
  3652. it('should apply a nested .gitignore only to its own subtree', () => {
  3653. const appSrc = path.join(tempDir, 'app', 'src');
  3654. fs.mkdirSync(appSrc, { recursive: true });
  3655. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  3656. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  3657. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  3658. // A sibling with the same name outside app/ must NOT be ignored.
  3659. const otherDir = path.join(tempDir, 'other', 'src');
  3660. fs.mkdirSync(otherDir, { recursive: true });
  3661. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  3662. const files = scanDirectory(tempDir);
  3663. expect(files).toContain('app/src/keep.ts');
  3664. expect(files).not.toContain('app/src/skip.ts');
  3665. expect(files).toContain('other/src/skip.ts');
  3666. });
  3667. it('should always skip .git directories', () => {
  3668. const srcDir = path.join(tempDir, 'src');
  3669. const gitDir = path.join(tempDir, '.git', 'objects');
  3670. fs.mkdirSync(srcDir, { recursive: true });
  3671. fs.mkdirSync(gitDir, { recursive: true });
  3672. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3673. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  3674. const files = scanDirectory(tempDir);
  3675. expect(files).toContain('src/index.ts');
  3676. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  3677. });
  3678. it('should return forward-slash paths on all platforms', () => {
  3679. const srcDir = path.join(tempDir, 'src', 'components');
  3680. fs.mkdirSync(srcDir, { recursive: true });
  3681. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  3682. const files = scanDirectory(tempDir);
  3683. expect(files.length).toBe(1);
  3684. expect(files[0]).toBe('src/components/Button.tsx');
  3685. expect(files[0]).not.toContain('\\');
  3686. });
  3687. });
  3688. describe('Git Submodules', () => {
  3689. let tempDir: string;
  3690. beforeEach(() => {
  3691. tempDir = createTempDir();
  3692. });
  3693. afterEach(() => {
  3694. cleanupTempDir(tempDir);
  3695. });
  3696. it('should index files inside git submodules (issue #147)', async () => {
  3697. const { execFileSync } = await import('child_process');
  3698. const git = (cwd: string, ...args: string[]) =>
  3699. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3700. // Build a separate "library" repo to use as a submodule source.
  3701. const libDir = path.join(tempDir, '_lib');
  3702. fs.mkdirSync(libDir, { recursive: true });
  3703. git(libDir, 'init', '-q');
  3704. git(libDir, 'config', 'user.email', 'test@test.com');
  3705. git(libDir, 'config', 'user.name', 'Test');
  3706. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  3707. git(libDir, 'add', '-A');
  3708. git(libDir, 'commit', '-q', '-m', 'lib init');
  3709. // Build the main repo and add the lib repo as a submodule.
  3710. const mainDir = path.join(tempDir, 'main');
  3711. fs.mkdirSync(mainDir, { recursive: true });
  3712. git(mainDir, 'init', '-q');
  3713. git(mainDir, 'config', 'user.email', 'test@test.com');
  3714. git(mainDir, 'config', 'user.name', 'Test');
  3715. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  3716. git(mainDir, 'add', '-A');
  3717. git(mainDir, 'commit', '-q', '-m', 'app init');
  3718. // protocol.file.allow=always is required to add a local-path submodule on
  3719. // recent git versions (CVE-2022-39253 mitigation).
  3720. execFileSync(
  3721. 'git',
  3722. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  3723. { cwd: mainDir, stdio: 'pipe' }
  3724. );
  3725. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  3726. const files = scanDirectory(mainDir);
  3727. expect(files).toContain('app.ts');
  3728. expect(files).toContain('libs/lib/lib.ts');
  3729. });
  3730. });
  3731. describe('Nested non-submodule git repos', () => {
  3732. let tempDir: string;
  3733. beforeEach(() => {
  3734. tempDir = createTempDir();
  3735. });
  3736. afterEach(() => {
  3737. cleanupTempDir(tempDir);
  3738. });
  3739. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  3740. const { execFileSync } = await import('child_process');
  3741. const git = (cwd: string, ...args: string[]) =>
  3742. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3743. // Top-level workspace is itself a git repo, holding no source directly —
  3744. // the CMake "super-repo" layout from the issue.
  3745. const root = path.join(tempDir, 'root');
  3746. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  3747. git(root, 'init', '-q');
  3748. git(root, 'config', 'user.email', 'test@test.com');
  3749. git(root, 'config', 'user.name', 'Test');
  3750. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  3751. // Two independent clones living inside the workspace (NOT submodules):
  3752. // one with committed source, one with only untracked source.
  3753. const sub1 = path.join(root, 'sub_repo1', 'src');
  3754. fs.mkdirSync(sub1, { recursive: true });
  3755. git(path.join(root, 'sub_repo1'), 'init', '-q');
  3756. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  3757. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  3758. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  3759. git(path.join(root, 'sub_repo1'), 'add', '-A');
  3760. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  3761. const sub2 = path.join(root, 'sub_repo2', 'src');
  3762. fs.mkdirSync(sub2, { recursive: true });
  3763. git(path.join(root, 'sub_repo2'), 'init', '-q');
  3764. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  3765. const files = scanDirectory(root);
  3766. // Both committed and untracked source from the nested repos must be found.
  3767. expect(files).toContain('sub_repo1/src/one.ts');
  3768. expect(files).toContain('sub_repo2/src/two.ts');
  3769. });
  3770. it('should respect each embedded repo\'s own .gitignore', async () => {
  3771. const { execFileSync } = await import('child_process');
  3772. const git = (cwd: string, ...args: string[]) =>
  3773. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3774. const root = path.join(tempDir, 'root');
  3775. fs.mkdirSync(root, { recursive: true });
  3776. git(root, 'init', '-q');
  3777. const sub = path.join(root, 'sub_repo', 'src');
  3778. fs.mkdirSync(sub, { recursive: true });
  3779. git(path.join(root, 'sub_repo'), 'init', '-q');
  3780. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  3781. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  3782. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  3783. const files = scanDirectory(root);
  3784. expect(files).toContain('sub_repo/src/real.ts');
  3785. expect(files).not.toContain('sub_repo/src/generated.ts');
  3786. });
  3787. });
  3788. // =============================================================================
  3789. // Scala
  3790. // =============================================================================
  3791. describe('Scala Extraction', () => {
  3792. describe('Language detection', () => {
  3793. it('should detect Scala files', () => {
  3794. expect(detectLanguage('Main.scala')).toBe('scala');
  3795. expect(detectLanguage('script.sc')).toBe('scala');
  3796. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  3797. });
  3798. it('should report Scala as supported', () => {
  3799. expect(isLanguageSupported('scala')).toBe(true);
  3800. expect(getSupportedLanguages()).toContain('scala');
  3801. });
  3802. });
  3803. describe('Class extraction', () => {
  3804. it('should extract class definitions', () => {
  3805. const code = `
  3806. class UserService(private val repo: UserRepository) {
  3807. def findUser(id: String): Option[String] = Some(id)
  3808. }
  3809. `;
  3810. const result = extractFromSource('UserService.scala', code);
  3811. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  3812. expect(cls).toBeDefined();
  3813. expect(cls?.language).toBe('scala');
  3814. });
  3815. it('should extract object definitions as class kind', () => {
  3816. const code = `
  3817. object DatabaseConfig {
  3818. val url = "jdbc:postgresql://localhost/mydb"
  3819. }
  3820. `;
  3821. const result = extractFromSource('Config.scala', code);
  3822. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  3823. expect(obj).toBeDefined();
  3824. });
  3825. it('should extract trait definitions as trait kind', () => {
  3826. const code = `
  3827. trait Repository[A] {
  3828. def findById(id: String): Option[A]
  3829. def save(entity: A): Unit
  3830. }
  3831. `;
  3832. const result = extractFromSource('Repository.scala', code);
  3833. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  3834. expect(trait_).toBeDefined();
  3835. });
  3836. });
  3837. describe('Method and function extraction', () => {
  3838. it('should extract method definitions inside a class', () => {
  3839. const code = `
  3840. class Calculator {
  3841. def add(a: Int, b: Int): Int = a + b
  3842. def divide(a: Double, b: Double): Double = a / b
  3843. }
  3844. `;
  3845. const result = extractFromSource('Calculator.scala', code);
  3846. const methods = result.nodes.filter((n) => n.kind === 'method');
  3847. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  3848. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  3849. });
  3850. it('should extract method signatures', () => {
  3851. const code = `
  3852. class Greeter {
  3853. def greet(name: String): String = s"Hello, \${name}!"
  3854. }
  3855. `;
  3856. const result = extractFromSource('Greeter.scala', code);
  3857. const method = result.nodes.find((n) => n.name === 'greet');
  3858. expect(method?.signature).toContain('name: String');
  3859. expect(method?.signature).toContain('String');
  3860. });
  3861. it('should extract top-level function definitions as functions', () => {
  3862. const code = `
  3863. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  3864. def greet(name: String): String = s"Hello, \${name}!"
  3865. `;
  3866. const result = extractFromSource('utils.scala', code);
  3867. const fns = result.nodes.filter((n) => n.kind === 'function');
  3868. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  3869. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  3870. });
  3871. });
  3872. describe('Val and var extraction', () => {
  3873. it('should extract val inside a class as field', () => {
  3874. const code = `
  3875. class Config {
  3876. val timeout: Int = 30
  3877. val host: String = "localhost"
  3878. }
  3879. `;
  3880. const result = extractFromSource('Config.scala', code);
  3881. const fields = result.nodes.filter((n) => n.kind === 'field');
  3882. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  3883. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  3884. });
  3885. it('should extract var inside a class as field', () => {
  3886. const code = `
  3887. class Counter {
  3888. var count: Int = 0
  3889. }
  3890. `;
  3891. const result = extractFromSource('Counter.scala', code);
  3892. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  3893. expect(field).toBeDefined();
  3894. });
  3895. it('should extract top-level val as constant', () => {
  3896. const code = `
  3897. val MaxConnections: Int = 100
  3898. val DefaultTimeout = 30
  3899. `;
  3900. const result = extractFromSource('constants.scala', code);
  3901. const consts = result.nodes.filter((n) => n.kind === 'constant');
  3902. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  3903. });
  3904. it('should extract top-level var as variable', () => {
  3905. const code = `
  3906. var retries: Int = 3
  3907. `;
  3908. const result = extractFromSource('state.scala', code);
  3909. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  3910. expect(v).toBeDefined();
  3911. });
  3912. it('should include type in val/var signature', () => {
  3913. const code = `
  3914. class Service {
  3915. val timeout: Int = 30
  3916. }
  3917. `;
  3918. const result = extractFromSource('Service.scala', code);
  3919. const field = result.nodes.find((n) => n.name === 'timeout');
  3920. expect(field?.signature).toContain('timeout');
  3921. expect(field?.signature).toContain('Int');
  3922. });
  3923. });
  3924. describe('Enum extraction', () => {
  3925. it('should extract enum definitions', () => {
  3926. const code = `
  3927. enum Color:
  3928. case Red
  3929. case Green
  3930. case Blue
  3931. `;
  3932. const result = extractFromSource('Color.scala', code);
  3933. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  3934. expect(enumNode).toBeDefined();
  3935. });
  3936. it('should extract enum cases as enum_member', () => {
  3937. const code = `
  3938. enum Direction:
  3939. case North
  3940. case South
  3941. case East
  3942. case West
  3943. `;
  3944. const result = extractFromSource('Direction.scala', code);
  3945. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3946. expect(members.find((m) => m.name === 'North')).toBeDefined();
  3947. expect(members.find((m) => m.name === 'South')).toBeDefined();
  3948. expect(members.length).toBeGreaterThanOrEqual(4);
  3949. });
  3950. });
  3951. describe('Type alias extraction', () => {
  3952. it('should extract type aliases', () => {
  3953. const code = `
  3954. type UserId = String
  3955. type UserMap = Map[String, String]
  3956. `;
  3957. const result = extractFromSource('types.scala', code);
  3958. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3959. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  3960. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  3961. });
  3962. });
  3963. describe('Import extraction', () => {
  3964. it('should extract import declarations', () => {
  3965. const code = `
  3966. import scala.collection.mutable.ListBuffer
  3967. import scala.concurrent.Future
  3968. `;
  3969. const result = extractFromSource('imports.scala', code);
  3970. const imports = result.nodes.filter((n) => n.kind === 'import');
  3971. expect(imports.length).toBeGreaterThanOrEqual(2);
  3972. });
  3973. });
  3974. describe('Visibility modifiers', () => {
  3975. it('should extract private visibility', () => {
  3976. const code = `
  3977. class Service {
  3978. private val secret: String = "abc"
  3979. private def helper(): Unit = {}
  3980. }
  3981. `;
  3982. const result = extractFromSource('Service.scala', code);
  3983. const secretField = result.nodes.find((n) => n.name === 'secret');
  3984. expect(secretField?.visibility).toBe('private');
  3985. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  3986. expect(helperMethod?.visibility).toBe('private');
  3987. });
  3988. it('should extract protected visibility', () => {
  3989. const code = `
  3990. class Base {
  3991. protected def helperMethod(): Unit = {}
  3992. }
  3993. `;
  3994. const result = extractFromSource('Base.scala', code);
  3995. const method = result.nodes.find((n) => n.name === 'helperMethod');
  3996. expect(method?.visibility).toBe('protected');
  3997. });
  3998. it('should default to public visibility', () => {
  3999. const code = `
  4000. class Greeter {
  4001. def hello(): Unit = {}
  4002. }
  4003. `;
  4004. const result = extractFromSource('Greeter.scala', code);
  4005. const method = result.nodes.find((n) => n.name === 'hello');
  4006. expect(method?.visibility).toBe('public');
  4007. });
  4008. });
  4009. describe('Inheritance', () => {
  4010. it('should extract extends relationships', () => {
  4011. const code = `
  4012. class AdminUser extends User {
  4013. def adminAction(): Unit = {}
  4014. }
  4015. `;
  4016. const result = extractFromSource('AdminUser.scala', code);
  4017. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4018. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  4019. });
  4020. });
  4021. describe('Call extraction', () => {
  4022. it('should extract function call expressions', () => {
  4023. const code = `
  4024. def processData(): Unit = {
  4025. val result = computeResult()
  4026. println(result)
  4027. }
  4028. `;
  4029. const result = extractFromSource('processor.scala', code);
  4030. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  4031. expect(calls.length).toBeGreaterThan(0);
  4032. });
  4033. });
  4034. });
  4035. describe('Vue Extraction', () => {
  4036. it('should detect Vue files', () => {
  4037. expect(detectLanguage('App.vue')).toBe('vue');
  4038. expect(detectLanguage('components/Button.vue')).toBe('vue');
  4039. expect(isLanguageSupported('vue')).toBe(true);
  4040. });
  4041. it('should extract component node from a Vue SFC', () => {
  4042. const code = `<template>
  4043. <div>{{ message }}</div>
  4044. </template>
  4045. <script>
  4046. export default {
  4047. data() {
  4048. return { message: 'Hello' };
  4049. }
  4050. }
  4051. </script>
  4052. `;
  4053. const result = extractFromSource('HelloWorld.vue', code);
  4054. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4055. expect(componentNode).toBeDefined();
  4056. expect(componentNode?.name).toBe('HelloWorld');
  4057. expect(componentNode?.language).toBe('vue');
  4058. expect(componentNode?.isExported).toBe(true);
  4059. });
  4060. it('should extract functions from <script> block', () => {
  4061. const code = `<template>
  4062. <button @click="handleClick">Click</button>
  4063. </template>
  4064. <script>
  4065. function handleClick() {
  4066. console.log('clicked');
  4067. }
  4068. const count = 0;
  4069. </script>
  4070. `;
  4071. const result = extractFromSource('Button.vue', code);
  4072. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4073. expect(componentNode).toBeDefined();
  4074. expect(componentNode?.name).toBe('Button');
  4075. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  4076. expect(funcNode).toBeDefined();
  4077. expect(funcNode?.language).toBe('vue');
  4078. });
  4079. it('should extract from <script setup lang="ts"> block', () => {
  4080. const code = `<template>
  4081. <div>{{ count }}</div>
  4082. </template>
  4083. <script setup lang="ts">
  4084. import { ref } from 'vue';
  4085. const count = ref(0);
  4086. function increment(): void {
  4087. count.value++;
  4088. }
  4089. </script>
  4090. `;
  4091. const result = extractFromSource('Counter.vue', code);
  4092. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4093. expect(componentNode).toBeDefined();
  4094. expect(componentNode?.name).toBe('Counter');
  4095. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  4096. expect(funcNode).toBeDefined();
  4097. expect(funcNode?.language).toBe('vue');
  4098. // All nodes should be marked as vue language
  4099. for (const node of result.nodes) {
  4100. expect(node.language).toBe('vue');
  4101. }
  4102. });
  4103. it('should extract calls from top-level <script setup> initializers', () => {
  4104. const code = `<template>
  4105. <div>{{ token }}</div>
  4106. </template>
  4107. <script setup lang="ts">
  4108. import { getTokenMp } from './api/upload';
  4109. const token = getTokenMp();
  4110. </script>
  4111. `;
  4112. const result = extractFromSource('Issue425Setup.vue', code);
  4113. const call = result.unresolvedReferences.find(
  4114. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4115. );
  4116. expect(call).toBeDefined();
  4117. });
  4118. it('should extract calls from Vue Options API object methods', () => {
  4119. const code = `<template>
  4120. <button @click="save">Save</button>
  4121. </template>
  4122. <script>
  4123. import { getTokenMp } from './api/upload';
  4124. export default {
  4125. methods: {
  4126. save() {
  4127. return getTokenMp();
  4128. }
  4129. },
  4130. setup() {
  4131. return getTokenMp();
  4132. }
  4133. }
  4134. </script>
  4135. `;
  4136. const result = extractFromSource('Issue425Options.vue', code);
  4137. const calls = result.unresolvedReferences.filter(
  4138. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4139. );
  4140. expect(calls).toHaveLength(2);
  4141. });
  4142. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  4143. const code = `<template>
  4144. <div class="wrap">
  4145. <UserCard :user="u" />
  4146. <my-button>Click</my-button>
  4147. <Transition><span>x</span></Transition>
  4148. </div>
  4149. </template>
  4150. <script setup lang="ts">
  4151. import UserCard from './UserCard.vue';
  4152. import MyButton from './MyButton.vue';
  4153. </script>
  4154. `;
  4155. const result = extractFromSource('Host.vue', code);
  4156. const refs = result.unresolvedReferences
  4157. .filter((r) => r.referenceKind === 'references')
  4158. .map((r) => r.referenceName);
  4159. expect(refs).toContain('UserCard'); // PascalCase tag
  4160. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  4161. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  4162. expect(refs).not.toContain('Div'); // native HTML element skipped
  4163. expect(refs).not.toContain('Span');
  4164. });
  4165. it('should extract from both <script> and <script setup> blocks', () => {
  4166. const code = `<template>
  4167. <div>{{ msg }}</div>
  4168. </template>
  4169. <script>
  4170. export default {
  4171. name: 'DualScript'
  4172. }
  4173. </script>
  4174. <script setup>
  4175. const msg = 'hello';
  4176. function greet() {
  4177. return msg;
  4178. }
  4179. </script>
  4180. `;
  4181. const result = extractFromSource('DualScript.vue', code);
  4182. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4183. expect(componentNode).toBeDefined();
  4184. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  4185. expect(greetFunc).toBeDefined();
  4186. });
  4187. it('should create component node for template-only Vue file', () => {
  4188. const code = `<template>
  4189. <div>Static content</div>
  4190. </template>
  4191. `;
  4192. const result = extractFromSource('Static.vue', code);
  4193. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4194. expect(componentNode).toBeDefined();
  4195. expect(componentNode?.name).toBe('Static');
  4196. expect(componentNode?.language).toBe('vue');
  4197. // Only the component node should exist (no script nodes)
  4198. expect(result.nodes.length).toBe(1);
  4199. });
  4200. it('should create containment edges from component to script nodes', () => {
  4201. const code = `<template>
  4202. <div>{{ value }}</div>
  4203. </template>
  4204. <script setup lang="ts">
  4205. const value = 42;
  4206. </script>
  4207. `;
  4208. const result = extractFromSource('Contained.vue', code);
  4209. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4210. expect(componentNode).toBeDefined();
  4211. // Should have containment edges from component to child nodes
  4212. const containEdges = result.edges.filter(
  4213. (e) => e.source === componentNode!.id && e.kind === 'contains'
  4214. );
  4215. expect(containEdges.length).toBeGreaterThan(0);
  4216. });
  4217. });
  4218. describe('Instantiates + Decorates edge extraction', () => {
  4219. it('emits an instantiates ref for `new Foo()`', () => {
  4220. const code = `
  4221. class Foo {}
  4222. function bootstrap() { return new Foo(); }
  4223. `;
  4224. const result = extractFromSource('app.ts', code);
  4225. const ref = result.unresolvedReferences.find(
  4226. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  4227. );
  4228. expect(ref).toBeDefined();
  4229. });
  4230. it('strips type-argument suffix from generic constructors', () => {
  4231. const code = `
  4232. class Container<T> { constructor(_: T) {} }
  4233. function go() { return new Container<string>('x'); }
  4234. `;
  4235. const result = extractFromSource('app.ts', code);
  4236. const ref = result.unresolvedReferences.find(
  4237. (r) => r.referenceKind === 'instantiates'
  4238. );
  4239. expect(ref).toBeDefined();
  4240. // Container<string> must be normalised to "Container" — otherwise
  4241. // resolution can never match the class node.
  4242. expect(ref!.referenceName).toBe('Container');
  4243. });
  4244. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  4245. const code = `
  4246. const ns = { Foo: class {} };
  4247. function go() { return new ns.Foo(); }
  4248. `;
  4249. const result = extractFromSource('app.ts', code);
  4250. const ref = result.unresolvedReferences.find(
  4251. (r) => r.referenceKind === 'instantiates'
  4252. );
  4253. // We can't always resolve which Foo, but the name should be the
  4254. // simple identifier so name-matching has a chance.
  4255. expect(ref?.referenceName).toBe('Foo');
  4256. });
  4257. it('emits a decorates ref for `@Foo class X {}`', () => {
  4258. const code = `
  4259. function Foo(_arg: string) { return (cls: any) => cls; }
  4260. @Foo('x')
  4261. class X {}
  4262. `;
  4263. const result = extractFromSource('app.ts', code);
  4264. const decorClass = result.unresolvedReferences.find(
  4265. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  4266. );
  4267. expect(decorClass).toBeDefined();
  4268. });
  4269. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  4270. // Regression: the sibling-walk must stop at the first non-
  4271. // decorator separator. `@A class Foo {} @B class Bar {}` must
  4272. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  4273. // `decorates(Bar, A)`.
  4274. const code = `
  4275. function A(cls: any) { return cls; }
  4276. function B(cls: any) { return cls; }
  4277. @A
  4278. class Foo {}
  4279. @B
  4280. class Bar {}
  4281. `;
  4282. const result = extractFromSource('app.ts', code);
  4283. const decoratesEdges = result.unresolvedReferences.filter(
  4284. (r) => r.referenceKind === 'decorates'
  4285. );
  4286. // Exactly one decorates ref per decorated class, no cross-attribution.
  4287. const fromBar = decoratesEdges.filter((r) =>
  4288. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  4289. );
  4290. expect(fromBar.length).toBe(1);
  4291. expect(fromBar[0]!.referenceName).toBe('B');
  4292. });
  4293. it('emits a decorates ref for `@Foo method() {}`', () => {
  4294. const code = `
  4295. function Get(p: string) { return (t: any, k: string) => t; }
  4296. class Svc {
  4297. @Get('/x') method() { return 1; }
  4298. }
  4299. `;
  4300. const result = extractFromSource('app.ts', code);
  4301. const decorMethod = result.unresolvedReferences.find(
  4302. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  4303. );
  4304. expect(decorMethod).toBeDefined();
  4305. // The decorated symbol must be `method`, not the constructor or class.
  4306. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  4307. expect(decoratedNode?.name).toBe('method');
  4308. });
  4309. });
  4310. // =============================================================================
  4311. // Lua
  4312. // =============================================================================
  4313. describe('Lua Extraction', () => {
  4314. describe('Language detection', () => {
  4315. it('should detect Lua files', () => {
  4316. expect(detectLanguage('init.lua')).toBe('lua');
  4317. expect(detectLanguage('src/util.lua')).toBe('lua');
  4318. });
  4319. it('should report Lua as supported', () => {
  4320. expect(isLanguageSupported('lua')).toBe(true);
  4321. expect(getSupportedLanguages()).toContain('lua');
  4322. });
  4323. });
  4324. describe('Function extraction', () => {
  4325. it('should extract global and local functions', () => {
  4326. const code = `
  4327. function configure(opts) return opts end
  4328. local function helper(x) return x * 2 end
  4329. `;
  4330. const result = extractFromSource('init.lua', code);
  4331. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4332. expect(funcs).toContain('configure');
  4333. expect(funcs).toContain('helper');
  4334. const configure = result.nodes.find((n) => n.name === 'configure');
  4335. expect(configure?.language).toBe('lua');
  4336. expect(configure?.signature).toBe('(opts)');
  4337. });
  4338. it('should split table/method functions into a receiver and method name', () => {
  4339. const code = `
  4340. function M.connect(host, port) return host end
  4341. function M:send(data) return self end
  4342. `;
  4343. const result = extractFromSource('init.lua', code);
  4344. const methods = result.nodes.filter((n) => n.kind === 'method');
  4345. const connect = methods.find((m) => m.name === 'connect');
  4346. expect(connect?.qualifiedName).toBe('M::connect');
  4347. const send = methods.find((m) => m.name === 'send');
  4348. expect(send?.qualifiedName).toBe('M::send');
  4349. });
  4350. });
  4351. describe('Variable extraction', () => {
  4352. it('should extract local variable declarations', () => {
  4353. const code = `
  4354. local M = {}
  4355. local count = 0
  4356. `;
  4357. const result = extractFromSource('mod.lua', code);
  4358. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4359. expect(vars).toContain('M');
  4360. expect(vars).toContain('count');
  4361. });
  4362. });
  4363. describe('Import extraction (require)', () => {
  4364. it('should extract require() in local declarations and bare calls', () => {
  4365. const code = `
  4366. local socket = require("socket")
  4367. local http = require "resty.http"
  4368. require("side.effect")
  4369. `;
  4370. const result = extractFromSource('net.lua', code);
  4371. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4372. expect(imports).toContain('socket');
  4373. expect(imports).toContain('resty.http');
  4374. expect(imports).toContain('side.effect');
  4375. const ref = result.unresolvedReferences.find(
  4376. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  4377. );
  4378. expect(ref).toBeDefined();
  4379. });
  4380. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  4381. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  4382. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  4383. // by extracting several sources in sequence and asserting the LAST still works.
  4384. it('should keep extracting require across many sequential parses', () => {
  4385. let last;
  4386. for (let i = 0; i < 8; i++) {
  4387. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  4388. }
  4389. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4390. expect(imports).toContain('module.7');
  4391. });
  4392. });
  4393. describe('Call extraction', () => {
  4394. it('should record intra-file calls as resolvable references', () => {
  4395. const code = `
  4396. local function helper(x) return x end
  4397. local function run(y) return helper(y) end
  4398. `;
  4399. const result = extractFromSource('calls.lua', code);
  4400. const call = result.unresolvedReferences.find(
  4401. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  4402. );
  4403. expect(call).toBeDefined();
  4404. });
  4405. });
  4406. });
  4407. // =============================================================================
  4408. // Luau (typed superset of Lua — https://luau.org)
  4409. // =============================================================================
  4410. describe('Luau Extraction', () => {
  4411. describe('Language detection', () => {
  4412. it('should detect Luau files', () => {
  4413. expect(detectLanguage('init.luau')).toBe('luau');
  4414. expect(detectLanguage('src/Client.luau')).toBe('luau');
  4415. });
  4416. it('should report Luau as supported', () => {
  4417. expect(isLanguageSupported('luau')).toBe(true);
  4418. expect(getSupportedLanguages()).toContain('luau');
  4419. });
  4420. });
  4421. describe('Type aliases', () => {
  4422. it('should extract `type` and `export type` definitions', () => {
  4423. const code = `
  4424. export type Vector = { x: number, y: number }
  4425. type Handler = (msg: string) -> boolean
  4426. `;
  4427. const result = extractFromSource('types.luau', code);
  4428. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4429. const vector = aliases.find((a) => a.name === 'Vector');
  4430. expect(vector).toBeDefined();
  4431. expect(vector?.isExported).toBe(true);
  4432. const handler = aliases.find((a) => a.name === 'Handler');
  4433. expect(handler).toBeDefined();
  4434. expect(handler?.isExported).toBe(false);
  4435. });
  4436. });
  4437. describe('Typed functions and methods', () => {
  4438. it('should capture typed signatures and split methods by receiver', () => {
  4439. const code = `
  4440. function configure(opts: { debug: boolean }): boolean
  4441. return opts.debug
  4442. end
  4443. function Client:fetch(path: string): Response
  4444. return path
  4445. end
  4446. `;
  4447. const result = extractFromSource('client.luau', code);
  4448. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  4449. expect(configure?.language).toBe('luau');
  4450. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  4451. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  4452. expect(fetch?.qualifiedName).toBe('Client::fetch');
  4453. });
  4454. });
  4455. describe('Imports and variables', () => {
  4456. it('should extract string and Roblox instance-path require imports', () => {
  4457. const code = `
  4458. local http = require("http")
  4459. local Signal = require(script.Parent.Signal)
  4460. local count = 0
  4461. `;
  4462. const result = extractFromSource('mod.luau', code);
  4463. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4464. expect(imports).toContain('http'); // string require
  4465. expect(imports).toContain('Signal'); // Roblox instance-path require
  4466. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4467. expect(vars).toContain('count');
  4468. });
  4469. });
  4470. });
  4471. // =============================================================================
  4472. // Objective-C
  4473. // =============================================================================
  4474. describe('Objective-C Extraction', () => {
  4475. const sample = `
  4476. #import <Foundation/Foundation.h>
  4477. #import "MyClass.h"
  4478. @interface MyClass : NSObject <NSCopying>
  4479. @property (nonatomic, copy) NSString *name;
  4480. - (void)greet;
  4481. - (void)doThing:(id)x with:(id)y;
  4482. + (instancetype)shared;
  4483. @end
  4484. @implementation MyClass
  4485. - (void)greet {
  4486. NSLog(@"Hello");
  4487. [self doWork];
  4488. }
  4489. - (void)doThing:(id)x with:(id)y {
  4490. [self notify:x];
  4491. }
  4492. + (instancetype)shared {
  4493. return [[MyClass alloc] init];
  4494. }
  4495. @end
  4496. void helperFunction(int count) {
  4497. MyClass *obj = [MyClass shared];
  4498. [obj greet];
  4499. }
  4500. `;
  4501. it('should extract classes, methods, functions, and imports', () => {
  4502. const result = extractFromSource('App.m', sample);
  4503. const classes = result.nodes.filter((n) => n.kind === 'class');
  4504. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  4505. const methods = result.nodes.filter((n) => n.kind === 'method');
  4506. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  4507. const shared = methods.find((m) => m.name === 'shared');
  4508. expect(shared?.isStatic).toBe(true);
  4509. const properties = result.nodes.filter((n) => n.kind === 'property');
  4510. expect(properties.some((p) => p.name === 'name')).toBe(true);
  4511. const functions = result.nodes.filter((n) => n.kind === 'function');
  4512. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  4513. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4514. expect(imports).toContain('Foundation/Foundation.h');
  4515. expect(imports).toContain('MyClass.h');
  4516. });
  4517. it('should record inheritance and protocol conformance', () => {
  4518. const result = extractFromSource('App.m', sample);
  4519. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4520. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  4521. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  4522. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  4523. });
  4524. it('should record message sends and C calls', () => {
  4525. const result = extractFromSource('App.m', sample);
  4526. const calls = result.unresolvedReferences
  4527. .filter((r) => r.referenceKind === 'calls')
  4528. .map((r) => r.referenceName);
  4529. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  4530. });
  4531. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  4532. // Regression for the gap discovered post-#165: message_expression's
  4533. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  4534. // so calls never resolved to multi-part method definitions like
  4535. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  4536. // must match the method-definition name with full keywords + trailing colons.
  4537. const code = `
  4538. @implementation Caller
  4539. - (void)demo {
  4540. NSMutableDictionary *d = [NSMutableDictionary new];
  4541. [d setObject:@"v" forKey:@"k"];
  4542. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  4543. [self touchesBegan:nil withEvent:nil];
  4544. }
  4545. @end
  4546. `;
  4547. const result = extractFromSource('Caller.m', code);
  4548. const calls = result.unresolvedReferences
  4549. .filter((r) => r.referenceKind === 'calls')
  4550. .map((r) => r.referenceName);
  4551. expect(calls).toEqual(
  4552. expect.arrayContaining([
  4553. 'd.setObject:forKey:',
  4554. 'd.setObject:forKey:withRetry:',
  4555. 'touchesBegan:withEvent:',
  4556. ])
  4557. );
  4558. });
  4559. it('should not classify pure C headers with @end in comments as objc', () => {
  4560. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  4561. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  4562. });
  4563. it('should extract protocol declarations', () => {
  4564. const code = `
  4565. @protocol DataSource <NSObject>
  4566. - (NSInteger)numberOfItems;
  4567. @end
  4568. `;
  4569. const result = extractFromSource('DataSource.h', code);
  4570. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  4571. expect(protocol).toBeDefined();
  4572. });
  4573. it('should report Objective-C as supported', () => {
  4574. expect(isLanguageSupported('objc')).toBe(true);
  4575. expect(getSupportedLanguages()).toContain('objc');
  4576. });
  4577. });
  4578. describe('Regression: issue-specific extraction fixes', () => {
  4579. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  4580. const code = `
  4581. define(['dep'], function (dep) {
  4582. function innerHelper(x) { return x + 1; }
  4583. function compute(y) { return innerHelper(y); }
  4584. return { compute: compute };
  4585. });
  4586. `;
  4587. const result = extractFromSource('amd-module.js', code);
  4588. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4589. expect(fns).toContain('innerHelper');
  4590. expect(fns).toContain('compute');
  4591. });
  4592. it('attaches Go methods on generic receivers to their type (#583)', () => {
  4593. const code = `
  4594. package main
  4595. type Stack[T any] struct { items []T }
  4596. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  4597. func (s Stack[T]) Len() int { return len(s.items) }
  4598. `;
  4599. const result = extractFromSource('stack.go', code);
  4600. const methods = result.nodes.filter((n) => n.kind === 'method');
  4601. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  4602. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  4603. });
  4604. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  4605. expect(isSourceFile('mod.mts')).toBe(true);
  4606. expect(isSourceFile('mod.cts')).toBe(true);
  4607. expect(isSourceFile('service.xsjs')).toBe(true);
  4608. expect(isSourceFile('lib.xsjslib')).toBe(true);
  4609. expect(detectLanguage('mod.mts')).toBe('typescript');
  4610. expect(detectLanguage('service.xsjs')).toBe('javascript');
  4611. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  4612. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  4613. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  4614. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  4615. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  4616. });
  4617. });
  4618. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  4619. // An import IS a dependency, but extraction only emits references for calls,
  4620. // instantiations, type annotations, and inheritance — so a symbol imported and
  4621. // then merely re-exported, placed in a registry array, passed as an argument,
  4622. // or used in JSX produced no cross-file edge, leaving the providing file with a
  4623. // false "0 dependents". These tests pin the import/re-export binding linking.
  4624. it('emits an imports reference per named, aliased, and default import binding', () => {
  4625. const code = `
  4626. import { widget, helper as h } from './foo';
  4627. import Thing from './thing';
  4628. import * as NS from './ns';
  4629. export const registry = [widget];
  4630. `;
  4631. const result = extractFromSource('bar.ts', code);
  4632. const names = result.unresolvedReferences
  4633. .filter((r) => r.referenceKind === 'imports')
  4634. .map((r) => r.referenceName);
  4635. expect(names).toContain('widget'); // named import → local name
  4636. expect(names).toContain('h'); // aliased import → local alias
  4637. expect(names).toContain('Thing'); // default import
  4638. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  4639. });
  4640. it('emits an imports reference per re-exported binding', () => {
  4641. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  4642. const names = result.unresolvedReferences
  4643. .filter((r) => r.referenceKind === 'imports')
  4644. .map((r) => r.referenceName);
  4645. // Re-export links the SOURCE-side name, not the local alias.
  4646. expect(names).toContain('alpha');
  4647. expect(names).toContain('beta');
  4648. });
  4649. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  4650. const dir = createTempDir();
  4651. try {
  4652. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4653. fs.writeFileSync(
  4654. path.join(dir, 'src', 'foo.ts'),
  4655. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  4656. );
  4657. // bar uses widget ONLY in an array and re-exports helper — neither is
  4658. // called/typed, so before import-linking bar had no edge to foo at all.
  4659. fs.writeFileSync(
  4660. path.join(dir, 'src', 'bar.ts'),
  4661. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  4662. );
  4663. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4664. await cg.indexAll();
  4665. cg.resolveReferences();
  4666. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4667. cg.destroy();
  4668. } finally {
  4669. cleanupTempDir(dir);
  4670. }
  4671. });
  4672. it('a namespace import touched only via a value-member read still links the module file', async () => {
  4673. const dir = createTempDir();
  4674. try {
  4675. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4676. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  4677. // `foo` is imported as a namespace and used ONLY via a value-member read
  4678. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  4679. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  4680. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  4681. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4682. await cg.indexAll();
  4683. cg.resolveReferences();
  4684. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4685. cg.destroy();
  4686. } finally {
  4687. cleanupTempDir(dir);
  4688. }
  4689. });
  4690. });
  4691. describe('Python import dependency linking (blast-radius recall)', () => {
  4692. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  4693. // name brought in with `from module import X` and then merely stored, used as
  4694. // a decorator/argument, or re-exported through an `__init__.py` produced no
  4695. // cross-file edge — the providing module showed a false "0 dependents".
  4696. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  4697. const code = [
  4698. 'from foo import helper, widget',
  4699. 'from foo import Thing as T',
  4700. 'from . import sibling',
  4701. 'from bar import *',
  4702. ].join('\n');
  4703. const names = extractFromSource('mod.py', code)
  4704. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  4705. .map((r) => r.referenceName);
  4706. expect(names).toContain('helper');
  4707. expect(names).toContain('widget'); // value import
  4708. expect(names).toContain('T'); // aliased import → local name
  4709. expect(names).toContain('sibling'); // `from . import <name>`
  4710. expect(names).not.toContain('*'); // wildcard import has no names
  4711. });
  4712. it('a Python value imported but never called still makes the importer a dependent', async () => {
  4713. const dir = createTempDir();
  4714. try {
  4715. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4716. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  4717. // bar imports widget+helper but only stores widget in a list — nothing is
  4718. // called, so before import-linking bar had no edge to foo.
  4719. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  4720. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4721. await cg.indexAll();
  4722. cg.resolveReferences();
  4723. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  4724. cg.destroy();
  4725. } finally {
  4726. cleanupTempDir(dir);
  4727. }
  4728. });
  4729. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  4730. const dir = createTempDir();
  4731. try {
  4732. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4733. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4734. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  4735. // certs is an imported MODULE (a file), and certs.where() is a qualified
  4736. // call through it — the receiver isn't a symbol, so plain name-matching
  4737. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  4738. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  4739. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4740. await cg.indexAll();
  4741. cg.resolveReferences();
  4742. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4743. cg.destroy();
  4744. } finally {
  4745. cleanupTempDir(dir);
  4746. }
  4747. });
  4748. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  4749. const dir = createTempDir();
  4750. try {
  4751. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4752. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4753. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  4754. // member resolution can't find it — the module-import backstop must still
  4755. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  4756. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  4757. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  4758. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4759. await cg.indexAll();
  4760. cg.resolveReferences();
  4761. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4762. cg.destroy();
  4763. } finally {
  4764. cleanupTempDir(dir);
  4765. }
  4766. });
  4767. });
  4768. describe('Go cross-package composite literals (blast-radius recall)', () => {
  4769. // Go function calls and type references across packages already resolved, but
  4770. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  4771. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  4772. // (gin's render/binding implementations) showed 0 dependents.
  4773. it('links a cross-package struct composite literal to the defining package', async () => {
  4774. const dir = createTempDir();
  4775. try {
  4776. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4777. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4778. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  4779. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  4780. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4781. await cg.indexAll();
  4782. cg.resolveReferences();
  4783. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  4784. cg.destroy();
  4785. } finally {
  4786. cleanupTempDir(dir);
  4787. }
  4788. });
  4789. it('links a composite literal in a package-level var registry', async () => {
  4790. const dir = createTempDir();
  4791. try {
  4792. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4793. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4794. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  4795. // The implementation is registered only in a top-level `var registry = {...}`
  4796. // map literal — the body walker doesn't cover top-level declarations, so this
  4797. // exercises the var-initializer walking added for Go.
  4798. fs.writeFileSync(path.join(dir, 'reg.go'), `package main\n\nimport "example.com/proj/render"\n\ntype R interface { Render() }\n\nvar registry = map[string]R{ "xml": render.XML{} }\n`);
  4799. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4800. await cg.indexAll();
  4801. cg.resolveReferences();
  4802. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  4803. cg.destroy();
  4804. } finally {
  4805. cleanupTempDir(dir);
  4806. }
  4807. });
  4808. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  4809. const dir = createTempDir();
  4810. try {
  4811. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4812. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  4813. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  4814. // `(*Wrapped)` — without normalization it dropped on the floor.
  4815. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  4816. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4817. await cg.indexAll();
  4818. cg.resolveReferences();
  4819. expect(cg.getFileDependents('types.go')).toContain('use.go');
  4820. cg.destroy();
  4821. } finally {
  4822. cleanupTempDir(dir);
  4823. }
  4824. });
  4825. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  4826. const dir = createTempDir();
  4827. try {
  4828. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4829. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  4830. fs.writeFileSync(path.join(dir, 'codec', 'api.go'), `package codec\n\ntype Core interface {\n\tMarshal(v any) ([]byte, error)\n}\n\nvar API Core\n`);
  4831. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  4832. // reached ONLY through the interface (API.Marshal). Without implicit
  4833. // interface satisfaction + dispatch, json.go shows 0 dependents.
  4834. fs.writeFileSync(path.join(dir, 'codec', 'json.go'), `package codec\n\ntype jsonApi struct{}\n\nfunc (j jsonApi) Marshal(v any) ([]byte, error) { return nil, nil }\n\nfunc init() { API = jsonApi{} }\n`);
  4835. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4836. await cg.indexAll();
  4837. cg.resolveReferences();
  4838. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  4839. cg.destroy();
  4840. } finally {
  4841. cleanupTempDir(dir);
  4842. }
  4843. });
  4844. });
  4845. describe('C# records (blast-radius recall)', () => {
  4846. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  4847. // but `record` / `record struct` declarations weren't extracted as types — so
  4848. // every reference, generic-type-argument, and `new` of a record dropped on the
  4849. // floor and the defining file showed 0 dependents. (#237)
  4850. it('extracts a record as a graph node (record class + record struct)', () => {
  4851. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  4852. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4853. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4854. });
  4855. it('resolves references / instantiations of a record across files', async () => {
  4856. const dir = createTempDir();
  4857. try {
  4858. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  4859. // Box is used as a generic type argument and instantiated — both require
  4860. // Box to be a node to resolve.
  4861. fs.writeFileSync(
  4862. path.join(dir, 'use.cs'),
  4863. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  4864. );
  4865. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  4866. await cg.indexAll();
  4867. cg.resolveReferences();
  4868. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  4869. cg.destroy();
  4870. } finally {
  4871. cleanupTempDir(dir);
  4872. }
  4873. });
  4874. });
  4875. describe('Rust cross-module recall', () => {
  4876. function rustProject(files: Record<string, string>): string {
  4877. const dir = createTempDir();
  4878. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  4879. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4880. for (const [rel, content] of Object.entries(files)) {
  4881. const full = path.join(dir, 'src', rel);
  4882. fs.mkdirSync(path.dirname(full), { recursive: true });
  4883. fs.writeFileSync(full, content);
  4884. }
  4885. return dir;
  4886. }
  4887. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  4888. const dir = rustProject({
  4889. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4890. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  4891. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  4892. });
  4893. try {
  4894. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4895. await cg.indexAll();
  4896. cg.resolveReferences();
  4897. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4898. cg.destroy();
  4899. } finally { cleanupTempDir(dir); }
  4900. });
  4901. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  4902. const dir = rustProject({
  4903. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4904. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  4905. // Mine implements Render structurally; reached via &dyn Render dispatch.
  4906. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  4907. });
  4908. try {
  4909. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4910. await cg.indexAll();
  4911. cg.resolveReferences();
  4912. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  4913. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4914. cg.destroy();
  4915. } finally { cleanupTempDir(dir); }
  4916. });
  4917. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  4918. const dir = rustProject({
  4919. 'lib.rs': 'pub mod api;\n',
  4920. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  4921. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  4922. });
  4923. try {
  4924. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4925. await cg.indexAll();
  4926. cg.resolveReferences();
  4927. // The re-export hub depends on the module it re-exports from.
  4928. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  4929. cg.destroy();
  4930. } finally { cleanupTempDir(dir); }
  4931. });
  4932. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  4933. const dir = rustProject({
  4934. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  4935. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  4936. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  4937. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  4938. // send this re-export to fast.rs specifically, not name-match either.
  4939. 'hub.rs': 'pub use crate::fast::read;\n',
  4940. });
  4941. try {
  4942. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4943. await cg.indexAll();
  4944. cg.resolveReferences();
  4945. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  4946. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  4947. cg.destroy();
  4948. } finally { cleanupTempDir(dir); }
  4949. });
  4950. });
  4951. describe('Java annotations (blast-radius recall)', () => {
  4952. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  4953. const dir = createTempDir();
  4954. try {
  4955. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  4956. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  4957. // live inside a `modifiers` node on the class/field/method) must extract.
  4958. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  4959. fs.writeFileSync(
  4960. path.join(dir, 'p', 'User.java'),
  4961. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  4962. );
  4963. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  4964. await cg.indexAll();
  4965. cg.resolveReferences();
  4966. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  4967. cg.destroy();
  4968. } finally { cleanupTempDir(dir); }
  4969. });
  4970. });
  4971. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  4972. it('links a @propertyWrapper usage to the wrapper type', async () => {
  4973. const dir = createTempDir();
  4974. try {
  4975. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  4976. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  4977. // `@Argument` is a Swift attribute on a stored property — it lives in the
  4978. // property's `modifiers` and Swift doesn't extract instance properties as
  4979. // their own nodes, so without the fix the wrapper type has no users.
  4980. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  4981. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  4982. await cg.indexAll();
  4983. cg.resolveReferences();
  4984. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  4985. cg.destroy();
  4986. } finally { cleanupTempDir(dir); }
  4987. });
  4988. });