extraction.test.ts 280 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698
  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, buildDefaultIgnore, discoverEmbeddedRepoRoots, buildScopeIgnore } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars, isSourceFile } from '../src/extraction/grammars';
  13. import { stripCppTemplateArgs, blankCppExportMacros } from '../src/extraction/languages/c-cpp';
  14. import { normalizePath } from '../src/utils';
  15. beforeAll(async () => {
  16. await initGrammars();
  17. await loadAllGrammars();
  18. });
  19. // Create a temporary directory for each test
  20. function createTempDir(): string {
  21. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  22. }
  23. // Clean up temporary directory
  24. function cleanupTempDir(dir: string): void {
  25. if (fs.existsSync(dir)) {
  26. fs.rmSync(dir, { recursive: true, force: true });
  27. }
  28. }
  29. describe('Language Detection', () => {
  30. it('should detect TypeScript files', () => {
  31. expect(detectLanguage('src/index.ts')).toBe('typescript');
  32. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  33. });
  34. it('should detect JavaScript files', () => {
  35. expect(detectLanguage('index.js')).toBe('javascript');
  36. expect(detectLanguage('App.jsx')).toBe('jsx');
  37. expect(detectLanguage('config.mjs')).toBe('javascript');
  38. });
  39. it('should detect Python files', () => {
  40. expect(detectLanguage('main.py')).toBe('python');
  41. });
  42. it('should detect Go files', () => {
  43. expect(detectLanguage('main.go')).toBe('go');
  44. });
  45. it('should detect Rust files', () => {
  46. expect(detectLanguage('lib.rs')).toBe('rust');
  47. });
  48. it('should detect Java files', () => {
  49. expect(detectLanguage('Main.java')).toBe('java');
  50. });
  51. it('should detect C files', () => {
  52. expect(detectLanguage('main.c')).toBe('c');
  53. expect(detectLanguage('utils.h')).toBe('c');
  54. });
  55. it('should detect C++ files', () => {
  56. expect(detectLanguage('main.cpp')).toBe('cpp');
  57. expect(detectLanguage('class.hpp')).toBe('cpp');
  58. });
  59. it('should detect C# files', () => {
  60. expect(detectLanguage('Program.cs')).toBe('csharp');
  61. });
  62. it('should detect PHP files', () => {
  63. expect(detectLanguage('index.php')).toBe('php');
  64. });
  65. it('should detect Ruby files', () => {
  66. expect(detectLanguage('app.rb')).toBe('ruby');
  67. });
  68. it('should detect Swift files', () => {
  69. expect(detectLanguage('ViewController.swift')).toBe('swift');
  70. });
  71. it('should detect Kotlin files', () => {
  72. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  73. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  74. });
  75. it('should detect Dart files', () => {
  76. expect(detectLanguage('main.dart')).toBe('dart');
  77. });
  78. it('should detect Objective-C files', () => {
  79. expect(detectLanguage('AppDelegate.m')).toBe('objc');
  80. expect(detectLanguage('ViewController.mm')).toBe('objc');
  81. const objcHeader = '@interface Foo : NSObject\n@end\n';
  82. expect(detectLanguage('Foo.h', objcHeader)).toBe('objc');
  83. expect(detectLanguage('stdio.h', '#ifndef STDIO_H\nvoid printf();\n#endif\n')).toBe('c');
  84. });
  85. it('should return unknown for unsupported extensions', () => {
  86. expect(detectLanguage('styles.css')).toBe('unknown');
  87. expect(detectLanguage('data.json')).toBe('unknown');
  88. });
  89. });
  90. describe('Language Support', () => {
  91. it('should report supported languages', () => {
  92. expect(isLanguageSupported('typescript')).toBe(true);
  93. expect(isLanguageSupported('python')).toBe(true);
  94. expect(isLanguageSupported('go')).toBe(true);
  95. expect(isLanguageSupported('unknown')).toBe(false);
  96. });
  97. it('should list all supported languages', () => {
  98. const languages = getSupportedLanguages();
  99. expect(languages).toContain('typescript');
  100. expect(languages).toContain('javascript');
  101. expect(languages).toContain('python');
  102. expect(languages).toContain('go');
  103. expect(languages).toContain('rust');
  104. expect(languages).toContain('java');
  105. expect(languages).toContain('csharp');
  106. expect(languages).toContain('php');
  107. expect(languages).toContain('ruby');
  108. expect(languages).toContain('swift');
  109. expect(languages).toContain('kotlin');
  110. expect(languages).toContain('dart');
  111. });
  112. });
  113. describe('TypeScript Extraction', () => {
  114. it('should extract function declarations', () => {
  115. const code = `
  116. export function processPayment(amount: number): Promise<Receipt> {
  117. return stripe.charge(amount);
  118. }
  119. `;
  120. const result = extractFromSource('payment.ts', code);
  121. // File node + function node
  122. const fileNode = result.nodes.find((n) => n.kind === 'file');
  123. expect(fileNode).toBeDefined();
  124. expect(fileNode?.name).toBe('payment.ts');
  125. const funcNode = result.nodes.find((n) => n.kind === 'function');
  126. expect(funcNode).toMatchObject({
  127. kind: 'function',
  128. name: 'processPayment',
  129. language: 'typescript',
  130. isExported: true,
  131. });
  132. expect(funcNode?.signature).toContain('amount: number');
  133. });
  134. it('should extract class declarations', () => {
  135. const code = `
  136. export class PaymentService {
  137. private stripe: StripeClient;
  138. constructor(apiKey: string) {
  139. this.stripe = new StripeClient(apiKey);
  140. }
  141. async charge(amount: number): Promise<Receipt> {
  142. return this.stripe.charge(amount);
  143. }
  144. }
  145. `;
  146. const result = extractFromSource('service.ts', code);
  147. const classNode = result.nodes.find((n) => n.kind === 'class');
  148. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  149. expect(classNode).toBeDefined();
  150. expect(classNode?.name).toBe('PaymentService');
  151. expect(classNode?.isExported).toBe(true);
  152. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  153. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  154. expect(chargeMethod).toBeDefined();
  155. });
  156. it('captures docstrings for export- and const-wrapped declarations (#780)', () => {
  157. const code = `
  158. // plain class control
  159. class Ledger {}
  160. // exported class
  161. export class Invoice {}
  162. // export default
  163. export default function settle() { return true; }
  164. // exported arrow const
  165. export const refund = (amount: number) => amount;
  166. // non-export arrow const
  167. const audit = (amount: number) => amount;
  168. `;
  169. const byName = new Map(extractFromSource('doc.ts', code).nodes.map((n) => [n.name, n]));
  170. expect(byName.get('Ledger')?.docstring).toBe('plain class control'); // control still works
  171. expect(byName.get('Invoice')?.docstring).toBe('exported class');
  172. expect(byName.get('settle')?.docstring).toBe('export default');
  173. expect(byName.get('refund')?.docstring).toBe('exported arrow const');
  174. expect(byName.get('audit')?.docstring).toBe('non-export arrow const');
  175. });
  176. it('does not mis-attribute a class comment to an uncommented member (#780)', () => {
  177. const code = `
  178. // Comment for Box
  179. export class Box {
  180. noComment() {}
  181. // own comment
  182. withComment() {}
  183. }
  184. `;
  185. const byName = new Map(extractFromSource('box.ts', code).nodes.map((n) => [n.name, n]));
  186. expect(byName.get('Box')?.docstring).toBe('Comment for Box');
  187. expect(byName.get('noComment')?.docstring ?? null).toBeNull(); // no over-walk
  188. expect(byName.get('withComment')?.docstring).toBe('own comment');
  189. });
  190. it('captures docstrings for decorated Python declarations, stripping `#` (#780)', () => {
  191. const code = [
  192. '# decorated function',
  193. '@app.route("/x")',
  194. 'def py_handler():',
  195. ' return 1',
  196. '',
  197. '',
  198. '# plain function control',
  199. 'def py_plain():',
  200. ' return 1',
  201. '',
  202. '',
  203. '# decorated class',
  204. '@dataclass',
  205. 'class PyModel:',
  206. ' pass',
  207. '',
  208. ].join('\n');
  209. const byName = new Map(extractFromSource('mod.py', code).nodes.map((n) => [n.name, n]));
  210. expect(byName.get('py_handler')?.docstring).toBe('decorated function');
  211. expect(byName.get('py_plain')?.docstring).toBe('plain function control'); // `#` stripped
  212. expect(byName.get('PyModel')?.docstring).toBe('decorated class');
  213. });
  214. it('cleans comment markers across language styles (#780)', () => {
  215. const doc = (file: string, code: string, name: string) =>
  216. new Map(extractFromSource(file, code).nodes.map((n) => [n.name, n])).get(name)?.docstring;
  217. // Rust doc lines (`///`, `//!`) — the trailing slash used to leak through.
  218. expect(doc('m.rs', '/// rust doc line\nfn rs_fn() {}', 'rs_fn')).toBe('rust doc line');
  219. // Lua line + long-bracket comments.
  220. expect(doc('m.lua', '-- lua line\nfunction lua_fn() end', 'lua_fn')).toBe('lua line');
  221. expect(doc('b.lua', '--[[ lua block ]]\nfunction lua_b() end', 'lua_b')).toBe('lua block');
  222. // Pascal brace and paren-star comments.
  223. const pasUnit = (c: string) =>
  224. `unit U;\ninterface\n${c}\nprocedure P;\nimplementation\nprocedure P;\nbegin\nend;\nend.\n`;
  225. expect(doc('a.pas', pasUnit('{ pascal brace }'), 'P')).toBe('pascal brace');
  226. expect(doc('c.pas', pasUnit('(* pascal paren *)'), 'P')).toBe('pascal paren');
  227. // C block comment still clean (no regression).
  228. expect(doc('m.c', '/* c block */\nvoid c_fn(void) {}', 'c_fn')).toBe('c block');
  229. });
  230. it('should extract interfaces', () => {
  231. const code = `
  232. export interface User {
  233. id: string;
  234. name: string;
  235. email: string;
  236. }
  237. `;
  238. const result = extractFromSource('types.ts', code);
  239. const fileNode = result.nodes.find((n) => n.kind === 'file');
  240. expect(fileNode).toBeDefined();
  241. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  242. expect(ifaceNode).toMatchObject({
  243. kind: 'interface',
  244. name: 'User',
  245. isExported: true,
  246. });
  247. });
  248. it('should extract type references from interface property signatures', () => {
  249. const code = `
  250. import type { IPage } from '../PromoterList';
  251. import type { IOrderField } from '../types';
  252. interface Hprops {
  253. value?: Partial<IPage> & Partial<IOrderField>;
  254. }
  255. `;
  256. const result = extractFromSource('HeaderFilter.ts', code);
  257. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  258. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  259. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  260. });
  261. it('should extract type references from interface method signatures', () => {
  262. const code = `
  263. import type { IPage } from '../PromoterList';
  264. import type { IOrderField } from '../types';
  265. interface MethodForm {
  266. fetchPage(arg: IPage): IOrderField;
  267. }
  268. `;
  269. const result = extractFromSource('MethodForm.ts', code);
  270. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  271. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  272. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  273. });
  274. it('extracts type references from in-body local variable annotations', () => {
  275. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  276. // still depends on Foo. The body walker used to capture calls but never type
  277. // annotations, so impact / `affected` missed the dependency. Must cover
  278. // function, class-method, and object-literal-method bodies — and must NOT
  279. // turn the locals themselves into graph nodes (that would explode the graph).
  280. const code = `
  281. import { Foo } from './types';
  282. export function build(): void {
  283. const items: Foo[] = [];
  284. void items;
  285. }
  286. export class K {
  287. run(): void {
  288. const a: Foo = { x: 1 };
  289. void a;
  290. }
  291. }
  292. export const handler = {
  293. handle(): void {
  294. const b: Foo = { x: 1 };
  295. void b;
  296. },
  297. };
  298. `;
  299. const result = extractFromSource('inbody.ts', code);
  300. const fooRefs = result.unresolvedReferences.filter(
  301. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  302. );
  303. // One per body scope: build(), K.run(), handler.handle().
  304. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  305. // Each reference is attributed to its enclosing function/method node — never
  306. // to a local-variable node, because locals are intentionally not extracted.
  307. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  308. for (const ref of fooRefs) {
  309. const owner = byId.get(ref.fromNodeId);
  310. expect(owner).toBeDefined();
  311. expect(['function', 'method']).toContain(owner!.kind);
  312. }
  313. // The locals (items/a/b) must not leak in as symbols.
  314. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  315. });
  316. it('should track function calls', () => {
  317. const code = `
  318. function main() {
  319. const result = processData();
  320. console.log(result);
  321. }
  322. `;
  323. const result = extractFromSource('main.ts', code);
  324. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  325. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  326. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  327. });
  328. });
  329. describe('Arrow Function Export Extraction', () => {
  330. it('should extract exported arrow functions assigned to const', () => {
  331. const code = `
  332. export const useAuth = (): AuthContextValue => {
  333. return useContext(AuthContext);
  334. };
  335. `;
  336. const result = extractFromSource('hooks.ts', code);
  337. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  338. expect(funcNode).toBeDefined();
  339. expect(funcNode).toMatchObject({
  340. kind: 'function',
  341. name: 'useAuth',
  342. isExported: true,
  343. });
  344. });
  345. it('should extract exported function expressions assigned to const', () => {
  346. const code = `
  347. export const processData = function(input: string): string {
  348. return input.trim();
  349. };
  350. `;
  351. const result = extractFromSource('utils.ts', code);
  352. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  353. expect(funcNode).toBeDefined();
  354. expect(funcNode).toMatchObject({
  355. kind: 'function',
  356. name: 'processData',
  357. isExported: true,
  358. });
  359. });
  360. it('should not extract non-exported arrow functions as exported', () => {
  361. const code = `
  362. const internalHelper = () => {
  363. return 42;
  364. };
  365. `;
  366. const result = extractFromSource('internal.ts', code);
  367. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  368. expect(helperNode).toBeDefined();
  369. expect(helperNode?.isExported).toBeFalsy();
  370. });
  371. it('should still skip truly anonymous arrow functions', () => {
  372. const code = `
  373. const items = [1, 2, 3].map((x) => x * 2);
  374. `;
  375. const result = extractFromSource('anon.ts', code);
  376. // The inline arrow function passed to .map() has no variable_declarator parent
  377. // and should remain anonymous (skipped)
  378. const anonFunctions = result.nodes.filter(
  379. (n) => n.kind === 'function' && n.name === '<anonymous>'
  380. );
  381. expect(anonFunctions).toHaveLength(0);
  382. });
  383. it('should extract multiple exported arrow functions from the same file', () => {
  384. const code = `
  385. export const add = (a: number, b: number): number => a + b;
  386. export const subtract = (a: number, b: number): number => a - b;
  387. const internal = () => 'not exported';
  388. `;
  389. const result = extractFromSource('math.ts', code);
  390. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  391. expect(exported).toHaveLength(2);
  392. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  393. const internalNode = result.nodes.find((n) => n.name === 'internal');
  394. expect(internalNode).toBeDefined();
  395. expect(internalNode?.isExported).toBeFalsy();
  396. });
  397. it('should extract arrow functions in JavaScript files', () => {
  398. const code = `
  399. export const fetchData = async () => {
  400. const response = await fetch('/api/data');
  401. return response.json();
  402. };
  403. `;
  404. const result = extractFromSource('api.js', code);
  405. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  406. expect(funcNode).toBeDefined();
  407. expect(funcNode).toMatchObject({
  408. kind: 'function',
  409. name: 'fetchData',
  410. isExported: true,
  411. });
  412. });
  413. });
  414. describe('Type Alias Extraction', () => {
  415. it('should extract exported type aliases in TypeScript', () => {
  416. const code = `
  417. export type AuthContextValue = {
  418. user: User | null;
  419. login: () => void;
  420. logout: () => void;
  421. };
  422. `;
  423. const result = extractFromSource('types.ts', code);
  424. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  425. expect(typeNode).toMatchObject({
  426. kind: 'type_alias',
  427. name: 'AuthContextValue',
  428. isExported: true,
  429. });
  430. });
  431. it('should extract non-exported type aliases', () => {
  432. const code = `
  433. type InternalState = {
  434. loading: boolean;
  435. error: string | null;
  436. };
  437. `;
  438. const result = extractFromSource('internal.ts', code);
  439. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  440. expect(typeNode).toMatchObject({
  441. kind: 'type_alias',
  442. name: 'InternalState',
  443. isExported: false,
  444. });
  445. });
  446. it('should extract multiple type aliases from the same file', () => {
  447. const code = `
  448. export type UnitSystem = 'metric' | 'imperial';
  449. export type DateFormat = 'ISO' | 'US' | 'EU';
  450. type Internal = string;
  451. `;
  452. const result = extractFromSource('config.ts', code);
  453. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  454. expect(typeAliases).toHaveLength(3);
  455. const exported = typeAliases.filter((n) => n.isExported);
  456. expect(exported).toHaveLength(2);
  457. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  458. });
  459. // A service/contract registry written as a tuple of generic instantiations —
  460. // the names are string-literal type arguments, not declarations, so static
  461. // extraction otherwise never indexes them (issue #634).
  462. it('extracts string-literal contract names from a generic tuple type alias (#634)', () => {
  463. const code = `
  464. interface Service<Name extends string, Req, Resp> { name: Name; }
  465. export type MyServiceList = [
  466. Service<'query_apply_record', { pageNo: number }, { ok: boolean }>,
  467. Service<'apply_confirm', { code: string }, { ok: boolean }>
  468. ];
  469. `;
  470. const result = extractFromSource('services/api.ts', code);
  471. const names = result.nodes.filter(
  472. (n) => n.kind === 'method' && n.qualifiedName.startsWith('MyServiceList::')
  473. );
  474. expect(names.map((n) => n.name).sort()).toEqual(['apply_confirm', 'query_apply_record']);
  475. const queryNode = names.find((n) => n.name === 'query_apply_record');
  476. expect(queryNode?.qualifiedName).toBe('MyServiceList::query_apply_record');
  477. // Signature carries the full contract entry so search results show context.
  478. expect(queryNode?.signature).toContain("Service<'query_apply_record'");
  479. // The string-literal name is contained by the type alias.
  480. const alias = result.nodes.find((n) => n.kind === 'type_alias' && n.name === 'MyServiceList');
  481. const containsEdge = result.edges.find(
  482. (e) => e.kind === 'contains' && e.source === alias?.id && e.target === queryNode?.id
  483. );
  484. expect(containsEdge).toBeDefined();
  485. });
  486. it('does not extract string literals from utility types or nested generics (#634)', () => {
  487. const code = `
  488. interface User { id: string; name: string; }
  489. interface Service<Name extends string, Req, Resp> { name: Name; }
  490. export type Picked = Pick<User, 'id' | 'name'>;
  491. export type Rec = Record<'foo' | 'bar', number>;
  492. // Tuple entry, but the name is a non-identifier route path; the nested Pick's
  493. // 'id' must also stay out (only DIRECT literal args of a tuple's generic count).
  494. export type Routes = [Service<'/api/users', Pick<User, 'id'>, {}>];
  495. // Bare string-literal tuple — not generic type arguments.
  496. export type Names = ['alpha', 'beta'];
  497. `;
  498. const result = extractFromSource('noise.ts', code);
  499. const leaked = result.nodes.filter(
  500. (n) =>
  501. (n.kind === 'method' || n.kind === 'property') &&
  502. ['id', 'name', 'foo', 'bar', 'alpha', 'beta'].includes(n.name)
  503. );
  504. expect(leaked).toEqual([]);
  505. });
  506. });
  507. describe('Exported Variable Extraction', () => {
  508. it('should extract exported const with call expression (Zustand store)', () => {
  509. const code = `
  510. export const useUIStore = create<UIState>((set) => ({
  511. isOpen: false,
  512. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  513. }));
  514. `;
  515. const result = extractFromSource('store.ts', code);
  516. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  517. expect(varNode).toBeDefined();
  518. expect(varNode?.isExported).toBe(true);
  519. });
  520. it('should extract exported const with object literal', () => {
  521. const code = `
  522. export const config = {
  523. apiUrl: 'https://api.example.com',
  524. timeout: 5000,
  525. };
  526. `;
  527. const result = extractFromSource('config.ts', code);
  528. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  529. expect(varNode).toBeDefined();
  530. expect(varNode?.isExported).toBe(true);
  531. });
  532. it('should extract exported const with array literal', () => {
  533. const code = `
  534. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  535. `;
  536. const result = extractFromSource('constants.ts', code);
  537. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  538. expect(varNode).toBeDefined();
  539. expect(varNode?.isExported).toBe(true);
  540. });
  541. it('should extract exported const with primitive value', () => {
  542. const code = `
  543. export const MAX_RETRIES = 3;
  544. export const API_VERSION = "v2";
  545. `;
  546. const result = extractFromSource('constants.ts', code);
  547. const variables = result.nodes.filter((n) => n.kind === 'constant');
  548. expect(variables).toHaveLength(2);
  549. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  550. });
  551. it('should NOT duplicate arrow functions as both function and variable', () => {
  552. const code = `
  553. export const useAuth = () => {
  554. return useContext(AuthContext);
  555. };
  556. `;
  557. const result = extractFromSource('hooks.ts', code);
  558. // Should be extracted as function (from arrow function handler), NOT as variable
  559. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  560. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  561. expect(funcNodes).toHaveLength(1);
  562. expect(varNodes).toHaveLength(0);
  563. });
  564. it('should extract non-exported const as non-exported variable', () => {
  565. const code = `
  566. const internalConfig = {
  567. debug: true,
  568. };
  569. `;
  570. const result = extractFromSource('internal.ts', code);
  571. // Non-exported const at file level should be extracted as a constant (not exported)
  572. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  573. expect(varNodes).toHaveLength(1);
  574. expect(varNodes[0]?.isExported).toBeFalsy();
  575. });
  576. it('should extract Zod schema exports', () => {
  577. const code = `
  578. export const userSchema = z.object({
  579. id: z.string(),
  580. name: z.string(),
  581. email: z.string().email(),
  582. });
  583. `;
  584. const result = extractFromSource('schemas.ts', code);
  585. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  586. expect(varNode).toBeDefined();
  587. expect(varNode?.isExported).toBe(true);
  588. });
  589. it('should extract XState machine exports', () => {
  590. const code = `
  591. export const authMachine = createMachine({
  592. id: "auth",
  593. initial: "idle",
  594. states: {
  595. idle: {},
  596. authenticated: {},
  597. },
  598. });
  599. `;
  600. const result = extractFromSource('machine.ts', code);
  601. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  602. expect(varNode).toBeDefined();
  603. expect(varNode?.isExported).toBe(true);
  604. });
  605. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  606. const code = `
  607. import { getTokenMp } from './api/upload';
  608. const token = getTokenMp();
  609. `;
  610. const result = extractFromSource('app.ts', code);
  611. const call = result.unresolvedReferences.find(
  612. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  613. );
  614. expect(call).toBeDefined();
  615. });
  616. });
  617. describe('File Node Extraction', () => {
  618. it('should create a file-kind node for each parsed file', () => {
  619. const code = `
  620. export function greet(name: string): string {
  621. return "Hello " + name;
  622. }
  623. `;
  624. const result = extractFromSource('greeter.ts', code);
  625. const fileNode = result.nodes.find((n) => n.kind === 'file');
  626. expect(fileNode).toBeDefined();
  627. expect(fileNode?.name).toBe('greeter.ts');
  628. expect(fileNode?.filePath).toBe('greeter.ts');
  629. expect(fileNode?.language).toBe('typescript');
  630. expect(fileNode?.startLine).toBe(1);
  631. });
  632. it('should create file nodes for Python files', () => {
  633. const code = `
  634. def main():
  635. pass
  636. `;
  637. const result = extractFromSource('main.py', code);
  638. const fileNode = result.nodes.find((n) => n.kind === 'file');
  639. expect(fileNode).toBeDefined();
  640. expect(fileNode?.name).toBe('main.py');
  641. expect(fileNode?.language).toBe('python');
  642. });
  643. it('should create containment edges from file node to top-level declarations', () => {
  644. const code = `
  645. export function foo() {}
  646. export function bar() {}
  647. `;
  648. const result = extractFromSource('fns.ts', code);
  649. const fileNode = result.nodes.find((n) => n.kind === 'file');
  650. expect(fileNode).toBeDefined();
  651. // There should be contains edges from the file node to each function
  652. const containsEdges = result.edges.filter(
  653. (e) => e.source === fileNode?.id && e.kind === 'contains'
  654. );
  655. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  656. });
  657. });
  658. describe('Python Extraction', () => {
  659. it('should extract function definitions', () => {
  660. const code = `
  661. def calculate_total(items: list, tax_rate: float) -> float:
  662. """Calculate total with tax."""
  663. subtotal = sum(item.price for item in items)
  664. return subtotal * (1 + tax_rate)
  665. `;
  666. const result = extractFromSource('calc.py', code);
  667. const fileNode = result.nodes.find((n) => n.kind === 'file');
  668. expect(fileNode).toBeDefined();
  669. const funcNode = result.nodes.find((n) => n.kind === 'function');
  670. expect(funcNode).toMatchObject({
  671. kind: 'function',
  672. name: 'calculate_total',
  673. language: 'python',
  674. });
  675. });
  676. it('should extract class definitions', () => {
  677. const code = `
  678. class UserService:
  679. """Service for managing users."""
  680. def __init__(self, db):
  681. self.db = db
  682. def get_user(self, user_id: str) -> User:
  683. return self.db.find_user(user_id)
  684. `;
  685. const result = extractFromSource('service.py', code);
  686. const classNode = result.nodes.find((n) => n.kind === 'class');
  687. expect(classNode).toBeDefined();
  688. expect(classNode?.name).toBe('UserService');
  689. });
  690. });
  691. describe('Go Extraction', () => {
  692. it('should extract function declarations', () => {
  693. const code = `
  694. package main
  695. func ProcessOrder(order Order) (Receipt, error) {
  696. // Process the order
  697. return Receipt{}, nil
  698. }
  699. `;
  700. const result = extractFromSource('main.go', code);
  701. const funcNode = result.nodes.find((n) => n.kind === 'function');
  702. expect(funcNode).toBeDefined();
  703. expect(funcNode?.name).toBe('ProcessOrder');
  704. });
  705. it('should extract method declarations', () => {
  706. const code = `
  707. package main
  708. type Service struct {
  709. db *Database
  710. }
  711. func (s *Service) GetUser(id string) (*User, error) {
  712. return s.db.FindUser(id)
  713. }
  714. `;
  715. const result = extractFromSource('service.go', code);
  716. const methodNode = result.nodes.find((n) => n.kind === 'method');
  717. expect(methodNode).toBeDefined();
  718. expect(methodNode?.name).toBe('GetUser');
  719. });
  720. });
  721. describe('Rust Extraction', () => {
  722. it('should extract function declarations', () => {
  723. const code = `
  724. pub fn process_data(input: &str) -> Result<Output, Error> {
  725. // Process data
  726. Ok(Output::new())
  727. }
  728. `;
  729. const result = extractFromSource('lib.rs', code);
  730. const funcNode = result.nodes.find((n) => n.kind === 'function');
  731. expect(funcNode).toBeDefined();
  732. expect(funcNode?.name).toBe('process_data');
  733. expect(funcNode?.visibility).toBe('public');
  734. });
  735. it('should extract struct declarations', () => {
  736. const code = `
  737. pub struct User {
  738. pub id: String,
  739. pub name: String,
  740. email: String,
  741. }
  742. `;
  743. const result = extractFromSource('models.rs', code);
  744. const structNode = result.nodes.find((n) => n.kind === 'struct');
  745. expect(structNode).toBeDefined();
  746. expect(structNode?.name).toBe('User');
  747. });
  748. it('should extract trait declarations', () => {
  749. const code = `
  750. pub trait Repository {
  751. fn find(&self, id: &str) -> Option<Entity>;
  752. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  753. }
  754. `;
  755. const result = extractFromSource('traits.rs', code);
  756. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  757. expect(traitNode).toBeDefined();
  758. expect(traitNode?.name).toBe('Repository');
  759. });
  760. it('should extract impl Trait for Type as implements edges', () => {
  761. const code = `
  762. pub struct MyCache {}
  763. pub trait Cache {
  764. fn get(&self, key: &str) -> Option<String>;
  765. }
  766. impl Cache for MyCache {
  767. fn get(&self, key: &str) -> Option<String> {
  768. None
  769. }
  770. }
  771. `;
  772. const result = extractFromSource('cache.rs', code);
  773. // Should have an unresolved reference for implements
  774. const implRef = result.unresolvedReferences.find(
  775. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  776. );
  777. expect(implRef).toBeDefined();
  778. // The struct MyCache should be the source
  779. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  780. expect(myCacheNode).toBeDefined();
  781. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  782. });
  783. it('should extract trait supertraits as extends references', () => {
  784. const code = `
  785. pub trait Display {}
  786. pub trait Error: Display {
  787. fn description(&self) -> &str;
  788. }
  789. `;
  790. const result = extractFromSource('error.rs', code);
  791. const extendsRef = result.unresolvedReferences.find(
  792. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  793. );
  794. expect(extendsRef).toBeDefined();
  795. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  796. expect(errorTrait).toBeDefined();
  797. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  798. });
  799. it('should not create implements edges for plain impl blocks', () => {
  800. const code = `
  801. pub struct Counter {
  802. count: u32,
  803. }
  804. impl Counter {
  805. pub fn new() -> Counter {
  806. Counter { count: 0 }
  807. }
  808. pub fn increment(&mut self) {
  809. self.count += 1;
  810. }
  811. }
  812. `;
  813. const result = extractFromSource('counter.rs', code);
  814. // Should have no implements references (no trait involved)
  815. const implRefs = result.unresolvedReferences.filter(
  816. (r) => r.referenceKind === 'implements'
  817. );
  818. expect(implRefs).toHaveLength(0);
  819. });
  820. });
  821. describe('Java Extraction', () => {
  822. it('should extract class declarations', () => {
  823. const code = `
  824. public class UserService {
  825. private final UserRepository repository;
  826. public UserService(UserRepository repository) {
  827. this.repository = repository;
  828. }
  829. public User getUser(String id) {
  830. return repository.findById(id);
  831. }
  832. }
  833. `;
  834. const result = extractFromSource('UserService.java', code);
  835. const classNode = result.nodes.find((n) => n.kind === 'class');
  836. expect(classNode).toBeDefined();
  837. expect(classNode?.name).toBe('UserService');
  838. expect(classNode?.visibility).toBe('public');
  839. });
  840. it('should extract method declarations', () => {
  841. const code = `
  842. public class Calculator {
  843. public static int add(int a, int b) {
  844. return a + b;
  845. }
  846. }
  847. `;
  848. const result = extractFromSource('Calculator.java', code);
  849. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  850. expect(methodNode).toBeDefined();
  851. expect(methodNode?.isStatic).toBe(true);
  852. });
  853. it('wraps top-level declarations in a namespace from package_declaration', () => {
  854. const code = `
  855. package com.example.foo;
  856. public class Bar {
  857. public String greet() { return "hi"; }
  858. }
  859. `;
  860. const result = extractFromSource('Bar.java', code);
  861. const ns = result.nodes.find((n) => n.kind === 'namespace');
  862. expect(ns?.name).toBe('com.example.foo');
  863. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  864. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  865. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  866. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  867. });
  868. it('does not wrap when no package is declared', () => {
  869. const code = `
  870. public class Bar {
  871. public String greet() { return "hi"; }
  872. }
  873. `;
  874. const result = extractFromSource('Bar.java', code);
  875. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  876. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  877. expect(cls?.qualifiedName).toBe('Bar');
  878. });
  879. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  880. // The pattern that breaks the trace through `strategy.foo()` in
  881. // libraries like guava's Splitter: the lambda-returned anonymous
  882. // class overrides abstract methods on the base, but without
  883. // extracting those overrides the interface→impl synthesizer has
  884. // nothing to bridge.
  885. const code = `
  886. package com.example;
  887. abstract class Base {
  888. abstract int compute(int x);
  889. }
  890. public class Factory {
  891. public Base make() {
  892. return new Base() {
  893. @Override
  894. int compute(int x) { return x + 1; }
  895. };
  896. }
  897. }
  898. `;
  899. const result = extractFromSource('Factory.java', code);
  900. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  901. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  902. const compute = result.nodes.find(
  903. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  904. );
  905. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  906. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  907. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  908. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  909. const extendsRef = result.unresolvedReferences.find(
  910. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  911. );
  912. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  913. // The enclosing `make` method still emits an instantiates edge to Base —
  914. // anon extraction must not swallow that signal.
  915. const instantiatesRef = result.unresolvedReferences.find(
  916. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  917. );
  918. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  919. });
  920. it('extracts anonymous-class overrides inside a lambda body', () => {
  921. // The exact guava pattern: a lambda is passed to a constructor, and the
  922. // lambda body returns `new T() { @Override ... }`. The anon class must
  923. // still surface even though it sits inside a lambda_expression node.
  924. const code = `
  925. package com.example;
  926. interface Strategy {
  927. java.util.Iterator<String> iterator(String s);
  928. }
  929. abstract class BaseIter implements java.util.Iterator<String> {
  930. abstract int separatorStart(int start);
  931. }
  932. public class Splitter {
  933. private final Strategy strategy;
  934. public Splitter(Strategy s) { this.strategy = s; }
  935. public static Splitter on(char c) {
  936. return new Splitter((seq) ->
  937. new BaseIter() {
  938. @Override
  939. int separatorStart(int start) { return start + 1; }
  940. @Override public boolean hasNext() { return false; }
  941. @Override public String next() { return null; }
  942. });
  943. }
  944. }
  945. `;
  946. const result = extractFromSource('Splitter.java', code);
  947. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  948. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  949. const sepStart = result.nodes.find(
  950. (n) =>
  951. n.kind === 'method' &&
  952. n.name === 'separatorStart' &&
  953. n.qualifiedName.includes('$anon@')
  954. );
  955. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  956. });
  957. });
  958. describe('C# Extraction', () => {
  959. it('should extract class declarations', () => {
  960. const code = `
  961. public class OrderService
  962. {
  963. private readonly IOrderRepository _repository;
  964. public OrderService(IOrderRepository repository)
  965. {
  966. _repository = repository;
  967. }
  968. public async Task<Order> GetOrderAsync(string id)
  969. {
  970. return await _repository.FindByIdAsync(id);
  971. }
  972. }
  973. `;
  974. const result = extractFromSource('OrderService.cs', code);
  975. const classNode = result.nodes.find((n) => n.kind === 'class');
  976. expect(classNode).toBeDefined();
  977. expect(classNode?.name).toBe('OrderService');
  978. expect(classNode?.visibility).toBe('public');
  979. });
  980. it('indexes every record form with the right kind (#831)', () => {
  981. // The grammar parses ALL record forms as record_declaration — there is no
  982. // record_struct_declaration node — so the value-type forms are told apart
  983. // by their `struct` keyword child. Positional one-liners have no body
  984. // block and must still index (the no-body gate is for C/C++ forward
  985. // declarations, not records).
  986. const code = `
  987. namespace Fixture;
  988. public record SimplePositional(int A);
  989. public record WithBody(int A) { public int DoubleIt() => A * 2; }
  990. public record class ExplicitClassRec(string Name);
  991. public record struct ValueRec(int X);
  992. public readonly record struct ReadonlyRec(int X, int Y);
  993. public record DerivedRec(int A, string B) : SimplePositional(A);
  994. public record GenericRec<T>(T Value);
  995. public partial record PartialRec(int A);
  996. `;
  997. const result = extractFromSource('Records.cs', code);
  998. const kindOf = (name: string) => result.nodes.find((n) => n.name === name)?.kind;
  999. expect(kindOf('SimplePositional')).toBe('class');
  1000. expect(kindOf('WithBody')).toBe('class');
  1001. expect(kindOf('ExplicitClassRec')).toBe('class');
  1002. expect(kindOf('DerivedRec')).toBe('class');
  1003. expect(kindOf('GenericRec')).toBe('class');
  1004. expect(kindOf('PartialRec')).toBe('class');
  1005. // Value-type records are structs, not classes.
  1006. expect(kindOf('ValueRec')).toBe('struct');
  1007. expect(kindOf('ReadonlyRec')).toBe('struct');
  1008. // Members of a bodied record still extract.
  1009. expect(kindOf('DoubleIt')).toBe('method');
  1010. });
  1011. it('indexes primary-constructor classes, including keyed-DI attribute params (#237)', () => {
  1012. // C# 12 primary constructors (`class Foo(IDep dep) { … }`) are parsed
  1013. // natively by the vendored tree-sitter-c-sharp 0.23.x grammar. The worst
  1014. // shape under the previous (older) grammar — an attribute-with-args on a
  1015. // ctor param (`[FromKeyedServices("primary")] …`, the ASP.NET keyed-DI
  1016. // pattern) — used to parse as an ERROR that swallowed the whole class, so
  1017. // the class and all its methods vanished. They now index in every case.
  1018. const code = `
  1019. public class DataService(IMemoryCache cache)
  1020. {
  1021. public void Warm() { }
  1022. }
  1023. public class InstanceService(InstanceManager m, ProfileManager p)
  1024. {
  1025. public void DeployAndLaunchAsync() { }
  1026. public void Deploy() { }
  1027. }
  1028. public partial class UpdateService(int x) : ILifetimeService
  1029. {
  1030. public void Run() { }
  1031. }
  1032. public class K1KeyedDi([FromKeyedServices("primary")] IMemoryCache cache)
  1033. {
  1034. public void Warm() { }
  1035. }
  1036. public record CatalogBrand(int Id, string Name);
  1037. `;
  1038. const result = extractFromSource('Services.cs', code);
  1039. const classNames = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  1040. expect(classNames).toContain('DataService');
  1041. expect(classNames).toContain('InstanceService');
  1042. expect(classNames).toContain('UpdateService'); // partial + base list
  1043. expect(classNames).toContain('K1KeyedDi'); // attribute-arg ctor param — used to vanish entirely
  1044. expect(classNames).toContain('CatalogBrand'); // record
  1045. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1046. expect(methods).toContain('DeployAndLaunchAsync');
  1047. expect(methods).toContain('Deploy');
  1048. expect(methods).toContain('Run');
  1049. });
  1050. it('keeps a class indexable when a nested enum has #if-guarded members (#237)', () => {
  1051. // A `#if` directive inside an enum member list (the multi-targeting pattern
  1052. // in libraries like Newtonsoft.Json) makes the grammar emit an ERROR that,
  1053. // for a nested enum, detaches the enclosing class's member list — dropping
  1054. // most of the class's methods. A pre-parse pass blanks the directive lines
  1055. // (keeping both branches), so the class and all its methods still index.
  1056. const code = `
  1057. public class Reader
  1058. {
  1059. private enum ReadType
  1060. {
  1061. #if HAVE_DATE_TIME_OFFSET
  1062. ReadAsDateTimeOffset,
  1063. #endif
  1064. ReadAsDouble,
  1065. ReadAsString,
  1066. }
  1067. public void Open() { }
  1068. public void Close() { }
  1069. public int ReadInt() { return 0; }
  1070. }
  1071. `;
  1072. const result = extractFromSource('Reader.cs', code);
  1073. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1074. // All three methods after the #if-bearing enum must survive.
  1075. expect(methods).toContain('Open');
  1076. expect(methods).toContain('Close');
  1077. expect(methods).toContain('ReadInt');
  1078. // Both enum branches are kept.
  1079. const enumMembers = result.nodes.filter((n) => n.kind === 'enum_member').map((n) => n.name);
  1080. expect(enumMembers).toContain('ReadAsDateTimeOffset');
  1081. expect(enumMembers).toContain('ReadAsDouble');
  1082. });
  1083. });
  1084. describe('PHP Extraction', () => {
  1085. it('should extract class declarations', () => {
  1086. const code = `<?php
  1087. class UserController
  1088. {
  1089. private UserService $userService;
  1090. public function __construct(UserService $userService)
  1091. {
  1092. $this->userService = $userService;
  1093. }
  1094. public function show(string $id): User
  1095. {
  1096. return $this->userService->find($id);
  1097. }
  1098. }
  1099. `;
  1100. const result = extractFromSource('UserController.php', code);
  1101. const classNode = result.nodes.find((n) => n.kind === 'class');
  1102. expect(classNode).toBeDefined();
  1103. expect(classNode?.name).toBe('UserController');
  1104. });
  1105. it('should extract class inheritance (extends) and interface implementation', () => {
  1106. const code = `<?php
  1107. class ChildController extends BaseController implements Serializable, JsonSerializable
  1108. {
  1109. public function serialize(): string
  1110. {
  1111. return json_encode($this);
  1112. }
  1113. }
  1114. `;
  1115. const result = extractFromSource('ChildController.php', code);
  1116. const classNode = result.nodes.find((n) => n.kind === 'class');
  1117. expect(classNode).toBeDefined();
  1118. expect(classNode?.name).toBe('ChildController');
  1119. const extendsRef = result.unresolvedReferences.find(
  1120. (r) => r.referenceKind === 'extends'
  1121. );
  1122. expect(extendsRef).toBeDefined();
  1123. expect(extendsRef?.referenceName).toBe('BaseController');
  1124. const implementsRefs = result.unresolvedReferences.filter(
  1125. (r) => r.referenceKind === 'implements'
  1126. );
  1127. expect(implementsRefs.length).toBe(2);
  1128. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  1129. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  1130. });
  1131. });
  1132. describe('Swift Extraction', () => {
  1133. it('should extract class declarations', () => {
  1134. const code = `
  1135. public class NetworkManager {
  1136. private let session: URLSession
  1137. public init(session: URLSession = .shared) {
  1138. self.session = session
  1139. }
  1140. public func fetchData(from url: URL) async throws -> Data {
  1141. let (data, _) = try await session.data(from: url)
  1142. return data
  1143. }
  1144. }
  1145. `;
  1146. const result = extractFromSource('NetworkManager.swift', code);
  1147. const classNode = result.nodes.find((n) => n.kind === 'class');
  1148. expect(classNode).toBeDefined();
  1149. expect(classNode?.name).toBe('NetworkManager');
  1150. });
  1151. it('should extract function declarations', () => {
  1152. const code = `
  1153. func calculateSum(_ numbers: [Int]) -> Int {
  1154. return numbers.reduce(0, +)
  1155. }
  1156. public func formatCurrency(amount: Double) -> String {
  1157. return String(format: "$%.2f", amount)
  1158. }
  1159. `;
  1160. const result = extractFromSource('utils.swift', code);
  1161. const functions = result.nodes.filter((n) => n.kind === 'function');
  1162. expect(functions.length).toBeGreaterThanOrEqual(1);
  1163. });
  1164. it('should extract struct declarations', () => {
  1165. const code = `
  1166. public struct User {
  1167. let id: UUID
  1168. var name: String
  1169. var email: String
  1170. func displayName() -> String {
  1171. return name
  1172. }
  1173. }
  1174. `;
  1175. const result = extractFromSource('User.swift', code);
  1176. const structNode = result.nodes.find((n) => n.kind === 'struct');
  1177. expect(structNode).toBeDefined();
  1178. expect(structNode?.name).toBe('User');
  1179. });
  1180. it('should extract protocol declarations', () => {
  1181. const code = `
  1182. public protocol Repository {
  1183. associatedtype Entity
  1184. func find(id: String) async throws -> Entity?
  1185. func save(_ entity: Entity) async throws
  1186. }
  1187. `;
  1188. const result = extractFromSource('Repository.swift', code);
  1189. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  1190. expect(protocolNode).toBeDefined();
  1191. expect(protocolNode?.name).toBe('Repository');
  1192. });
  1193. it('should extract class inheritance and protocol conformance', () => {
  1194. const code = `
  1195. class DataRequest: Request {
  1196. func validate() {}
  1197. }
  1198. class UploadRequest: DataRequest, Sendable {
  1199. func upload() {}
  1200. }
  1201. enum AFError: Error {
  1202. case invalidURL
  1203. }
  1204. struct HTTPMethod: RawRepresentable {
  1205. let rawValue: String
  1206. }
  1207. protocol UploadConvertible: URLRequestConvertible {
  1208. func asURLRequest() throws -> URLRequest
  1209. }
  1210. `;
  1211. const result = extractFromSource('Inheritance.swift', code);
  1212. const extendsRefs = result.unresolvedReferences.filter(
  1213. (r) => r.referenceKind === 'extends'
  1214. );
  1215. // DataRequest extends Request
  1216. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  1217. // UploadRequest extends DataRequest and Sendable
  1218. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  1219. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  1220. // AFError extends Error
  1221. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  1222. // HTTPMethod extends RawRepresentable
  1223. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  1224. // UploadConvertible extends URLRequestConvertible
  1225. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1226. });
  1227. it('indexes Swift properties so they are findable: computed → property, stored → field, static → constant/variable (#1020)', () => {
  1228. const code = `
  1229. struct ReproConfig {
  1230. let reproStoredValue: Int
  1231. var reproComputedFlag: Bool {
  1232. reproStoredValue > 0
  1233. }
  1234. static let sharedLimit = 10
  1235. static var sharedCount = 0
  1236. func reproControlMethod() -> Bool {
  1237. reproComputedFlag
  1238. }
  1239. }
  1240. final class ReproService {
  1241. private let reproClassStored: String = "x"
  1242. var reproClassComputed: Int { reproClassStored.count }
  1243. }
  1244. `;
  1245. const result = extractFromSource('Repro.swift', code);
  1246. const byName = (name: string) => result.nodes.find((n) => n.name === name);
  1247. // Computed properties are the regression this fix targets: before #1020 they
  1248. // were dropped entirely, so search/explore returned nothing for them.
  1249. expect(byName('reproComputedFlag')?.kind).toBe('property');
  1250. expect(byName('reproClassComputed')?.kind).toBe('property');
  1251. // Stored instance properties stay `field` (fixed earlier in #708 — guard it).
  1252. expect(byName('reproStoredValue')?.kind).toBe('field');
  1253. expect(byName('reproClassStored')?.kind).toBe('field');
  1254. // `static let`/`static var` members remain shared constant/variable nodes.
  1255. expect(byName('sharedLimit')?.kind).toBe('constant');
  1256. expect(byName('sharedCount')?.kind).toBe('variable');
  1257. // The control method is unaffected.
  1258. expect(byName('reproControlMethod')?.kind).toBe('method');
  1259. });
  1260. it("attributes a computed property's getter calls to the property, not the type (SwiftUI body flow) (#1020)", () => {
  1261. const code = `
  1262. struct GreetingView {
  1263. let name: String
  1264. var body: some View {
  1265. let prefix = "Hi"
  1266. return VStack {
  1267. Text(greeting(prefix))
  1268. }
  1269. }
  1270. func greeting(_ p: String) -> String { p }
  1271. }
  1272. `;
  1273. const result = extractFromSource('View.swift', code);
  1274. const body = result.nodes.find((n) => n.kind === 'property' && n.name === 'body');
  1275. expect(body).toBeDefined();
  1276. // The getter's call to greeting() must originate from `body` (so a SwiftUI
  1277. // view's render flow is reachable through the property), not flatten onto the
  1278. // enclosing struct.
  1279. const callsFromBody = result.unresolvedReferences.filter(
  1280. (r) => r.fromNodeId === body!.id && r.referenceKind === 'calls'
  1281. );
  1282. expect(callsFromBody.some((r) => r.referenceName === 'greeting')).toBe(true);
  1283. // The getter is walked as a body, so a local declared inside it is NOT
  1284. // node-ified (locals are the data-flow frontier we leave uncovered). Before
  1285. // this fix the generic walker treated such a local as a struct `field`.
  1286. expect(result.nodes.find((n) => n.name === 'prefix')).toBeUndefined();
  1287. });
  1288. it('indexes a Swift protocol property requirement as a findable property (#1020)', () => {
  1289. const code = `
  1290. protocol Themable {
  1291. var accentColor: Color { get }
  1292. var title: String { get set }
  1293. }
  1294. `;
  1295. const result = extractFromSource('Themable.swift', code);
  1296. expect(result.nodes.find((n) => n.name === 'accentColor')?.kind).toBe('property');
  1297. expect(result.nodes.find((n) => n.name === 'title')?.kind).toBe('property');
  1298. });
  1299. });
  1300. describe('Kotlin Extraction', () => {
  1301. it('should extract class declarations', () => {
  1302. const code = `
  1303. class UserRepository(private val database: Database) {
  1304. fun findById(id: String): User? {
  1305. return database.query("SELECT * FROM users WHERE id = ?", id)
  1306. }
  1307. suspend fun save(user: User) {
  1308. database.insert(user)
  1309. }
  1310. }
  1311. `;
  1312. const result = extractFromSource('UserRepository.kt', code);
  1313. const classNode = result.nodes.find((n) => n.kind === 'class');
  1314. expect(classNode).toBeDefined();
  1315. expect(classNode?.name).toBe('UserRepository');
  1316. });
  1317. it('should extract function declarations', () => {
  1318. const code = `
  1319. fun calculateTotal(items: List<Item>): Double {
  1320. return items.sumOf { it.price }
  1321. }
  1322. suspend fun fetchUserData(userId: String): User {
  1323. return api.getUser(userId)
  1324. }
  1325. `;
  1326. const result = extractFromSource('utils.kt', code);
  1327. const functions = result.nodes.filter((n) => n.kind === 'function');
  1328. expect(functions.length).toBeGreaterThanOrEqual(1);
  1329. });
  1330. it('should detect suspend functions as async', () => {
  1331. const code = `
  1332. suspend fun loadData(): List<String> {
  1333. delay(1000)
  1334. return listOf("a", "b", "c")
  1335. }
  1336. `;
  1337. const result = extractFromSource('loader.kt', code);
  1338. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1339. expect(funcNode).toBeDefined();
  1340. expect(funcNode?.isAsync).toBe(true);
  1341. });
  1342. it('should extract fun interface declarations', () => {
  1343. const code = `
  1344. fun interface OnObjectRetainedListener {
  1345. fun onObjectRetained()
  1346. }
  1347. `;
  1348. const result = extractFromSource('listener.kt', code);
  1349. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1350. expect(ifaceNode).toBeDefined();
  1351. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1352. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1353. expect(methodNode).toBeDefined();
  1354. expect(methodNode?.name).toBe('onObjectRetained');
  1355. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1356. });
  1357. it('should extract complex fun interface with nested classes', () => {
  1358. const code = `
  1359. fun interface EventListener {
  1360. fun onEvent(event: Event)
  1361. sealed class Event {
  1362. class DumpingHeap : Event()
  1363. }
  1364. }
  1365. `;
  1366. const result = extractFromSource('events.kt', code);
  1367. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1368. expect(ifaceNode).toBeDefined();
  1369. expect(ifaceNode?.name).toBe('EventListener');
  1370. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1371. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1372. expect(eventClass).toBeDefined();
  1373. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1374. expect(dumpingHeap).toBeDefined();
  1375. });
  1376. it('should not affect regular function declarations', () => {
  1377. const code = `
  1378. fun interface MyCallback {
  1379. fun invoke(value: Int)
  1380. }
  1381. fun regularFunction(): String {
  1382. return "hello"
  1383. }
  1384. `;
  1385. const result = extractFromSource('mixed.kt', code);
  1386. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1387. expect(ifaceNode).toBeDefined();
  1388. expect(ifaceNode?.name).toBe('MyCallback');
  1389. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1390. expect(funcNode).toBeDefined();
  1391. expect(funcNode?.name).toBe('regularFunction');
  1392. });
  1393. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1394. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1395. // misparse: function_declaration > ERROR("interface Name {") instead of
  1396. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1397. const code = `
  1398. import java.io.IOException
  1399. fun interface Interceptor {
  1400. @Throws(IOException::class)
  1401. fun intercept(chain: Chain): Response
  1402. }
  1403. `;
  1404. const result = extractFromSource('interceptor.kt', code);
  1405. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1406. expect(ifaceNode).toBeDefined();
  1407. expect(ifaceNode?.name).toBe('Interceptor');
  1408. });
  1409. it('should extract methods from interface with nested fun interface', () => {
  1410. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1411. // the parent body as ERROR. Methods inside should still be extracted.
  1412. const code = `
  1413. interface WebSocket {
  1414. fun request(): Request
  1415. fun send(text: String): Boolean
  1416. fun cancel()
  1417. fun interface Factory {
  1418. fun newWebSocket(request: Request): WebSocket
  1419. }
  1420. }
  1421. `;
  1422. const result = extractFromSource('websocket.kt', code);
  1423. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1424. expect(wsIface).toBeDefined();
  1425. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1426. const methodNames = methods.map((m) => m.name);
  1427. expect(methodNames).toContain('request');
  1428. expect(methodNames).toContain('send');
  1429. expect(methodNames).toContain('cancel');
  1430. });
  1431. it('wraps top-level declarations in a namespace from package_header', () => {
  1432. const code = `
  1433. package com.example.foo
  1434. class Bar {
  1435. fun greet(): String = "hi"
  1436. }
  1437. fun util(): Int = 42
  1438. `;
  1439. const result = extractFromSource('Bar.kt', code);
  1440. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1441. expect(ns?.name).toBe('com.example.foo');
  1442. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1443. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1444. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1445. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1446. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1447. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1448. });
  1449. it('handles a single-segment package', () => {
  1450. const code = `
  1451. package foo
  1452. class Bar
  1453. `;
  1454. const result = extractFromSource('Bar.kt', code);
  1455. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1456. expect(cls?.qualifiedName).toBe('foo::Bar');
  1457. });
  1458. it('does not wrap when no package is declared', () => {
  1459. const code = `
  1460. class Bar {
  1461. fun greet() = "hi"
  1462. }
  1463. `;
  1464. const result = extractFromSource('Bar.kt', code);
  1465. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1466. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1467. expect(cls?.qualifiedName).toBe('Bar');
  1468. });
  1469. });
  1470. describe('Dart Extraction', () => {
  1471. it('should extract class declarations', () => {
  1472. const code = `
  1473. class UserService {
  1474. final Database _db;
  1475. Future<User> findById(String id) async {
  1476. return await _db.query(id);
  1477. }
  1478. void _privateMethod() {}
  1479. }
  1480. `;
  1481. const result = extractFromSource('service.dart', code);
  1482. const classNode = result.nodes.find((n) => n.kind === 'class');
  1483. expect(classNode).toBeDefined();
  1484. expect(classNode?.name).toBe('UserService');
  1485. expect(classNode?.visibility).toBe('public');
  1486. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1487. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1488. const findById = methodNodes.find((m) => m.name === 'findById');
  1489. expect(findById).toBeDefined();
  1490. expect(findById?.isAsync).toBe(true);
  1491. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1492. expect(privateMethod).toBeDefined();
  1493. expect(privateMethod?.visibility).toBe('private');
  1494. // Dart models a method body as a SIBLING of the signature, so the method
  1495. // node must be extended to span its body (not just the signature line) —
  1496. // required for body-level analysis (callees, the callback synthesizer).
  1497. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1498. });
  1499. it('should extract top-level function declarations', () => {
  1500. const code = `
  1501. void topLevelFunction(String name) {
  1502. print(name);
  1503. }
  1504. `;
  1505. const result = extractFromSource('utils.dart', code);
  1506. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1507. expect(funcNode).toBeDefined();
  1508. expect(funcNode?.name).toBe('topLevelFunction');
  1509. expect(funcNode?.language).toBe('dart');
  1510. });
  1511. it('should extract enum declarations', () => {
  1512. const code = `
  1513. enum Status { active, inactive, pending }
  1514. `;
  1515. const result = extractFromSource('models.dart', code);
  1516. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1517. expect(enumNode).toBeDefined();
  1518. expect(enumNode?.name).toBe('Status');
  1519. });
  1520. it('should extract mixin declarations', () => {
  1521. const code = `
  1522. mixin LoggerMixin {
  1523. void log(String message) {}
  1524. }
  1525. `;
  1526. const result = extractFromSource('mixins.dart', code);
  1527. const classNode = result.nodes.find((n) => n.kind === 'class');
  1528. expect(classNode).toBeDefined();
  1529. expect(classNode?.name).toBe('LoggerMixin');
  1530. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1531. expect(methodNode).toBeDefined();
  1532. expect(methodNode?.name).toBe('log');
  1533. });
  1534. it('should extract extension declarations', () => {
  1535. const code = `
  1536. extension StringExt on String {
  1537. bool get isBlank => trim().isEmpty;
  1538. }
  1539. `;
  1540. const result = extractFromSource('extensions.dart', code);
  1541. const classNode = result.nodes.find((n) => n.kind === 'class');
  1542. expect(classNode).toBeDefined();
  1543. expect(classNode?.name).toBe('StringExt');
  1544. });
  1545. it('should detect static methods', () => {
  1546. const code = `
  1547. class Utils {
  1548. static void doWork() {}
  1549. }
  1550. `;
  1551. const result = extractFromSource('utils.dart', code);
  1552. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1553. expect(methodNode).toBeDefined();
  1554. expect(methodNode?.name).toBe('doWork');
  1555. expect(methodNode?.isStatic).toBe(true);
  1556. });
  1557. it('should detect async functions', () => {
  1558. const code = `
  1559. Future<String> fetchData() async {
  1560. return await http.get('/data');
  1561. }
  1562. `;
  1563. const result = extractFromSource('api.dart', code);
  1564. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1565. expect(funcNode).toBeDefined();
  1566. expect(funcNode?.name).toBe('fetchData');
  1567. expect(funcNode?.isAsync).toBe(true);
  1568. });
  1569. it('should detect private visibility via underscore convention', () => {
  1570. const code = `
  1571. void _privateHelper() {}
  1572. void publicFunction() {}
  1573. `;
  1574. const result = extractFromSource('helpers.dart', code);
  1575. const functions = result.nodes.filter((n) => n.kind === 'function');
  1576. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1577. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1578. expect(privateFunc?.visibility).toBe('private');
  1579. expect(publicFunc?.visibility).toBe('public');
  1580. });
  1581. });
  1582. describe('Import Extraction', () => {
  1583. describe('TypeScript/JavaScript imports', () => {
  1584. it('should extract default imports', () => {
  1585. const code = `import React from 'react';`;
  1586. const result = extractFromSource('app.tsx', code);
  1587. const importNode = result.nodes.find((n) => n.kind === 'import');
  1588. expect(importNode).toBeDefined();
  1589. expect(importNode?.name).toBe('react');
  1590. expect(importNode?.signature).toBe("import React from 'react';");
  1591. });
  1592. it('should extract named imports', () => {
  1593. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1594. const result = extractFromSource('icons.tsx', code);
  1595. const importNode = result.nodes.find((n) => n.kind === 'import');
  1596. expect(importNode).toBeDefined();
  1597. expect(importNode?.name).toBe('@phosphor-icons/react');
  1598. expect(importNode?.signature).toContain('Bug');
  1599. expect(importNode?.signature).toContain('Database');
  1600. });
  1601. it('should extract namespace imports', () => {
  1602. const code = `import * as Icons from '@phosphor-icons/react';`;
  1603. const result = extractFromSource('icons.tsx', code);
  1604. const importNode = result.nodes.find((n) => n.kind === 'import');
  1605. expect(importNode).toBeDefined();
  1606. expect(importNode?.name).toBe('@phosphor-icons/react');
  1607. expect(importNode?.signature).toContain('* as Icons');
  1608. });
  1609. it('should extract side-effect imports', () => {
  1610. const code = `import './styles.css';`;
  1611. const result = extractFromSource('app.tsx', code);
  1612. const importNode = result.nodes.find((n) => n.kind === 'import');
  1613. expect(importNode).toBeDefined();
  1614. expect(importNode?.name).toBe('./styles.css');
  1615. });
  1616. it('should extract mixed imports (default + named)', () => {
  1617. const code = `import React, { useState, useEffect } from 'react';`;
  1618. const result = extractFromSource('app.tsx', code);
  1619. const importNode = result.nodes.find((n) => n.kind === 'import');
  1620. expect(importNode).toBeDefined();
  1621. expect(importNode?.name).toBe('react');
  1622. expect(importNode?.signature).toContain('React');
  1623. expect(importNode?.signature).toContain('useState');
  1624. expect(importNode?.signature).toContain('useEffect');
  1625. });
  1626. it('should extract multiple import statements', () => {
  1627. const code = `
  1628. import React from 'react';
  1629. import { Button } from './components';
  1630. import './styles.css';
  1631. `;
  1632. const result = extractFromSource('app.tsx', code);
  1633. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1634. expect(importNodes.length).toBe(3);
  1635. const names = importNodes.map((n) => n.name);
  1636. expect(names).toContain('react');
  1637. expect(names).toContain('./components');
  1638. expect(names).toContain('./styles.css');
  1639. });
  1640. it('should extract type imports', () => {
  1641. const code = `import type { FC, ReactNode } from 'react';`;
  1642. const result = extractFromSource('types.ts', code);
  1643. const importNode = result.nodes.find((n) => n.kind === 'import');
  1644. expect(importNode).toBeDefined();
  1645. expect(importNode?.name).toBe('react');
  1646. expect(importNode?.signature).toContain('type');
  1647. expect(importNode?.signature).toContain('FC');
  1648. });
  1649. it('should extract aliased named imports', () => {
  1650. const code = `import { useState as useStateAlias } from 'react';`;
  1651. const result = extractFromSource('hooks.ts', code);
  1652. const importNode = result.nodes.find((n) => n.kind === 'import');
  1653. expect(importNode).toBeDefined();
  1654. expect(importNode?.name).toBe('react');
  1655. expect(importNode?.signature).toContain('useState');
  1656. expect(importNode?.signature).toContain('useStateAlias');
  1657. });
  1658. it('should extract relative path imports', () => {
  1659. const code = `import { helper } from '../utils/helper';`;
  1660. const result = extractFromSource('components/Button.tsx', code);
  1661. const importNode = result.nodes.find((n) => n.kind === 'import');
  1662. expect(importNode).toBeDefined();
  1663. expect(importNode?.name).toBe('../utils/helper');
  1664. expect(importNode?.signature).toContain('helper');
  1665. });
  1666. });
  1667. describe('Python imports', () => {
  1668. it('should extract simple import statement', () => {
  1669. const code = `import json`;
  1670. const result = extractFromSource('utils.py', code);
  1671. const importNode = result.nodes.find((n) => n.kind === 'import');
  1672. expect(importNode).toBeDefined();
  1673. expect(importNode?.name).toBe('json');
  1674. });
  1675. it('should extract from import statement', () => {
  1676. const code = `from os import path`;
  1677. const result = extractFromSource('utils.py', code);
  1678. const importNode = result.nodes.find((n) => n.kind === 'import');
  1679. expect(importNode).toBeDefined();
  1680. expect(importNode?.name).toBe('os');
  1681. expect(importNode?.signature).toContain('path');
  1682. });
  1683. it('should extract multiple imports from same module', () => {
  1684. const code = `from typing import List, Dict, Optional`;
  1685. const result = extractFromSource('types.py', code);
  1686. const importNode = result.nodes.find((n) => n.kind === 'import');
  1687. expect(importNode).toBeDefined();
  1688. expect(importNode?.name).toBe('typing');
  1689. expect(importNode?.signature).toContain('List');
  1690. expect(importNode?.signature).toContain('Dict');
  1691. });
  1692. it('should extract multiple import statements', () => {
  1693. const code = `
  1694. import os
  1695. import sys
  1696. `;
  1697. const result = extractFromSource('main.py', code);
  1698. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1699. expect(importNodes.length).toBe(2);
  1700. const names = importNodes.map((n) => n.name);
  1701. expect(names).toContain('os');
  1702. expect(names).toContain('sys');
  1703. });
  1704. it('should extract aliased import', () => {
  1705. const code = `import numpy as np`;
  1706. const result = extractFromSource('data.py', code);
  1707. const importNode = result.nodes.find((n) => n.kind === 'import');
  1708. expect(importNode).toBeDefined();
  1709. expect(importNode?.name).toBe('numpy');
  1710. expect(importNode?.signature).toContain('as np');
  1711. });
  1712. it('should extract relative import', () => {
  1713. const code = `from .utils import helper`;
  1714. const result = extractFromSource('module.py', code);
  1715. const importNode = result.nodes.find((n) => n.kind === 'import');
  1716. expect(importNode).toBeDefined();
  1717. expect(importNode?.name).toBe('.utils');
  1718. expect(importNode?.signature).toContain('helper');
  1719. });
  1720. it('should extract wildcard import', () => {
  1721. const code = `from typing import *`;
  1722. const result = extractFromSource('types.py', code);
  1723. const importNode = result.nodes.find((n) => n.kind === 'import');
  1724. expect(importNode).toBeDefined();
  1725. expect(importNode?.name).toBe('typing');
  1726. expect(importNode?.signature).toContain('*');
  1727. });
  1728. });
  1729. describe('Rust imports', () => {
  1730. it('should extract simple use declaration', () => {
  1731. const code = `use std::io;`;
  1732. const result = extractFromSource('main.rs', code);
  1733. const importNode = result.nodes.find((n) => n.kind === 'import');
  1734. expect(importNode).toBeDefined();
  1735. expect(importNode?.name).toBe('std');
  1736. expect(importNode?.signature).toBe('use std::io;');
  1737. });
  1738. it('should extract scoped use list', () => {
  1739. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1740. const result = extractFromSource('main.rs', code);
  1741. const importNode = result.nodes.find((n) => n.kind === 'import');
  1742. expect(importNode).toBeDefined();
  1743. expect(importNode?.name).toBe('std');
  1744. expect(importNode?.signature).toContain('ffi::OsStr');
  1745. expect(importNode?.signature).toContain('path::Path');
  1746. });
  1747. it('should extract crate imports', () => {
  1748. const code = `use crate::error::Error;`;
  1749. const result = extractFromSource('lib.rs', code);
  1750. const importNode = result.nodes.find((n) => n.kind === 'import');
  1751. expect(importNode).toBeDefined();
  1752. expect(importNode?.name).toBe('crate');
  1753. });
  1754. it('should extract super imports', () => {
  1755. const code = `use super::utils;`;
  1756. const result = extractFromSource('submod.rs', code);
  1757. const importNode = result.nodes.find((n) => n.kind === 'import');
  1758. expect(importNode).toBeDefined();
  1759. expect(importNode?.name).toBe('super');
  1760. });
  1761. it('should extract external crate imports', () => {
  1762. const code = `use serde::{Serialize, Deserialize};`;
  1763. const result = extractFromSource('types.rs', code);
  1764. const importNode = result.nodes.find((n) => n.kind === 'import');
  1765. expect(importNode).toBeDefined();
  1766. expect(importNode?.name).toBe('serde');
  1767. expect(importNode?.signature).toContain('Serialize');
  1768. expect(importNode?.signature).toContain('Deserialize');
  1769. });
  1770. });
  1771. describe('Go imports', () => {
  1772. it('should extract single import', () => {
  1773. const code = `
  1774. package main
  1775. import "fmt"
  1776. `;
  1777. const result = extractFromSource('main.go', code);
  1778. const importNode = result.nodes.find((n) => n.kind === 'import');
  1779. expect(importNode).toBeDefined();
  1780. expect(importNode?.name).toBe('fmt');
  1781. });
  1782. it('should extract grouped imports', () => {
  1783. const code = `
  1784. package main
  1785. import (
  1786. "fmt"
  1787. "os"
  1788. "encoding/json"
  1789. )
  1790. `;
  1791. const result = extractFromSource('main.go', code);
  1792. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1793. expect(importNodes.length).toBe(3);
  1794. const names = importNodes.map((n) => n.name);
  1795. expect(names).toContain('fmt');
  1796. expect(names).toContain('os');
  1797. expect(names).toContain('encoding/json');
  1798. });
  1799. it('should extract aliased import', () => {
  1800. const code = `
  1801. package main
  1802. import f "fmt"
  1803. `;
  1804. const result = extractFromSource('main.go', code);
  1805. const importNode = result.nodes.find((n) => n.kind === 'import');
  1806. expect(importNode).toBeDefined();
  1807. expect(importNode?.name).toBe('fmt');
  1808. expect(importNode?.signature).toContain('f');
  1809. });
  1810. it('should extract dot import', () => {
  1811. const code = `
  1812. package main
  1813. import . "math"
  1814. `;
  1815. const result = extractFromSource('main.go', code);
  1816. const importNode = result.nodes.find((n) => n.kind === 'import');
  1817. expect(importNode).toBeDefined();
  1818. expect(importNode?.name).toBe('math');
  1819. expect(importNode?.signature).toContain('.');
  1820. });
  1821. it('should extract blank import', () => {
  1822. const code = `
  1823. package main
  1824. import _ "github.com/go-sql-driver/mysql"
  1825. `;
  1826. const result = extractFromSource('main.go', code);
  1827. const importNode = result.nodes.find((n) => n.kind === 'import');
  1828. expect(importNode).toBeDefined();
  1829. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1830. expect(importNode?.signature).toContain('_');
  1831. });
  1832. });
  1833. describe('Swift imports', () => {
  1834. it('should extract simple import', () => {
  1835. const code = `import Foundation`;
  1836. const result = extractFromSource('main.swift', code);
  1837. const importNode = result.nodes.find((n) => n.kind === 'import');
  1838. expect(importNode).toBeDefined();
  1839. expect(importNode?.name).toBe('Foundation');
  1840. expect(importNode?.signature).toBe('import Foundation');
  1841. });
  1842. it('should extract @testable import', () => {
  1843. const code = `@testable import Alamofire`;
  1844. const result = extractFromSource('Tests.swift', code);
  1845. const importNode = result.nodes.find((n) => n.kind === 'import');
  1846. expect(importNode).toBeDefined();
  1847. expect(importNode?.name).toBe('Alamofire');
  1848. expect(importNode?.signature).toContain('@testable');
  1849. });
  1850. it('should extract @preconcurrency import', () => {
  1851. const code = `@preconcurrency import Security`;
  1852. const result = extractFromSource('Auth.swift', code);
  1853. const importNode = result.nodes.find((n) => n.kind === 'import');
  1854. expect(importNode).toBeDefined();
  1855. expect(importNode?.name).toBe('Security');
  1856. });
  1857. it('should extract multiple imports', () => {
  1858. const code = `
  1859. import Foundation
  1860. import UIKit
  1861. import Alamofire
  1862. `;
  1863. const result = extractFromSource('App.swift', code);
  1864. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1865. expect(importNodes.length).toBe(3);
  1866. const names = importNodes.map((n) => n.name);
  1867. expect(names).toContain('Foundation');
  1868. expect(names).toContain('UIKit');
  1869. expect(names).toContain('Alamofire');
  1870. });
  1871. });
  1872. describe('Kotlin imports', () => {
  1873. it('should extract simple import', () => {
  1874. const code = `import java.io.IOException`;
  1875. const result = extractFromSource('Main.kt', code);
  1876. const importNode = result.nodes.find((n) => n.kind === 'import');
  1877. expect(importNode).toBeDefined();
  1878. expect(importNode?.name).toBe('java.io.IOException');
  1879. expect(importNode?.signature).toBe('import java.io.IOException');
  1880. });
  1881. it('should extract aliased import', () => {
  1882. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1883. const result = extractFromSource('Utils.kt', code);
  1884. const importNode = result.nodes.find((n) => n.kind === 'import');
  1885. expect(importNode).toBeDefined();
  1886. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1887. expect(importNode?.signature).toContain('as RequestBuilder');
  1888. });
  1889. it('should extract wildcard import', () => {
  1890. const code = `import java.util.concurrent.TimeUnit.*`;
  1891. const result = extractFromSource('Time.kt', code);
  1892. const importNode = result.nodes.find((n) => n.kind === 'import');
  1893. expect(importNode).toBeDefined();
  1894. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1895. expect(importNode?.signature).toContain('.*');
  1896. });
  1897. it('should extract multiple imports', () => {
  1898. const code = `
  1899. import java.io.IOException
  1900. import kotlin.test.assertFailsWith
  1901. import okhttp3.OkHttpClient
  1902. `;
  1903. const result = extractFromSource('Test.kt', code);
  1904. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1905. expect(importNodes.length).toBe(3);
  1906. const names = importNodes.map((n) => n.name);
  1907. expect(names).toContain('java.io.IOException');
  1908. expect(names).toContain('kotlin.test.assertFailsWith');
  1909. expect(names).toContain('okhttp3.OkHttpClient');
  1910. });
  1911. });
  1912. describe('Java imports', () => {
  1913. it('should extract simple import', () => {
  1914. const code = `import java.util.List;`;
  1915. const result = extractFromSource('Main.java', code);
  1916. const importNode = result.nodes.find((n) => n.kind === 'import');
  1917. expect(importNode).toBeDefined();
  1918. expect(importNode?.name).toBe('java.util.List');
  1919. expect(importNode?.signature).toBe('import java.util.List;');
  1920. });
  1921. it('should extract static import', () => {
  1922. const code = `import static java.util.Collections.emptyList;`;
  1923. const result = extractFromSource('Utils.java', code);
  1924. const importNode = result.nodes.find((n) => n.kind === 'import');
  1925. expect(importNode).toBeDefined();
  1926. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1927. expect(importNode?.signature).toContain('static');
  1928. });
  1929. it('should extract wildcard import', () => {
  1930. const code = `import java.util.*;`;
  1931. const result = extractFromSource('App.java', code);
  1932. const importNode = result.nodes.find((n) => n.kind === 'import');
  1933. expect(importNode).toBeDefined();
  1934. expect(importNode?.name).toBe('java.util');
  1935. expect(importNode?.signature).toContain('.*');
  1936. });
  1937. it('should extract nested class import', () => {
  1938. const code = `import java.util.Map.Entry;`;
  1939. const result = extractFromSource('MapUtil.java', code);
  1940. const importNode = result.nodes.find((n) => n.kind === 'import');
  1941. expect(importNode).toBeDefined();
  1942. expect(importNode?.name).toBe('java.util.Map.Entry');
  1943. });
  1944. it('should extract multiple imports', () => {
  1945. const code = `
  1946. import java.util.List;
  1947. import java.util.Map;
  1948. import java.io.IOException;
  1949. `;
  1950. const result = extractFromSource('Service.java', code);
  1951. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1952. expect(importNodes.length).toBe(3);
  1953. const names = importNodes.map((n) => n.name);
  1954. expect(names).toContain('java.util.List');
  1955. expect(names).toContain('java.util.Map');
  1956. expect(names).toContain('java.io.IOException');
  1957. });
  1958. });
  1959. describe('C# imports', () => {
  1960. it('should extract simple using', () => {
  1961. const code = `using System;`;
  1962. const result = extractFromSource('Program.cs', code);
  1963. const importNode = result.nodes.find((n) => n.kind === 'import');
  1964. expect(importNode).toBeDefined();
  1965. expect(importNode?.name).toBe('System');
  1966. expect(importNode?.signature).toBe('using System;');
  1967. });
  1968. it('should extract qualified using', () => {
  1969. const code = `using System.Collections.Generic;`;
  1970. const result = extractFromSource('Utils.cs', code);
  1971. const importNode = result.nodes.find((n) => n.kind === 'import');
  1972. expect(importNode).toBeDefined();
  1973. expect(importNode?.name).toBe('System.Collections.Generic');
  1974. });
  1975. it('should extract static using', () => {
  1976. const code = `using static System.Console;`;
  1977. const result = extractFromSource('App.cs', code);
  1978. const importNode = result.nodes.find((n) => n.kind === 'import');
  1979. expect(importNode).toBeDefined();
  1980. expect(importNode?.name).toBe('System.Console');
  1981. expect(importNode?.signature).toContain('static');
  1982. });
  1983. it('should extract alias using', () => {
  1984. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1985. const result = extractFromSource('Types.cs', code);
  1986. const importNode = result.nodes.find((n) => n.kind === 'import');
  1987. expect(importNode).toBeDefined();
  1988. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1989. expect(importNode?.signature).toContain('MyList =');
  1990. });
  1991. it('should extract multiple usings', () => {
  1992. const code = `
  1993. using System;
  1994. using System.Threading.Tasks;
  1995. using Microsoft.Extensions.DependencyInjection;
  1996. `;
  1997. const result = extractFromSource('Service.cs', code);
  1998. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1999. expect(importNodes.length).toBe(3);
  2000. const names = importNodes.map((n) => n.name);
  2001. expect(names).toContain('System');
  2002. expect(names).toContain('System.Threading.Tasks');
  2003. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  2004. });
  2005. });
  2006. describe('PHP imports', () => {
  2007. it('should extract simple use', () => {
  2008. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  2009. const result = extractFromSource('Test.php', code);
  2010. const importNode = result.nodes.find((n) => n.kind === 'import');
  2011. expect(importNode).toBeDefined();
  2012. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  2013. });
  2014. it('should extract aliased use', () => {
  2015. const code = `<?php use Mockery as m;`;
  2016. const result = extractFromSource('Test.php', code);
  2017. const importNode = result.nodes.find((n) => n.kind === 'import');
  2018. expect(importNode).toBeDefined();
  2019. expect(importNode?.name).toBe('Mockery');
  2020. expect(importNode?.signature).toContain('as m');
  2021. });
  2022. it('should extract function use', () => {
  2023. const code = `<?php use function Illuminate\\Support\\env;`;
  2024. const result = extractFromSource('helpers.php', code);
  2025. const importNode = result.nodes.find((n) => n.kind === 'import');
  2026. expect(importNode).toBeDefined();
  2027. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  2028. expect(importNode?.signature).toContain('function');
  2029. });
  2030. it('should extract grouped use', () => {
  2031. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  2032. const result = extractFromSource('Models.php', code);
  2033. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2034. expect(importNodes.length).toBe(2);
  2035. const names = importNodes.map((n) => n.name);
  2036. expect(names).toContain('Illuminate\\Database\\Model');
  2037. expect(names).toContain('Illuminate\\Database\\Builder');
  2038. });
  2039. it('should extract multiple uses', () => {
  2040. const code = `<?php
  2041. use Illuminate\\Support\\Collection;
  2042. use Illuminate\\Support\\Str;
  2043. use Closure;
  2044. `;
  2045. const result = extractFromSource('Service.php', code);
  2046. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2047. expect(importNodes.length).toBe(3);
  2048. const names = importNodes.map((n) => n.name);
  2049. expect(names).toContain('Illuminate\\Support\\Collection');
  2050. expect(names).toContain('Illuminate\\Support\\Str');
  2051. expect(names).toContain('Closure');
  2052. });
  2053. it('should extract include/require (+_once) static paths as imports (#660)', () => {
  2054. const code = `<?php
  2055. require_once("lib.php");
  2056. include 'other.php';
  2057. require 'r.php';
  2058. include_once("io.php");
  2059. `;
  2060. const result = extractFromSource('page.php', code);
  2061. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2062. expect(names).toContain('lib.php');
  2063. expect(names).toContain('other.php');
  2064. expect(names).toContain('r.php');
  2065. expect(names).toContain('io.php');
  2066. });
  2067. it('should skip dynamic include/require with no static path (#660)', () => {
  2068. const code = `<?php
  2069. require_once(__DIR__ . '/dyn.php');
  2070. include $file;
  2071. include "tpl/{$name}.php";
  2072. `;
  2073. const result = extractFromSource('page.php', code);
  2074. const imports = result.nodes.filter((n) => n.kind === 'import');
  2075. expect(imports).toHaveLength(0);
  2076. });
  2077. it('should extract include alongside namespace use without interference (#660)', () => {
  2078. const code = `<?php
  2079. use App\\Service\\Mailer;
  2080. require_once("bootstrap.php");
  2081. `;
  2082. const result = extractFromSource('page.php', code);
  2083. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2084. expect(names).toContain('App\\Service\\Mailer');
  2085. expect(names).toContain('bootstrap.php');
  2086. });
  2087. });
  2088. describe('Ruby imports', () => {
  2089. it('should extract require', () => {
  2090. const code = `require 'json'`;
  2091. const result = extractFromSource('app.rb', code);
  2092. const importNode = result.nodes.find((n) => n.kind === 'import');
  2093. expect(importNode).toBeDefined();
  2094. expect(importNode?.name).toBe('json');
  2095. expect(importNode?.signature).toBe("require 'json'");
  2096. });
  2097. it('should extract require with path', () => {
  2098. const code = `require 'active_support/core_ext/string'`;
  2099. const result = extractFromSource('config.rb', code);
  2100. const importNode = result.nodes.find((n) => n.kind === 'import');
  2101. expect(importNode).toBeDefined();
  2102. expect(importNode?.name).toBe('active_support/core_ext/string');
  2103. });
  2104. it('should extract require_relative', () => {
  2105. const code = `require_relative '../test_helper'`;
  2106. const result = extractFromSource('test/my_test.rb', code);
  2107. const importNode = result.nodes.find((n) => n.kind === 'import');
  2108. expect(importNode).toBeDefined();
  2109. expect(importNode?.name).toBe('../test_helper');
  2110. expect(importNode?.signature).toContain('require_relative');
  2111. });
  2112. it('should not extract non-require calls', () => {
  2113. const code = `puts 'hello'`;
  2114. const result = extractFromSource('app.rb', code);
  2115. const importNode = result.nodes.find((n) => n.kind === 'import');
  2116. expect(importNode).toBeUndefined();
  2117. });
  2118. it('should extract multiple requires', () => {
  2119. const code = `
  2120. require 'json'
  2121. require 'yaml'
  2122. require_relative 'helper'
  2123. `;
  2124. const result = extractFromSource('lib.rb', code);
  2125. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2126. expect(importNodes.length).toBe(3);
  2127. const names = importNodes.map((n) => n.name);
  2128. expect(names).toContain('json');
  2129. expect(names).toContain('yaml');
  2130. expect(names).toContain('helper');
  2131. });
  2132. });
  2133. describe('Ruby modules', () => {
  2134. it('should extract module as module node with containment', () => {
  2135. const code = `
  2136. module CachedCounting
  2137. def self.disable
  2138. @enabled = false
  2139. end
  2140. def perform_increment!(key, count)
  2141. write_cache!(key, count)
  2142. end
  2143. end
  2144. `;
  2145. const result = extractFromSource('concerns/cached_counting.rb', code);
  2146. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  2147. expect(moduleNode).toBeDefined();
  2148. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  2149. // Methods inside module should have module-qualified names
  2150. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  2151. expect(disableMethod).toBeDefined();
  2152. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  2153. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  2154. expect(incrementMethod).toBeDefined();
  2155. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  2156. // Containment edge from module to methods
  2157. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  2158. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  2159. });
  2160. it('should handle nested modules with classes', () => {
  2161. const code = `
  2162. module Discourse
  2163. module Auth
  2164. class AuthProvider
  2165. def authenticate(params)
  2166. validate(params)
  2167. end
  2168. end
  2169. end
  2170. end
  2171. `;
  2172. const result = extractFromSource('lib/auth.rb', code);
  2173. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  2174. expect(discourseModule).toBeDefined();
  2175. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  2176. expect(authModule).toBeDefined();
  2177. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  2178. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  2179. expect(authProvider).toBeDefined();
  2180. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  2181. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  2182. expect(authMethod).toBeDefined();
  2183. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  2184. });
  2185. });
  2186. describe('PHP return type capture (#608)', () => {
  2187. it('captures self/static factory returns as the `self` marker; primitives as undefined', () => {
  2188. const code = `<?php
  2189. class ApiClient {
  2190. public static function for(string $c): self { return new self; }
  2191. public static function make(): static { return new static; }
  2192. public function send(array $p): array { return []; }
  2193. }`;
  2194. const result = extractFromSource('ApiClient.php', code);
  2195. expect(result.nodes.find((n) => n.name === 'for' && n.kind === 'method')?.returnType).toBe('self');
  2196. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('self');
  2197. // `array` is not a class to chain on → no return type recorded.
  2198. expect(result.nodes.find((n) => n.name === 'send' && n.kind === 'method')?.returnType).toBeUndefined();
  2199. });
  2200. it('captures a concrete return type as its short class name', () => {
  2201. const code = `<?php
  2202. namespace App;
  2203. class WidgetFactory { public static function make(): Widget { return new Widget(); } }`;
  2204. const result = extractFromSource('WidgetFactory.php', code);
  2205. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('Widget');
  2206. });
  2207. });
  2208. describe('C/C++ return type capture (#645)', () => {
  2209. it('captures the normalized return type of a C++ method/function', () => {
  2210. const code = `
  2211. struct Widget { void draw(); };
  2212. class Factory { public: static Widget create(); };
  2213. Widget Factory::create() { return Widget(); }
  2214. void doNothing() {}
  2215. `;
  2216. const result = extractFromSource('f.cpp', code);
  2217. const create = result.nodes.find(
  2218. (n) => n.name === 'create' && (n.kind === 'method' || n.kind === 'function')
  2219. );
  2220. expect(create?.returnType).toBe('Widget');
  2221. // A `void` return records no type, so resolution never tries to resolve a
  2222. // method on it.
  2223. const doNothing = result.nodes.find((n) => n.name === 'doNothing');
  2224. expect(doNothing).toBeDefined();
  2225. expect(doNothing?.returnType).toBeUndefined();
  2226. });
  2227. it('unwraps a smart-pointer return type to its pointee', () => {
  2228. const code = `
  2229. #include <memory>
  2230. struct Widget {};
  2231. std::unique_ptr<Widget> makeWidget() { return nullptr; }
  2232. `;
  2233. const result = extractFromSource('f.cpp', code);
  2234. const make = result.nodes.find((n) => n.name === 'makeWidget');
  2235. expect(make?.returnType).toBe('Widget');
  2236. });
  2237. });
  2238. describe('C++ macro-prefixed class/struct misparse (#946 → recovered in #1061)', () => {
  2239. // An export/visibility macro before the class name (`class MACRO Name :
  2240. // public Base { … }`) makes tree-sitter read `class MACRO` as an elaborated
  2241. // type and the whole declaration as a function_definition named after the
  2242. // class — a phantom `function` that polluted callers/impact/blast-radius.
  2243. // #946 dropped that phantom; #1061's preParse (`blankCppExportMacros`) now
  2244. // blanks the ALL-CAPS macro before parsing, so the class parses normally and
  2245. // is *recovered* — node, members, and base edge all present — not just
  2246. // de-phantomed. The #946 drop survives as the fallback for any residual
  2247. // misparse the blanking doesn't catch.
  2248. it('recovers a macro-annotated class that inherits (no phantom, real class + base edge)', () => {
  2249. const code = `#pragma once
  2250. #define MAPCORE_EXPORT __attribute__((visibility("default")))
  2251. class DataProvider {
  2252. public:
  2253. virtual bool Request(void* param) = 0;
  2254. };
  2255. class MAPCORE_EXPORT LocalDataProvider : public DataProvider
  2256. {
  2257. public:
  2258. LocalDataProvider(int dataType);
  2259. virtual bool Request(void* param) override;
  2260. };
  2261. `;
  2262. // A header rich in C++ (class / public: / virtual) detects as C++ — the
  2263. // issue's exact scenario (a `.h` file). Guard it so a detection regression
  2264. // can't make this test pass for the wrong reason.
  2265. expect(detectLanguage('provider.h', code)).toBe('cpp');
  2266. const result = extractFromSource('provider.h', code);
  2267. // The misparse used to surface as `function | LocalDataProvider` spanning
  2268. // the whole class body — a false caller in the graph. It's gone.
  2269. expect(
  2270. result.nodes.find((n) => n.name === 'LocalDataProvider' && n.kind === 'function')
  2271. ).toBeUndefined();
  2272. // …and the class is now recovered (was dropped under #946), with its
  2273. // `extends DataProvider` edge — the whole point of #1061.
  2274. expect(result.nodes.find((n) => n.name === 'LocalDataProvider')?.kind).toBe('class');
  2275. expect(
  2276. result.unresolvedReferences.find(
  2277. (r) => r.referenceKind === 'extends' && r.referenceName === 'DataProvider'
  2278. )
  2279. ).toBeTruthy();
  2280. // The sibling class without the macro is unaffected — still a class.
  2281. expect(result.nodes.find((n) => n.name === 'DataProvider')?.kind).toBe('class');
  2282. });
  2283. it('recovers the struct variant too, without disturbing a genuine class', () => {
  2284. const code = `
  2285. #define API __declspec(dllexport)
  2286. struct API Widget : public Base { int x; };
  2287. class Plain : public Base { public: int y; };
  2288. `;
  2289. const result = extractFromSource('widget.cpp', code);
  2290. // `struct MACRO Name : Base { … }` misparses the same way — no phantom
  2291. // function, and the struct is recovered with its base edge.
  2292. expect(
  2293. result.nodes.find((n) => n.name === 'Widget' && n.kind === 'function')
  2294. ).toBeUndefined();
  2295. expect(result.nodes.find((n) => n.name === 'Widget')?.kind).toBe('struct');
  2296. // A normal class with a base clause and no macro is untouched.
  2297. expect(result.nodes.find((n) => n.name === 'Plain')?.kind).toBe('class');
  2298. const exts = result.unresolvedReferences
  2299. .filter((r) => r.referenceKind === 'extends')
  2300. .map((r) => r.referenceName);
  2301. expect(exts.filter((n) => n === 'Base').length).toBe(2); // Widget + Plain both extend Base
  2302. });
  2303. });
  2304. describe('C++ export-macro class recovery (#1061)', () => {
  2305. // Unreal-Engine style: `class MYGAME_API UMyComponent : public UActorComponent`.
  2306. // The leading `*_API` macro alone (base clause or not) triggers the #946
  2307. // misparse and dropped the class — breaking subclass / type-hierarchy /
  2308. // inheritance-impact queries for effectively every gameplay class in a UE
  2309. // project. blankCppExportMacros recovers them.
  2310. it('recovers UE *_API classes and the inheritance edge (the issue repro)', () => {
  2311. const code = `class ENGINE_API UActorComponent { };
  2312. class MYGAME_API UMyComponent : public UActorComponent { };
  2313. `;
  2314. const result = extractFromSource('ue.cpp', code);
  2315. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  2316. expect(classes).toContain('UActorComponent'); // macro, no base — also was dropped
  2317. expect(classes).toContain('UMyComponent');
  2318. expect(result.nodes.find((n) => n.kind === 'function')).toBeUndefined(); // no phantom
  2319. expect(
  2320. result.unresolvedReferences.find(
  2321. (r) => r.referenceKind === 'extends' && r.referenceName === 'UActorComponent'
  2322. )
  2323. ).toBeTruthy();
  2324. });
  2325. it('blankCppExportMacros blanks only the header macro, offset-preserving', () => {
  2326. // Blanking replaces the macro with equal-length spaces, so the output is
  2327. // byte-for-byte the same length and identical *except* the macro is gone —
  2328. // every downstream line/column stays exact.
  2329. const check = (inp: string, macro: string, rest: string) => {
  2330. const out = blankCppExportMacros(inp);
  2331. expect(out.length).toBe(inp.length); // every byte offset preserved
  2332. expect(out).not.toContain(macro); // the macro token is blanked
  2333. expect(out.replace(/ +/g, ' ')).toBe(rest); // nothing else changed
  2334. };
  2335. // Generalizes across the export-macro space: UE _API, Qt/Boost _EXPORT,
  2336. // LLVM _ABI, bare API.
  2337. check(
  2338. 'class MYGAME_API UMyComponent : public UActorComponent { };',
  2339. 'MYGAME_API',
  2340. 'class UMyComponent : public UActorComponent { };'
  2341. );
  2342. check('struct MAPCORE_EXPORT W : B {}', 'MAPCORE_EXPORT', 'struct W : B {}');
  2343. check('class LLVM_ABI Foo {}', 'LLVM_ABI', 'class Foo {}');
  2344. });
  2345. it('does NOT blank an all-caps class NAME or an elaborated-type var decl', () => {
  2346. // The name itself being ALL-CAPS (with or without a base) must survive —
  2347. // the macro is only the token *before* the name, gated on a `: { ` def.
  2348. for (const c of [
  2349. 'class FOO { int x; };',
  2350. 'class FOO : public Base { int x; };',
  2351. 'struct BAR : public Base { int y; };',
  2352. 'enum class COLOR { Red, Green };',
  2353. // elaborated-type variable declarations end in ; = [ — never : {
  2354. 'struct FOO bar;',
  2355. 'class FOO obj = make();',
  2356. 'struct FOO arr[10];',
  2357. // a *_API macro used as an ordinary value elsewhere
  2358. 'int x = SOME_API; void f() { use(MYMODULE_API); }',
  2359. ]) {
  2360. expect(blankCppExportMacros(c)).toBe(c);
  2361. }
  2362. // And the all-caps-named class keeps its base edge through real extraction.
  2363. const result = extractFromSource('ctrl.cpp', 'class FOO : public Base { int x; };');
  2364. expect(result.nodes.find((n) => n.name === 'FOO')?.kind).toBe('class');
  2365. expect(
  2366. result.unresolvedReferences.find(
  2367. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base'
  2368. )
  2369. ).toBeTruthy();
  2370. });
  2371. });
  2372. describe('C++ forward declarations do not mint phantom class nodes (#1093)', () => {
  2373. // `class Foo;` parses as a bodiless class_specifier. Repeated across headers,
  2374. // each forward decl minted a phantom bodiless `class` node that crowded out —
  2375. // and could be picked as the blast-radius representative over — the single
  2376. // real definition. Bodiless struct/enum specifiers were already skipped;
  2377. // classes now are too, but ONLY for C/C++ (opt-in flag), never for languages
  2378. // where a bodiless class is a complete definition.
  2379. it('keeps only the real definition, dropping repeated forward decls', () => {
  2380. const code = `
  2381. class APXCharacter; // forward decl (header 1)
  2382. class APXCharacter; // forward decl (header 2)
  2383. friend class APXCharacter; // elaborated / friend forward reference
  2384. class APXCharacter { // the one real definition
  2385. int hp;
  2386. void takeDamage(int amount) { hp -= amount; }
  2387. };
  2388. `;
  2389. const result = extractFromSource('character.cpp', code);
  2390. const classes = result.nodes.filter(
  2391. (n) => n.kind === 'class' && n.name === 'APXCharacter'
  2392. );
  2393. // Exactly one class node, and it's the definition (carries the member).
  2394. expect(classes).toHaveLength(1);
  2395. expect(classes[0].startLine).toBe(6);
  2396. expect(
  2397. result.nodes.some((n) => n.kind === 'method' && n.name === 'takeDamage')
  2398. ).toBe(true);
  2399. });
  2400. it('elaborated type references in declarations create no phantom class', () => {
  2401. // `class Foo obj;` is a variable declaration using an elaborated type, not
  2402. // a class definition — it must not mint a `Foo` class node.
  2403. const result = extractFromSource('use.cpp', 'class Foo;\nvoid f() { class Foo *p = nullptr; (void)p; }\n');
  2404. expect(result.nodes.filter((n) => n.kind === 'class' && n.name === 'Foo')).toHaveLength(0);
  2405. });
  2406. it('does NOT affect languages where a bodiless class is complete', () => {
  2407. // Kotlin `class Empty` and Scala `trait`/`case object`/`class` with no body
  2408. // are complete definitions — the C/C++-only skip must leave them indexed.
  2409. const kt = extractFromSource('Empty.kt', 'class Empty\nclass Full { val x = 1 }\n');
  2410. const ktClasses = kt.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  2411. expect(ktClasses).toContain('Empty');
  2412. expect(ktClasses).toContain('Full');
  2413. const scala = extractFromSource('M.scala', 'trait Marker\ncase object Red\nclass Foo\n');
  2414. const scalaNames = scala.nodes
  2415. .filter((n) => ['class', 'trait', 'interface'].includes(n.kind))
  2416. .map((n) => n.name);
  2417. expect(scalaNames).toEqual(expect.arrayContaining(['Marker', 'Red', 'Foo']));
  2418. });
  2419. });
  2420. describe('C++ templated base-class inheritance (#1043)', () => {
  2421. // Inheriting from a template (`class D : public Base<int>`) recorded the base
  2422. // ref as the full instantiation `Base<int>`, which never name-matched the
  2423. // template indexed as the bare node `Base`. The `<…>` args are stripped so the
  2424. // `extends` reference matches.
  2425. it('strips template args from a templated base so the extends ref is the bare name', () => {
  2426. const code = `
  2427. template<typename T> class Base {};
  2428. template<typename D> class CRTPBase {};
  2429. namespace ns { template<typename T> class Tpl {}; }
  2430. class Plain {};
  2431. class Widget : public Base<int> {};
  2432. class App : public CRTPBase<App> {};
  2433. class Q : public ns::Tpl<int> {};
  2434. class Both : public Base<char>, public Plain {};
  2435. `;
  2436. const extendsRefs = extractFromSource('f.cpp', code).unresolvedReferences.filter(
  2437. (r) => r.referenceKind === 'extends'
  2438. );
  2439. const names = extendsRefs.map((r) => r.referenceName);
  2440. // Templated bases carry the bare name, NOT the `<…>` instantiation.
  2441. expect(names).toContain('Base'); // from Base<int> / Base<char>
  2442. expect(names).toContain('CRTPBase'); // from CRTPBase<App> (CRTP)
  2443. expect(names).toContain('ns::Tpl'); // qualified head preserved, args dropped
  2444. expect(names).toContain('Plain'); // non-templated base unchanged
  2445. // No reference still carries angle brackets.
  2446. expect(names.find((n) => n.includes('<'))).toBeUndefined();
  2447. });
  2448. it('stripCppTemplateArgs removes balanced <…> at any depth and is a no-op without them', () => {
  2449. expect(stripCppTemplateArgs('Base<int>')).toBe('Base');
  2450. expect(stripCppTemplateArgs('ns::Tpl<int>')).toBe('ns::Tpl');
  2451. expect(stripCppTemplateArgs('ns::Tpl<Foo<int>>')).toBe('ns::Tpl'); // nested
  2452. expect(stripCppTemplateArgs('Outer<int>::Inner')).toBe('Outer::Inner'); // mid-name
  2453. expect(stripCppTemplateArgs('Base')).toBe('Base'); // no-op
  2454. expect(stripCppTemplateArgs('ns::Plain')).toBe('ns::Plain'); // no-op qualified
  2455. });
  2456. });
  2457. describe('C++ stack-allocation construction (#1035)', () => {
  2458. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init) carry
  2459. // the constructor args directly on the declarator — no call/new node — so
  2460. // they emitted no constructor reference, unlike heap `new Calculator(0)`. An
  2461. // `instantiates` ref to the constructed type is now emitted for both.
  2462. const instNames = (code: string) =>
  2463. extractFromSource('f.cpp', `void run() {\n${code}\n}`)
  2464. .unresolvedReferences.filter((r) => r.referenceKind === 'instantiates')
  2465. .map((r) => r.referenceName);
  2466. it('emits an instantiates ref for direct-init and brace-init', () => {
  2467. expect(instNames('Calculator calc(0);')).toEqual(['Calculator']);
  2468. expect(instNames('Widget w{1, 2};')).toEqual(['Widget']);
  2469. });
  2470. it('strips template args and namespace to the bare class name', () => {
  2471. // `std::vector<int> v(10)` → `vector`; `ns::Widget w(0)` → `Widget`.
  2472. expect(instNames('std::vector<int> v(10);')).toEqual(['vector']);
  2473. expect(instNames('ns::Widget w(0);')).toEqual(['Widget']);
  2474. });
  2475. it('does not emit for primitives, default construction, or the most-vexing parse', () => {
  2476. expect(instNames('int x(5);')).toEqual([]); // primitive direct-init
  2477. expect(instNames('int y{6};')).toEqual([]); // primitive brace-init
  2478. expect(instNames('auto z = make();')).toEqual([]); // auto + call (handled elsewhere)
  2479. expect(instNames('Calculator deferred;')).toEqual([]); // default construction, no args
  2480. expect(instNames('Calculator calc();')).toEqual([]); // function declaration (most-vexing parse)
  2481. });
  2482. it('emits a single instantiates ref for a multi-declarator statement', () => {
  2483. // `Calculator a(1), b(2);` shares one `type` field; both construct a
  2484. // Calculator, so one ref suffices (it dedups to one edge regardless).
  2485. expect(instNames('Calculator a(1), b(2);')).toEqual(['Calculator']);
  2486. });
  2487. });
  2488. describe('C/C++ imports', () => {
  2489. it('should extract system include', () => {
  2490. const code = `#include <iostream>`;
  2491. const result = extractFromSource('main.cpp', code);
  2492. const importNode = result.nodes.find((n) => n.kind === 'import');
  2493. expect(importNode).toBeDefined();
  2494. expect(importNode?.name).toBe('iostream');
  2495. expect(importNode?.signature).toBe('#include <iostream>');
  2496. });
  2497. it('should extract system include with path', () => {
  2498. const code = `#include <nlohmann/json.hpp>`;
  2499. const result = extractFromSource('app.cpp', code);
  2500. const importNode = result.nodes.find((n) => n.kind === 'import');
  2501. expect(importNode).toBeDefined();
  2502. expect(importNode?.name).toBe('nlohmann/json.hpp');
  2503. });
  2504. it('should extract local include', () => {
  2505. const code = `#include "myheader.h"`;
  2506. const result = extractFromSource('main.cpp', code);
  2507. const importNode = result.nodes.find((n) => n.kind === 'import');
  2508. expect(importNode).toBeDefined();
  2509. expect(importNode?.name).toBe('myheader.h');
  2510. });
  2511. it('should extract C header', () => {
  2512. const code = `#include <stdio.h>`;
  2513. const result = extractFromSource('main.c', code);
  2514. const importNode = result.nodes.find((n) => n.kind === 'import');
  2515. expect(importNode).toBeDefined();
  2516. expect(importNode?.name).toBe('stdio.h');
  2517. });
  2518. it('should extract multiple includes', () => {
  2519. const code = `
  2520. #include <iostream>
  2521. #include <vector>
  2522. #include "config.h"
  2523. `;
  2524. const result = extractFromSource('app.cpp', code);
  2525. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2526. expect(importNodes.length).toBe(3);
  2527. const names = importNodes.map((n) => n.name);
  2528. expect(names).toContain('iostream');
  2529. expect(names).toContain('vector');
  2530. expect(names).toContain('config.h');
  2531. });
  2532. it('should create unresolved references for local includes', () => {
  2533. const code = `#include "myheader.h"`;
  2534. const result = extractFromSource('main.cpp', code);
  2535. const importRef = result.unresolvedReferences.find(
  2536. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  2537. );
  2538. expect(importRef).toBeDefined();
  2539. expect(importRef?.line).toBe(1);
  2540. });
  2541. it('should create unresolved references for system includes', () => {
  2542. const code = `#include <iostream>`;
  2543. const result = extractFromSource('main.cpp', code);
  2544. const importRef = result.unresolvedReferences.find(
  2545. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  2546. );
  2547. expect(importRef).toBeDefined();
  2548. });
  2549. });
  2550. describe('Dart imports', () => {
  2551. it('should extract dart: import', () => {
  2552. const code = `import 'dart:async';`;
  2553. const result = extractFromSource('main.dart', code);
  2554. const importNode = result.nodes.find((n) => n.kind === 'import');
  2555. expect(importNode).toBeDefined();
  2556. expect(importNode?.name).toBe('dart:async');
  2557. expect(importNode?.signature).toBe("import 'dart:async';");
  2558. });
  2559. it('should extract package import', () => {
  2560. const code = `import 'package:flutter/material.dart';`;
  2561. const result = extractFromSource('app.dart', code);
  2562. const importNode = result.nodes.find((n) => n.kind === 'import');
  2563. expect(importNode).toBeDefined();
  2564. expect(importNode?.name).toBe('package:flutter/material.dart');
  2565. });
  2566. it('should extract aliased import', () => {
  2567. const code = `import 'package:http/http.dart' as http;`;
  2568. const result = extractFromSource('api.dart', code);
  2569. const importNode = result.nodes.find((n) => n.kind === 'import');
  2570. expect(importNode).toBeDefined();
  2571. expect(importNode?.name).toBe('package:http/http.dart');
  2572. expect(importNode?.signature).toContain('as http');
  2573. });
  2574. it('should extract multiple imports', () => {
  2575. const code = `
  2576. import 'dart:async';
  2577. import 'dart:convert';
  2578. import 'package:flutter/material.dart';
  2579. `;
  2580. const result = extractFromSource('main.dart', code);
  2581. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2582. expect(importNodes.length).toBe(3);
  2583. const names = importNodes.map((n) => n.name);
  2584. expect(names).toContain('dart:async');
  2585. expect(names).toContain('dart:convert');
  2586. expect(names).toContain('package:flutter/material.dart');
  2587. });
  2588. it('should extract relative import', () => {
  2589. const code = `import '../utils/helpers.dart';`;
  2590. const result = extractFromSource('lib/main.dart', code);
  2591. const importNode = result.nodes.find((n) => n.kind === 'import');
  2592. expect(importNode).toBeDefined();
  2593. expect(importNode?.name).toBe('../utils/helpers.dart');
  2594. });
  2595. });
  2596. describe('Liquid imports', () => {
  2597. it('should extract render tag', () => {
  2598. const code = `{% render 'loading-spinner' %}`;
  2599. const result = extractFromSource('template.liquid', code);
  2600. const importNode = result.nodes.find((n) => n.kind === 'import');
  2601. expect(importNode).toBeDefined();
  2602. expect(importNode?.name).toBe('loading-spinner');
  2603. expect(importNode?.signature).toContain('render');
  2604. });
  2605. it('should extract section tag', () => {
  2606. const code = `{% section 'header' %}`;
  2607. const result = extractFromSource('layout/theme.liquid', code);
  2608. const importNode = result.nodes.find((n) => n.kind === 'import');
  2609. expect(importNode).toBeDefined();
  2610. expect(importNode?.name).toBe('header');
  2611. expect(importNode?.signature).toContain('section');
  2612. });
  2613. it('should extract include tag', () => {
  2614. const code = `{% include 'icon-cart' %}`;
  2615. const result = extractFromSource('snippets/header.liquid', code);
  2616. const importNode = result.nodes.find((n) => n.kind === 'import');
  2617. expect(importNode).toBeDefined();
  2618. expect(importNode?.name).toBe('icon-cart');
  2619. expect(importNode?.signature).toContain('include');
  2620. });
  2621. it('should extract render with whitespace control', () => {
  2622. const code = `{%- render 'price' -%}`;
  2623. const result = extractFromSource('snippets/product.liquid', code);
  2624. const importNode = result.nodes.find((n) => n.kind === 'import');
  2625. expect(importNode).toBeDefined();
  2626. expect(importNode?.name).toBe('price');
  2627. });
  2628. it('should extract multiple imports', () => {
  2629. const code = `
  2630. {% section 'header' %}
  2631. {% render 'loading-spinner' %}
  2632. {% render 'cart-drawer' %}
  2633. `;
  2634. const result = extractFromSource('layout/theme.liquid', code);
  2635. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2636. expect(importNodes.length).toBe(3);
  2637. const names = importNodes.map((n) => n.name);
  2638. expect(names).toContain('header');
  2639. expect(names).toContain('loading-spinner');
  2640. expect(names).toContain('cart-drawer');
  2641. });
  2642. });
  2643. });
  2644. // =============================================================================
  2645. // Pascal / Delphi Extraction
  2646. // =============================================================================
  2647. describe('Pascal / Delphi Extraction', () => {
  2648. describe('Language detection', () => {
  2649. it('should detect Pascal files', () => {
  2650. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2651. expect(detectLanguage('App.dpr')).toBe('pascal');
  2652. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2653. expect(detectLanguage('App.lpr')).toBe('pascal');
  2654. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2655. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2656. });
  2657. it('should report Pascal as supported', () => {
  2658. expect(isLanguageSupported('pascal')).toBe(true);
  2659. expect(getSupportedLanguages()).toContain('pascal');
  2660. });
  2661. });
  2662. describe('Unit extraction', () => {
  2663. it('should extract unit as module', () => {
  2664. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2665. const result = extractFromSource('MyUnit.pas', code);
  2666. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2667. expect(moduleNode).toBeDefined();
  2668. expect(moduleNode?.name).toBe('MyUnit');
  2669. expect(moduleNode?.language).toBe('pascal');
  2670. });
  2671. it('should extract program as module', () => {
  2672. const code = `program MyApp;\nbegin\nend.`;
  2673. const result = extractFromSource('MyApp.dpr', code);
  2674. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2675. expect(moduleNode).toBeDefined();
  2676. expect(moduleNode?.name).toBe('MyApp');
  2677. });
  2678. it('should fallback to filename when module name is empty', () => {
  2679. // Some .dpr templates use "program;" without a name
  2680. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2681. const result = extractFromSource('Console.dpr', code);
  2682. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2683. expect(moduleNode).toBeDefined();
  2684. expect(moduleNode?.name).toBe('Console');
  2685. });
  2686. });
  2687. describe('Uses clause (imports)', () => {
  2688. it('should extract uses as individual imports', () => {
  2689. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2690. const result = extractFromSource('Test.pas', code);
  2691. const imports = result.nodes.filter((n) => n.kind === 'import');
  2692. expect(imports.length).toBe(2);
  2693. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2694. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2695. });
  2696. it('should create unresolved references for imports', () => {
  2697. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2698. const result = extractFromSource('Test.pas', code);
  2699. const importRef = result.unresolvedReferences.find(
  2700. (r) => r.referenceKind === 'imports'
  2701. );
  2702. expect(importRef).toBeDefined();
  2703. expect(importRef?.referenceName).toBe('UAuth');
  2704. });
  2705. });
  2706. describe('Class extraction', () => {
  2707. it('should extract class declarations', () => {
  2708. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2709. const result = extractFromSource('Test.pas', code);
  2710. const classNode = result.nodes.find((n) => n.kind === 'class');
  2711. expect(classNode).toBeDefined();
  2712. expect(classNode?.name).toBe('TMyClass');
  2713. });
  2714. it('should extract class with inheritance', () => {
  2715. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2716. const result = extractFromSource('Test.pas', code);
  2717. const extendsRef = result.unresolvedReferences.find(
  2718. (r) => r.referenceKind === 'extends'
  2719. );
  2720. expect(extendsRef).toBeDefined();
  2721. expect(extendsRef?.referenceName).toBe('TParent');
  2722. });
  2723. it('should extract class with interface implementation', () => {
  2724. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2725. const result = extractFromSource('Test.pas', code);
  2726. const extendsRef = result.unresolvedReferences.find(
  2727. (r) => r.referenceKind === 'extends'
  2728. );
  2729. const implementsRef = result.unresolvedReferences.find(
  2730. (r) => r.referenceKind === 'implements'
  2731. );
  2732. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2733. expect(implementsRef?.referenceName).toBe('ILogger');
  2734. });
  2735. });
  2736. describe('Record extraction', () => {
  2737. it('should extract records as class nodes', () => {
  2738. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2739. const result = extractFromSource('Test.pas', code);
  2740. const classNode = result.nodes.find((n) => n.kind === 'class');
  2741. expect(classNode).toBeDefined();
  2742. expect(classNode?.name).toBe('TPoint');
  2743. const fields = result.nodes.filter((n) => n.kind === 'field');
  2744. expect(fields.length).toBe(2);
  2745. expect(fields.map((f) => f.name)).toContain('X');
  2746. expect(fields.map((f) => f.name)).toContain('Y');
  2747. });
  2748. });
  2749. describe('Interface extraction', () => {
  2750. it('should extract interface declarations', () => {
  2751. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2752. const result = extractFromSource('Test.pas', code);
  2753. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2754. expect(ifaceNode).toBeDefined();
  2755. expect(ifaceNode?.name).toBe('ILogger');
  2756. });
  2757. });
  2758. describe('Method extraction', () => {
  2759. it('should extract methods with visibility', () => {
  2760. 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.`;
  2761. const result = extractFromSource('Test.pas', code);
  2762. const methods = result.nodes.filter((n) => n.kind === 'method');
  2763. expect(methods.length).toBe(2);
  2764. const createMethod = methods.find((m) => m.name === 'Create');
  2765. expect(createMethod?.visibility).toBe('public');
  2766. const getValue = methods.find((m) => m.name === 'GetValue');
  2767. expect(getValue?.visibility).toBe('public');
  2768. const fields = result.nodes.filter((n) => n.kind === 'field');
  2769. const fValue = fields.find((f) => f.name === 'FValue');
  2770. expect(fValue?.visibility).toBe('private');
  2771. });
  2772. it('should detect static methods (class methods)', () => {
  2773. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2774. const result = extractFromSource('Test.pas', code);
  2775. const methods = result.nodes.filter((n) => n.kind === 'method');
  2776. const staticMethod = methods.find((m) => m.name === 'Create');
  2777. expect(staticMethod?.isStatic).toBe(true);
  2778. });
  2779. });
  2780. describe('Enum extraction', () => {
  2781. it('should extract enums with members', () => {
  2782. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2783. const result = extractFromSource('Test.pas', code);
  2784. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2785. expect(enumNode).toBeDefined();
  2786. expect(enumNode?.name).toBe('TColor');
  2787. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2788. expect(members.length).toBe(3);
  2789. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2790. });
  2791. });
  2792. describe('Property extraction', () => {
  2793. it('should extract properties', () => {
  2794. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2795. const result = extractFromSource('Test.pas', code);
  2796. const propNode = result.nodes.find((n) => n.kind === 'property');
  2797. expect(propNode).toBeDefined();
  2798. expect(propNode?.name).toBe('Name');
  2799. expect(propNode?.visibility).toBe('public');
  2800. });
  2801. });
  2802. describe('Constant extraction', () => {
  2803. it('should extract constants', () => {
  2804. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2805. const result = extractFromSource('Test.pas', code);
  2806. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2807. expect(constants.length).toBe(2);
  2808. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2809. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2810. });
  2811. });
  2812. describe('Type alias extraction', () => {
  2813. it('should extract type aliases', () => {
  2814. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2815. const result = extractFromSource('Test.pas', code);
  2816. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2817. expect(aliasNode).toBeDefined();
  2818. expect(aliasNode?.name).toBe('TUserName');
  2819. });
  2820. });
  2821. describe('Call extraction', () => {
  2822. it('should extract calls from implementation bodies', () => {
  2823. 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.`;
  2824. const result = extractFromSource('Test.pas', code);
  2825. const callRef = result.unresolvedReferences.find(
  2826. (r) => r.referenceKind === 'calls'
  2827. );
  2828. expect(callRef).toBeDefined();
  2829. expect(callRef?.referenceName).toBe('WriteLn');
  2830. });
  2831. });
  2832. describe('Containment edges', () => {
  2833. it('should create contains edges for class members', () => {
  2834. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2835. const result = extractFromSource('Test.pas', code);
  2836. const classNode = result.nodes.find((n) => n.kind === 'class');
  2837. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2838. expect(classNode).toBeDefined();
  2839. expect(methodNode).toBeDefined();
  2840. const containsEdge = result.edges.find(
  2841. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2842. );
  2843. expect(containsEdge).toBeDefined();
  2844. });
  2845. });
  2846. describe('Full fixture: UAuth.pas', () => {
  2847. const code = `unit UAuth;
  2848. interface
  2849. uses
  2850. System.SysUtils,
  2851. System.Classes;
  2852. type
  2853. ITokenValidator = interface
  2854. ['{11111111-1111-1111-1111-111111111111}']
  2855. function Validate(const AToken: string): Boolean;
  2856. end;
  2857. TAuthService = class(TInterfacedObject, ITokenValidator)
  2858. private
  2859. FToken: string;
  2860. FLoginCount: Integer;
  2861. procedure IncLoginCount;
  2862. protected
  2863. function GetToken: string;
  2864. public
  2865. constructor Create;
  2866. destructor Destroy; override;
  2867. function Validate(const AToken: string): Boolean;
  2868. function Login(const AUser, APass: string): string;
  2869. property Token: string read GetToken;
  2870. property LoginCount: Integer read FLoginCount;
  2871. end;
  2872. implementation
  2873. constructor TAuthService.Create;
  2874. begin
  2875. inherited Create;
  2876. FToken := '';
  2877. FLoginCount := 0;
  2878. end;
  2879. destructor TAuthService.Destroy;
  2880. begin
  2881. FToken := '';
  2882. inherited Destroy;
  2883. end;
  2884. procedure TAuthService.IncLoginCount;
  2885. begin
  2886. Inc(FLoginCount);
  2887. end;
  2888. function TAuthService.GetToken: string;
  2889. begin
  2890. Result := FToken;
  2891. end;
  2892. function TAuthService.Validate(const AToken: string): Boolean;
  2893. begin
  2894. Result := AToken <> '';
  2895. end;
  2896. function TAuthService.Login(const AUser, APass: string): string;
  2897. begin
  2898. IncLoginCount;
  2899. if Validate(AUser + ':' + APass) then
  2900. begin
  2901. FToken := AUser;
  2902. Result := 'ok';
  2903. end
  2904. else
  2905. Result := '';
  2906. end;
  2907. end.`;
  2908. it('should extract all expected nodes', () => {
  2909. const result = extractFromSource('UAuth.pas', code);
  2910. expect(result.errors).toHaveLength(0);
  2911. // Module
  2912. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2913. expect(moduleNode?.name).toBe('UAuth');
  2914. // Imports
  2915. const imports = result.nodes.filter((n) => n.kind === 'import');
  2916. expect(imports.length).toBe(2);
  2917. // Interface
  2918. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2919. expect(ifaceNode?.name).toBe('ITokenValidator');
  2920. // Class
  2921. const classNode = result.nodes.find((n) => n.kind === 'class');
  2922. expect(classNode?.name).toBe('TAuthService');
  2923. // Methods
  2924. const methods = result.nodes.filter((n) => n.kind === 'method');
  2925. expect(methods.length).toBeGreaterThanOrEqual(6);
  2926. expect(methods.map((m) => m.name)).toContain('Create');
  2927. expect(methods.map((m) => m.name)).toContain('Destroy');
  2928. expect(methods.map((m) => m.name)).toContain('Login');
  2929. // Fields
  2930. const fields = result.nodes.filter((n) => n.kind === 'field');
  2931. expect(fields.length).toBe(2);
  2932. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2933. // Properties
  2934. const props = result.nodes.filter((n) => n.kind === 'property');
  2935. expect(props.length).toBe(2);
  2936. expect(props.map((p) => p.name)).toContain('Token');
  2937. expect(props.map((p) => p.name)).toContain('LoginCount');
  2938. });
  2939. it('should extract inheritance and interface implementation', () => {
  2940. const result = extractFromSource('UAuth.pas', code);
  2941. const extendsRef = result.unresolvedReferences.find(
  2942. (r) => r.referenceKind === 'extends'
  2943. );
  2944. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2945. const implementsRef = result.unresolvedReferences.find(
  2946. (r) => r.referenceKind === 'implements'
  2947. );
  2948. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2949. });
  2950. it('should extract calls from implementation', () => {
  2951. const result = extractFromSource('UAuth.pas', code);
  2952. const callRefs = result.unresolvedReferences.filter(
  2953. (r) => r.referenceKind === 'calls'
  2954. );
  2955. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2956. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2957. });
  2958. });
  2959. describe('Full fixture: UTypes.pas', () => {
  2960. const code = `unit UTypes;
  2961. interface
  2962. uses
  2963. System.SysUtils;
  2964. const
  2965. C_MAX_RETRIES = 3;
  2966. C_DEFAULT_NAME = 'Guest';
  2967. type
  2968. TUserRole = (urAdmin, urEditor, urViewer);
  2969. TPoint2D = record
  2970. X: Double;
  2971. Y: Double;
  2972. end;
  2973. TUserName = string;
  2974. TUserInfo = class
  2975. public
  2976. type
  2977. TAddress = record
  2978. Street: string;
  2979. City: string;
  2980. Zip: string;
  2981. end;
  2982. private
  2983. FName: TUserName;
  2984. FRole: TUserRole;
  2985. FAddress: TAddress;
  2986. public
  2987. constructor Create(const AName: TUserName; ARole: TUserRole);
  2988. function GetDisplayName: string;
  2989. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2990. property Name: TUserName read FName write FName;
  2991. property Role: TUserRole read FRole;
  2992. property Address: TAddress read FAddress write FAddress;
  2993. end;
  2994. implementation
  2995. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2996. begin
  2997. FName := AName;
  2998. FRole := ARole;
  2999. end;
  3000. function TUserInfo.GetDisplayName: string;
  3001. begin
  3002. if FRole = urAdmin then
  3003. Result := '[Admin] ' + FName
  3004. else
  3005. Result := FName;
  3006. end;
  3007. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  3008. begin
  3009. Result := TUserInfo.Create(AName, urAdmin);
  3010. end;
  3011. end.`;
  3012. it('should extract enums with members', () => {
  3013. const result = extractFromSource('UTypes.pas', code);
  3014. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  3015. expect(enumNode?.name).toBe('TUserRole');
  3016. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3017. expect(members.length).toBe(3);
  3018. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  3019. });
  3020. it('should extract constants', () => {
  3021. const result = extractFromSource('UTypes.pas', code);
  3022. const constants = result.nodes.filter((n) => n.kind === 'constant');
  3023. expect(constants.length).toBe(2);
  3024. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  3025. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  3026. });
  3027. it('should extract type aliases', () => {
  3028. const result = extractFromSource('UTypes.pas', code);
  3029. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3030. expect(aliases.map((a) => a.name)).toContain('TUserName');
  3031. });
  3032. it('should extract records as classes with fields', () => {
  3033. const result = extractFromSource('UTypes.pas', code);
  3034. const classes = result.nodes.filter((n) => n.kind === 'class');
  3035. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  3036. // TPoint2D fields
  3037. const fields = result.nodes.filter((n) => n.kind === 'field');
  3038. expect(fields.map((f) => f.name)).toContain('X');
  3039. expect(fields.map((f) => f.name)).toContain('Y');
  3040. });
  3041. it('should extract static class methods', () => {
  3042. const result = extractFromSource('UTypes.pas', code);
  3043. const methods = result.nodes.filter((n) => n.kind === 'method');
  3044. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  3045. expect(staticMethod).toBeDefined();
  3046. expect(staticMethod?.isStatic).toBe(true);
  3047. });
  3048. it('should extract nested types', () => {
  3049. const result = extractFromSource('UTypes.pas', code);
  3050. const classes = result.nodes.filter((n) => n.kind === 'class');
  3051. expect(classes.map((c) => c.name)).toContain('TAddress');
  3052. });
  3053. });
  3054. });
  3055. // =============================================================================
  3056. // DFM/FMX Extraction
  3057. // =============================================================================
  3058. describe('DFM/FMX Extraction', () => {
  3059. it('should extract components from DFM', () => {
  3060. const code = `object Form1: TForm1
  3061. Left = 0
  3062. Top = 0
  3063. Caption = 'My Form'
  3064. object Button1: TButton
  3065. Left = 10
  3066. Top = 10
  3067. Caption = 'Click Me'
  3068. end
  3069. end`;
  3070. const result = extractFromSource('Form1.dfm', code);
  3071. const components = result.nodes.filter((n) => n.kind === 'component');
  3072. expect(components.length).toBe(2);
  3073. expect(components.map((c) => c.name)).toContain('Form1');
  3074. expect(components.map((c) => c.name)).toContain('Button1');
  3075. const button = components.find((c) => c.name === 'Button1');
  3076. expect(button?.signature).toBe('TButton');
  3077. });
  3078. it('should extract nested component hierarchy', () => {
  3079. const code = `object Form1: TForm1
  3080. object Panel1: TPanel
  3081. object Label1: TLabel
  3082. Caption = 'Hello'
  3083. end
  3084. end
  3085. end`;
  3086. const result = extractFromSource('Form1.dfm', code);
  3087. const components = result.nodes.filter((n) => n.kind === 'component');
  3088. expect(components.length).toBe(3);
  3089. // Check nesting: Panel1 contains Label1
  3090. const panel = components.find((c) => c.name === 'Panel1');
  3091. const label = components.find((c) => c.name === 'Label1');
  3092. const containsEdge = result.edges.find(
  3093. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  3094. );
  3095. expect(containsEdge).toBeDefined();
  3096. });
  3097. it('should extract event handler references', () => {
  3098. const code = `object Form1: TForm1
  3099. OnCreate = FormCreate
  3100. OnDestroy = FormDestroy
  3101. object Button1: TButton
  3102. OnClick = Button1Click
  3103. end
  3104. end`;
  3105. const result = extractFromSource('Form1.dfm', code);
  3106. const refs = result.unresolvedReferences;
  3107. expect(refs.length).toBe(3);
  3108. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  3109. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  3110. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  3111. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  3112. });
  3113. it('should handle multi-line properties', () => {
  3114. const code = `object Form1: TForm1
  3115. SQL.Strings = (
  3116. 'SELECT * FROM users'
  3117. 'WHERE active = 1')
  3118. object Button1: TButton
  3119. OnClick = Button1Click
  3120. end
  3121. end`;
  3122. const result = extractFromSource('Form1.dfm', code);
  3123. const components = result.nodes.filter((n) => n.kind === 'component');
  3124. expect(components.length).toBe(2);
  3125. const refs = result.unresolvedReferences;
  3126. expect(refs.length).toBe(1);
  3127. expect(refs[0]?.referenceName).toBe('Button1Click');
  3128. });
  3129. it('should handle inherited keyword', () => {
  3130. const code = `inherited Form1: TForm1
  3131. Caption = 'Inherited Form'
  3132. object Button1: TButton
  3133. OnClick = Button1Click
  3134. end
  3135. end`;
  3136. const result = extractFromSource('Form1.dfm', code);
  3137. const components = result.nodes.filter((n) => n.kind === 'component');
  3138. expect(components.length).toBe(2);
  3139. expect(components.map((c) => c.name)).toContain('Form1');
  3140. });
  3141. it('should handle item collection properties', () => {
  3142. const code = `object Form1: TForm1
  3143. object StatusBar1: TStatusBar
  3144. Panels = <
  3145. item
  3146. Width = 200
  3147. end
  3148. item
  3149. Width = 200
  3150. end>
  3151. end
  3152. end`;
  3153. const result = extractFromSource('Form1.dfm', code);
  3154. const components = result.nodes.filter((n) => n.kind === 'component');
  3155. expect(components.length).toBe(2);
  3156. });
  3157. describe('Full fixture: MainForm.dfm', () => {
  3158. const code = `object frmMain: TfrmMain
  3159. Left = 0
  3160. Top = 0
  3161. Caption = 'CodeGraph DFM Fixture'
  3162. ClientHeight = 480
  3163. ClientWidth = 640
  3164. OnCreate = FormCreate
  3165. OnDestroy = FormDestroy
  3166. object pnlTop: TPanel
  3167. Left = 0
  3168. Top = 0
  3169. Width = 640
  3170. Height = 50
  3171. object lblTitle: TLabel
  3172. Left = 16
  3173. Top = 16
  3174. Caption = 'Authentication Service'
  3175. end
  3176. object btnLogin: TButton
  3177. Left = 540
  3178. Top = 12
  3179. OnClick = btnLoginClick
  3180. end
  3181. end
  3182. object pnlContent: TPanel
  3183. Left = 0
  3184. Top = 50
  3185. object edtUsername: TEdit
  3186. Left = 16
  3187. Top = 16
  3188. OnChange = edtUsernameChange
  3189. end
  3190. object edtPassword: TEdit
  3191. Left = 16
  3192. Top = 48
  3193. OnKeyPress = edtPasswordKeyPress
  3194. end
  3195. object mmoLog: TMemo
  3196. Left = 16
  3197. Top = 88
  3198. end
  3199. end
  3200. object pnlStatus: TStatusBar
  3201. Left = 0
  3202. Top = 440
  3203. Panels = <
  3204. item
  3205. Width = 200
  3206. end
  3207. item
  3208. Width = 200
  3209. end>
  3210. end
  3211. end`;
  3212. it('should extract all components', () => {
  3213. const result = extractFromSource('MainForm.dfm', code);
  3214. const components = result.nodes.filter((n) => n.kind === 'component');
  3215. expect(components.length).toBe(9);
  3216. expect(components.map((c) => c.name)).toEqual(
  3217. expect.arrayContaining([
  3218. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  3219. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  3220. ])
  3221. );
  3222. });
  3223. it('should extract all event handlers', () => {
  3224. const result = extractFromSource('MainForm.dfm', code);
  3225. const refs = result.unresolvedReferences;
  3226. expect(refs.length).toBe(5);
  3227. expect(refs.map((r) => r.referenceName)).toEqual(
  3228. expect.arrayContaining([
  3229. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  3230. 'edtUsernameChange', 'edtPasswordKeyPress',
  3231. ])
  3232. );
  3233. });
  3234. });
  3235. });
  3236. describe('Kotlin Multiplatform expect/actual', () => {
  3237. let tempDir: string;
  3238. let cg: CodeGraph;
  3239. beforeEach(() => {
  3240. tempDir = createTempDir();
  3241. });
  3242. afterEach(() => {
  3243. if (cg) cg.close();
  3244. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3245. });
  3246. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  3247. const common = path.join(tempDir, 'src', 'commonMain');
  3248. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3249. fs.mkdirSync(common, { recursive: true });
  3250. fs.mkdirSync(jvm, { recursive: true });
  3251. // common source set: expect declarations + a caller that uses them
  3252. fs.writeFileSync(
  3253. path.join(common, 'SystemProps.kt'),
  3254. `package demo.internal
  3255. expect fun systemProp(name: String): String?
  3256. expect class Platform {
  3257. fun describe(): String
  3258. }
  3259. `
  3260. );
  3261. fs.writeFileSync(
  3262. path.join(common, 'Caller.kt'),
  3263. `package demo
  3264. import demo.internal.systemProp
  3265. import demo.internal.Platform
  3266. fun useIt(): String {
  3267. val v = systemProp("os.name")
  3268. return Platform().describe() + v
  3269. }
  3270. `
  3271. );
  3272. // jvm source set: actual implementations
  3273. fs.writeFileSync(
  3274. path.join(jvm, 'SystemProps.kt'),
  3275. `package demo.internal
  3276. actual fun systemProp(name: String): String? = System.getProperty(name)
  3277. actual class Platform {
  3278. actual fun describe(): String = "JVM"
  3279. }
  3280. `
  3281. );
  3282. cg = CodeGraph.initSync(tempDir);
  3283. await cg.indexAll();
  3284. cg.resolveReferences();
  3285. // The expect/actual markers are captured onto the node's decorators.
  3286. const fns = cg.getNodesByKind('function');
  3287. const actualFn = fns.find(
  3288. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  3289. );
  3290. const expectFn = fns.find(
  3291. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  3292. );
  3293. expect(actualFn).toBeDefined();
  3294. expect(expectFn).toBeDefined();
  3295. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  3296. // Editing the JVM actual must surface the common expect AND its caller —
  3297. // before the expect/actual bridge the actual had zero dependents.
  3298. const impact = cg.getImpactRadius(actualFn!.id, 3);
  3299. const impacted = [...impact.nodes.values()].map((n) => n.name);
  3300. expect(impacted).toContain('systemProp'); // the common expect
  3301. expect(impacted).toContain('useIt'); // the caller, reached transitively
  3302. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  3303. const bridge = impact.edges.find(
  3304. (e) =>
  3305. e.target === actualFn!.id &&
  3306. e.provenance === 'heuristic' &&
  3307. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3308. 'kotlin-expect-actual'
  3309. );
  3310. expect(bridge).toBeDefined();
  3311. expect(bridge!.source).toBe(expectFn!.id);
  3312. });
  3313. it('links an expect class to an actual typealias (different node kinds)', async () => {
  3314. const common = path.join(tempDir, 'src', 'commonMain');
  3315. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3316. fs.mkdirSync(common, { recursive: true });
  3317. fs.mkdirSync(jvm, { recursive: true });
  3318. fs.writeFileSync(
  3319. path.join(common, 'Lock.kt'),
  3320. `package demo
  3321. expect class Lock {
  3322. fun acquire()
  3323. }
  3324. `
  3325. );
  3326. fs.writeFileSync(
  3327. path.join(jvm, 'Lock.kt'),
  3328. `package demo
  3329. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  3330. `
  3331. );
  3332. cg = CodeGraph.initSync(tempDir);
  3333. await cg.indexAll();
  3334. cg.resolveReferences();
  3335. const aliasNode = cg
  3336. .getNodesByKind('type_alias')
  3337. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  3338. expect(aliasNode).toBeDefined();
  3339. // The actual typealias is now a cross-file dependency target (linked from
  3340. // the expect class), so it participates in impact rather than being orphaned.
  3341. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  3342. const bridge = impact.edges.find(
  3343. (e) =>
  3344. e.target === aliasNode!.id &&
  3345. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3346. 'kotlin-expect-actual'
  3347. );
  3348. expect(bridge).toBeDefined();
  3349. });
  3350. });
  3351. describe('Scala cross-file dependencies', () => {
  3352. let tempDir: string;
  3353. let cg: CodeGraph;
  3354. beforeEach(() => {
  3355. tempDir = createTempDir();
  3356. });
  3357. afterEach(() => {
  3358. if (cg) cg.close();
  3359. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3360. });
  3361. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  3362. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  3363. fs.mkdirSync(src, { recursive: true });
  3364. fs.writeFileSync(
  3365. path.join(src, 'Semigroup.scala'),
  3366. `package demo
  3367. trait Semigroup[A] {
  3368. def combine(x: A, y: A): A
  3369. }
  3370. `
  3371. );
  3372. fs.writeFileSync(
  3373. path.join(src, 'Monoid.scala'),
  3374. `package demo
  3375. trait Monoid[A] extends Semigroup[A] {
  3376. def empty: A
  3377. }
  3378. `
  3379. );
  3380. fs.writeFileSync(
  3381. path.join(src, 'Instances.scala'),
  3382. `package demo
  3383. object Instances {
  3384. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  3385. def empty: Int = 0
  3386. def combine(x: Int, y: Int): Int = x + y
  3387. }
  3388. }
  3389. `
  3390. );
  3391. fs.writeFileSync(
  3392. path.join(src, 'Folding.scala'),
  3393. `package demo
  3394. object Folding {
  3395. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  3396. xs.foldLeft(M.empty)(M.combine)
  3397. }
  3398. `
  3399. );
  3400. cg = CodeGraph.initSync(tempDir);
  3401. await cg.indexAll();
  3402. cg.resolveReferences();
  3403. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  3404. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  3405. expect(monoid).toBeDefined();
  3406. expect(semigroup).toBeDefined();
  3407. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  3408. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  3409. // the whole point of the fix (the `[A]` used to defeat name matching).
  3410. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  3411. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  3412. // Editing Monoid surfaces the cross-file users: the instance val typed
  3413. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  3414. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  3415. expect(impacted).toContain('intMonoid'); // field type annotation
  3416. expect(impacted).toContain('fold'); // trailing implicit parameter list
  3417. });
  3418. });
  3419. describe('PHP namespace + import resolution', () => {
  3420. let tempDir: string;
  3421. let cg: CodeGraph;
  3422. beforeEach(() => {
  3423. tempDir = createTempDir();
  3424. });
  3425. afterEach(() => {
  3426. if (cg) cg.close();
  3427. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3428. });
  3429. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  3430. const src = path.join(tempDir, 'src');
  3431. // Two interfaces with the SAME simple name in different namespaces — the
  3432. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  3433. // resolve. The namespace qualifies them; the `use` import disambiguates.
  3434. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  3435. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  3436. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  3437. fs.writeFileSync(
  3438. path.join(src, 'Cache', 'Factory.php'),
  3439. `<?php
  3440. namespace Contracts\\Cache;
  3441. interface Factory {
  3442. public function store(): object;
  3443. }
  3444. `
  3445. );
  3446. fs.writeFileSync(
  3447. path.join(src, 'Mail', 'Factory.php'),
  3448. `<?php
  3449. namespace Contracts\\Mail;
  3450. interface Factory {
  3451. public function mailer(): object;
  3452. }
  3453. `
  3454. );
  3455. fs.writeFileSync(
  3456. path.join(src, 'App', 'Service.php'),
  3457. `<?php
  3458. namespace App;
  3459. use Contracts\\Cache\\Factory;
  3460. class Service {
  3461. public function make(): Factory {
  3462. return resolve(Factory::class);
  3463. }
  3464. }
  3465. `
  3466. );
  3467. cg = CodeGraph.initSync(tempDir);
  3468. await cg.indexAll();
  3469. cg.resolveReferences();
  3470. // The PHP namespace is captured into the qualified name, so the two
  3471. // same-named interfaces are distinguishable.
  3472. const cacheFactory = cg
  3473. .getNodesByKind('interface')
  3474. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  3475. const mailFactory = cg
  3476. .getNodesByKind('interface')
  3477. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  3478. expect(cacheFactory).toBeDefined();
  3479. expect(mailFactory).toBeDefined();
  3480. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  3481. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  3482. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  3483. const serviceFile = 'src/App/Service.php';
  3484. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  3485. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3486. );
  3487. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  3488. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3489. );
  3490. expect(cacheReaches).toBe(true);
  3491. expect(mailReaches).toBe(false);
  3492. });
  3493. });
  3494. describe('Ruby mixins (include/extend/prepend)', () => {
  3495. let tempDir: string;
  3496. let cg: CodeGraph;
  3497. beforeEach(() => {
  3498. tempDir = createTempDir();
  3499. });
  3500. afterEach(() => {
  3501. if (cg) cg.close();
  3502. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3503. });
  3504. it('links include/extend/prepend to the mixed-in module across files', async () => {
  3505. const lib = path.join(tempDir, 'lib');
  3506. fs.mkdirSync(lib, { recursive: true });
  3507. fs.writeFileSync(
  3508. path.join(lib, 'concerns.rb'),
  3509. `module Trackable
  3510. def track; end
  3511. end
  3512. module Cacheable
  3513. def cache; end
  3514. end
  3515. module Loggable
  3516. def log; end
  3517. end
  3518. `
  3519. );
  3520. fs.writeFileSync(
  3521. path.join(lib, 'model.rb'),
  3522. `class Model
  3523. include Trackable
  3524. prepend Cacheable
  3525. extend Loggable
  3526. end
  3527. `
  3528. );
  3529. cg = CodeGraph.initSync(tempDir);
  3530. await cg.indexAll();
  3531. cg.resolveReferences();
  3532. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  3533. expect(model).toBeDefined();
  3534. // All three mixin forms create an `implements` edge Model → module, so
  3535. // editing a concern surfaces every class that mixes it in (across files).
  3536. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  3537. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  3538. expect(mod, moduleName).toBeDefined();
  3539. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  3540. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  3541. }
  3542. });
  3543. it('resolves require / require_relative to the required file', async () => {
  3544. const lib = path.join(tempDir, 'lib');
  3545. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  3546. // A leaf file whose class is referenced only dynamically — so without
  3547. // require resolution it would look like nothing depends on it.
  3548. fs.writeFileSync(
  3549. path.join(lib, 'app', 'fetcher.rb'),
  3550. `module App
  3551. class Fetcher
  3552. def fetch; end
  3553. end
  3554. end
  3555. `
  3556. );
  3557. // Pulled in by a load-path `require` …
  3558. fs.writeFileSync(
  3559. path.join(lib, 'app', 'worker.rb'),
  3560. `require "app/fetcher"
  3561. module App
  3562. class Worker; end
  3563. end
  3564. `
  3565. );
  3566. // … and a sibling pulled in by `require_relative`.
  3567. fs.writeFileSync(
  3568. path.join(lib, 'app', 'boot.rb'),
  3569. `require_relative "fetcher"
  3570. `
  3571. );
  3572. cg = CodeGraph.initSync(tempDir);
  3573. await cg.indexAll();
  3574. cg.resolveReferences();
  3575. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3576. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3577. // (boot.rb) — without require resolution its file would have no dependents.
  3578. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3579. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3580. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3581. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3582. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3583. });
  3584. });
  3585. describe('C++ free-function name extraction', () => {
  3586. let tempDir: string;
  3587. let cg: CodeGraph;
  3588. beforeEach(() => {
  3589. tempDir = createTempDir();
  3590. });
  3591. afterEach(() => {
  3592. if (cg) cg.close();
  3593. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3594. });
  3595. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3596. const src = path.join(tempDir, 'src');
  3597. fs.mkdirSync(src, { recursive: true });
  3598. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3599. // `auto … -> std::string` trailing return type. Both used to be named
  3600. // `string` (picked up from the parameter / return type), so callers never
  3601. // resolved and the defining file looked like nothing depended on it.
  3602. fs.writeFileSync(
  3603. path.join(src, 'names.cc'),
  3604. `#include <string>
  3605. std::string TableFileName(const std::string& dbname, int number) {
  3606. return dbname;
  3607. }
  3608. auto BuildName(const std::string& a) -> std::string {
  3609. return a;
  3610. }
  3611. `
  3612. );
  3613. fs.writeFileSync(
  3614. path.join(src, 'user.cc'),
  3615. `#include <string>
  3616. std::string use() {
  3617. return TableFileName("db", 1) + BuildName("x");
  3618. }
  3619. `
  3620. );
  3621. cg = CodeGraph.initSync(tempDir);
  3622. await cg.indexAll();
  3623. cg.resolveReferences();
  3624. // The functions are extracted under their real names, not `string`.
  3625. const fns = cg.getNodesByKind('function');
  3626. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3627. const buildFn = fns.find((n) => n.name === 'BuildName');
  3628. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3629. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3630. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3631. for (const fn of [tableFn!, buildFn!]) {
  3632. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3633. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3634. }
  3635. });
  3636. });
  3637. describe('Dart mixins and type references', () => {
  3638. let tempDir: string;
  3639. let cg: CodeGraph;
  3640. beforeEach(() => {
  3641. tempDir = createTempDir();
  3642. });
  3643. afterEach(() => {
  3644. if (cg) cg.close();
  3645. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3646. });
  3647. it('links `with` mixins and method parameter/return types across files', async () => {
  3648. const lib = path.join(tempDir, 'lib');
  3649. fs.mkdirSync(lib, { recursive: true });
  3650. fs.writeFileSync(
  3651. path.join(lib, 'models.dart'),
  3652. `class User {
  3653. final String name;
  3654. User(this.name);
  3655. }
  3656. mixin Loggable {
  3657. void log() {}
  3658. }
  3659. abstract class Repository {
  3660. User find(int id);
  3661. }
  3662. `
  3663. );
  3664. fs.writeFileSync(
  3665. path.join(lib, 'service.dart'),
  3666. `import 'models.dart';
  3667. class UserService extends Repository with Loggable {
  3668. @override
  3669. User find(int id) => User('x');
  3670. List<User> all() => [];
  3671. }
  3672. `
  3673. );
  3674. cg = CodeGraph.initSync(tempDir);
  3675. await cg.indexAll();
  3676. cg.resolveReferences();
  3677. const inModels = (name: string) =>
  3678. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3679. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3680. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3681. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3682. // as a class-like node.
  3683. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3684. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3685. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3686. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3687. expect(mixinUsers).toContain('UserService');
  3688. // `User` is used only as a method parameter/return type in service.dart —
  3689. // editing it must still surface service.dart via the type references.
  3690. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3691. expect(user, 'User indexed').toBeDefined();
  3692. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3693. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3694. });
  3695. });
  3696. describe('Static-member / value-read references', () => {
  3697. let tempDir: string;
  3698. let cg: CodeGraph;
  3699. beforeEach(() => {
  3700. tempDir = createTempDir();
  3701. });
  3702. afterEach(() => {
  3703. if (cg) cg.close();
  3704. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3705. });
  3706. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3707. fs.writeFileSync(
  3708. path.join(tempDir, 'JsonScope.java'),
  3709. `class JsonScope {
  3710. static final int EMPTY_DOCUMENT = 1;
  3711. }
  3712. `
  3713. );
  3714. fs.writeFileSync(
  3715. path.join(tempDir, 'Reader.java'),
  3716. `class Reader {
  3717. private int helper;
  3718. int peek() {
  3719. return JsonScope.EMPTY_DOCUMENT;
  3720. }
  3721. int noop() {
  3722. return this.helper;
  3723. }
  3724. }
  3725. `
  3726. );
  3727. cg = CodeGraph.initSync(tempDir);
  3728. await cg.indexAll();
  3729. cg.resolveReferences();
  3730. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3731. // read — never constructed or called), so before the static-member pass it
  3732. // had no dependents. Editing it now surfaces Reader.java.
  3733. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3734. expect(scope, 'JsonScope indexed').toBeDefined();
  3735. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3736. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3737. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3738. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3739. // should appear as a reference target from peek/noop beyond JsonScope.
  3740. const refTargets = cg
  3741. .getNodesByKind('class')
  3742. .filter((n) => n.name === 'this' || n.name === 'helper');
  3743. expect(refTargets.length).toBe(0);
  3744. });
  3745. it('does not link a static-member read across language families (coincidental name)', async () => {
  3746. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3747. // NOT link to a coincidentally same-named TS class (the cross-language false
  3748. // positive that name-matching produces; `references` edges are language-local).
  3749. fs.writeFileSync(
  3750. path.join(tempDir, 'Build.ts'),
  3751. `export class Build {\n static version = 1;\n}\n`
  3752. );
  3753. fs.writeFileSync(
  3754. path.join(tempDir, 'Device.kt'),
  3755. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3756. );
  3757. cg = CodeGraph.initSync(tempDir);
  3758. await cg.indexAll();
  3759. cg.resolveReferences();
  3760. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3761. expect(tsBuild).toBeDefined();
  3762. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3763. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3764. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3765. });
  3766. });
  3767. describe('Cross-language type/import gate (RN name collisions)', () => {
  3768. let tempDir: string;
  3769. let cg: CodeGraph;
  3770. beforeEach(() => {
  3771. tempDir = createTempDir();
  3772. });
  3773. afterEach(() => {
  3774. if (cg) cg.close();
  3775. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3776. });
  3777. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3778. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3779. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3780. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3781. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3782. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3783. // is intentionally NOT imported: a clean relative import would mask the bug
  3784. // by resolving via the import map before the framework strategy can win.
  3785. fs.writeFileSync(
  3786. path.join(tempDir, 'package.json'),
  3787. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3788. );
  3789. fs.writeFileSync(
  3790. path.join(tempDir, 'useTests.ts'),
  3791. `export type TestRunner = { run: () => void };\n`
  3792. );
  3793. fs.writeFileSync(
  3794. path.join(tempDir, 'basic.tsx'),
  3795. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3796. );
  3797. fs.writeFileSync(
  3798. path.join(tempDir, 'TestUtils.kt'),
  3799. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3800. );
  3801. cg = CodeGraph.initSync(tempDir);
  3802. await cg.indexAll();
  3803. cg.resolveReferences();
  3804. const ktRunner = cg
  3805. .getNodesByKind('class')
  3806. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3807. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3808. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3809. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3810. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3811. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3812. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3813. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3814. });
  3815. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3816. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3817. // create a web→apple dependency — but a sibling TS module imported by
  3818. // another TS file (same family) must still resolve (no over-gating).
  3819. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3820. fs.writeFileSync(
  3821. path.join(tempDir, 'widget.ts'),
  3822. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3823. );
  3824. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3825. fs.writeFileSync(
  3826. path.join(tempDir, 'app.ts'),
  3827. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3828. );
  3829. cg = CodeGraph.initSync(tempDir);
  3830. await cg.indexAll();
  3831. cg.resolveReferences();
  3832. const swiftWidget = cg
  3833. .getNodesByKind('class')
  3834. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3835. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3836. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3837. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3838. // Same-family control — the TS Helper must still see its TS dependent.
  3839. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3840. expect(helper, 'TS Helper class').toBeDefined();
  3841. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3842. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3843. });
  3844. });
  3845. describe('Python absolute module import resolution', () => {
  3846. let tempDir: string;
  3847. let cg: CodeGraph;
  3848. beforeEach(() => {
  3849. tempDir = createTempDir();
  3850. });
  3851. afterEach(() => {
  3852. if (cg) cg.close();
  3853. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3854. });
  3855. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3856. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3857. // dotted absolute module import) had no edge to the module file — only
  3858. // `from x import y` was linked — so a module imported by its dotted path
  3859. // looked like nothing depended on it.
  3860. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3861. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3862. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3863. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3864. fs.writeFileSync(
  3865. path.join(tempDir, 'conduit/apps/app.py'),
  3866. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3867. );
  3868. cg = CodeGraph.initSync(tempDir);
  3869. await cg.indexAll();
  3870. cg.resolveReferences();
  3871. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3872. expect(signals, 'signals.py indexed').toBeDefined();
  3873. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3874. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3875. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3876. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3877. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3878. });
  3879. it('Django include() links the root URLconf to the included app urls module', async () => {
  3880. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3881. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3882. // surfaces the project urlconf that mounts them.
  3883. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3884. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3885. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3886. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3887. fs.writeFileSync(
  3888. path.join(tempDir, 'app/urls.py'),
  3889. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3890. );
  3891. fs.writeFileSync(
  3892. path.join(tempDir, 'urls.py'),
  3893. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3894. );
  3895. cg = CodeGraph.initSync(tempDir);
  3896. await cg.indexAll();
  3897. cg.resolveReferences();
  3898. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3899. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3900. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3901. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3902. });
  3903. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3904. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3905. // with same-named modules in sibling packages must resolve via the import's
  3906. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3907. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3908. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3909. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3910. fs.writeFileSync(path.join(tempDir, p), '');
  3911. }
  3912. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3913. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3914. fs.writeFileSync(
  3915. path.join(tempDir, 'app/api/routes/api.py'),
  3916. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3917. );
  3918. cg = CodeGraph.initSync(tempDir);
  3919. await cg.indexAll();
  3920. cg.resolveReferences();
  3921. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3922. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3923. expect(routesAuth && depsAuth).toBeTruthy();
  3924. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3925. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3926. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3927. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3928. });
  3929. });
  3930. describe('Razor / Blazor markup extraction', () => {
  3931. let tempDir: string;
  3932. let cg: CodeGraph;
  3933. beforeEach(() => {
  3934. tempDir = createTempDir();
  3935. });
  3936. afterEach(() => {
  3937. if (cg) cg.close();
  3938. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3939. });
  3940. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  3941. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  3942. fs.writeFileSync(
  3943. path.join(tempDir, 'LoginViewModel.cs'),
  3944. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  3945. );
  3946. fs.writeFileSync(
  3947. path.join(tempDir, 'ToastComponent.cs'),
  3948. `namespace App { public class ToastComponent { } }`
  3949. );
  3950. fs.writeFileSync(
  3951. path.join(tempDir, 'Views/Login.cshtml'),
  3952. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  3953. );
  3954. fs.writeFileSync(
  3955. path.join(tempDir, 'Index.razor'),
  3956. `<div>\n <ToastComponent />\n</div>\n`
  3957. );
  3958. cg = CodeGraph.initSync(tempDir);
  3959. await cg.indexAll();
  3960. cg.resolveReferences();
  3961. // `@model LoginViewModel` → the view-model class.
  3962. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  3963. expect(vm, 'LoginViewModel class').toBeDefined();
  3964. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3965. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  3966. // `<ToastComponent />` → the component class.
  3967. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  3968. expect(toast, 'ToastComponent class').toBeDefined();
  3969. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3970. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  3971. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  3972. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  3973. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  3974. });
  3975. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  3976. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  3977. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  3978. cg = CodeGraph.initSync(tempDir);
  3979. await cg.indexAll();
  3980. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  3981. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  3982. const qns = brands.map((b) => b.qualifiedName).sort();
  3983. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  3984. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  3985. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  3986. });
  3987. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  3988. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  3989. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  3990. // ref must resolve to the DTO, not the same-named entity.
  3991. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  3992. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  3993. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  3994. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  3995. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  3996. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  3997. fs.writeFileSync(
  3998. path.join(tempDir, 'Pages/List.razor'),
  3999. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  4000. );
  4001. cg = CodeGraph.initSync(tempDir);
  4002. await cg.indexAll();
  4003. cg.resolveReferences();
  4004. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  4005. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  4006. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  4007. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4008. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4009. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  4010. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  4011. });
  4012. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  4013. fs.writeFileSync(
  4014. path.join(tempDir, 'CatalogService.cs'),
  4015. `namespace App { public class CatalogService { public void Load() { } } }`
  4016. );
  4017. fs.writeFileSync(
  4018. path.join(tempDir, 'List.razor'),
  4019. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  4020. );
  4021. cg = CodeGraph.initSync(tempDir);
  4022. await cg.indexAll();
  4023. cg.resolveReferences();
  4024. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  4025. expect(svc, 'CatalogService class').toBeDefined();
  4026. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4027. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  4028. });
  4029. });
  4030. describe('Default import resolution (renamed default export)', () => {
  4031. let tempDir: string;
  4032. let cg: CodeGraph;
  4033. beforeEach(() => {
  4034. tempDir = createTempDir();
  4035. });
  4036. afterEach(() => {
  4037. if (cg) cg.close();
  4038. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4039. });
  4040. it('links a renamed default import to the module file', async () => {
  4041. // Express route aggregator: `import articlesController from './controller'`
  4042. // where the module does `export default router`. The renamed local can't be
  4043. // found as a symbol, so the controller file had no dependent — the dependency
  4044. // is on the module file regardless of the default export's name.
  4045. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  4046. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  4047. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  4048. cg = CodeGraph.initSync(tempDir);
  4049. await cg.indexAll();
  4050. cg.resolveReferences();
  4051. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  4052. expect(controller, 'controller.ts indexed').toBeDefined();
  4053. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4054. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  4055. });
  4056. });
  4057. describe('Chained method-call resolution (C# extension methods)', () => {
  4058. let tempDir: string;
  4059. let cg: CodeGraph;
  4060. beforeEach(() => {
  4061. tempDir = createTempDir();
  4062. });
  4063. afterEach(() => {
  4064. if (cg) cg.close();
  4065. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4066. });
  4067. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  4068. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  4069. // static extension method elsewhere. A multi-dot receiver chain matched no
  4070. // method-call pattern before, so the extension method had no caller.
  4071. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  4072. fs.writeFileSync(
  4073. path.join(tempDir, 'cfg/Ext.cs'),
  4074. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  4075. );
  4076. fs.writeFileSync(
  4077. path.join(tempDir, 'Program.cs'),
  4078. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  4079. );
  4080. cg = CodeGraph.initSync(tempDir);
  4081. await cg.indexAll();
  4082. cg.resolveReferences();
  4083. const ext = cg
  4084. .getNodesByKind('method')
  4085. .find((n) => n.name === 'AddCoreServices')
  4086. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  4087. expect(ext, 'AddCoreServices defined').toBeDefined();
  4088. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4089. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  4090. });
  4091. });
  4092. describe('Same-directory include + KMP import resolution', () => {
  4093. let tempDir: string;
  4094. let cg: CodeGraph;
  4095. beforeEach(() => {
  4096. tempDir = createTempDir();
  4097. });
  4098. afterEach(() => {
  4099. if (cg) cg.close();
  4100. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4101. });
  4102. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  4103. // A multi-platform native module has a header of the same basename per
  4104. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  4105. // sibling header — not `apple/Storage.h` (which sorts first and so was
  4106. // picked arbitrarily before, leaving the real local header with 0 deps).
  4107. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  4108. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  4109. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4110. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4111. fs.writeFileSync(
  4112. path.join(tempDir, 'windows', 'Provider.cpp'),
  4113. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  4114. );
  4115. cg = CodeGraph.initSync(tempDir);
  4116. await cg.indexAll();
  4117. cg.resolveReferences();
  4118. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  4119. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  4120. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  4121. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  4122. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4123. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4124. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  4125. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  4126. });
  4127. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  4128. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  4129. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  4130. fs.mkdirSync(common, { recursive: true });
  4131. fs.mkdirSync(android, { recursive: true });
  4132. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  4133. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  4134. fs.writeFileSync(
  4135. path.join(common, 'Db.kt'),
  4136. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  4137. );
  4138. cg = CodeGraph.initSync(tempDir);
  4139. await cg.indexAll();
  4140. cg.resolveReferences();
  4141. const expectCtx = cg
  4142. .getNodesByKind('class')
  4143. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  4144. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  4145. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4146. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  4147. });
  4148. });
  4149. describe('Delphi form code-behind pairing', () => {
  4150. let tempDir: string;
  4151. let cg: CodeGraph;
  4152. beforeEach(() => {
  4153. tempDir = createTempDir();
  4154. });
  4155. afterEach(() => {
  4156. if (cg) cg.close();
  4157. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4158. });
  4159. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  4160. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  4161. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  4162. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  4163. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  4164. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  4165. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  4166. cg = CodeGraph.initSync(tempDir);
  4167. await cg.indexAll();
  4168. cg.resolveReferences();
  4169. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  4170. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  4171. const deps = cg.getFileDependents(dfm!.filePath);
  4172. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  4173. });
  4174. });
  4175. describe('Liquid Shopify JSON template section resolution', () => {
  4176. let tempDir: string;
  4177. let cg: CodeGraph;
  4178. beforeEach(() => {
  4179. tempDir = createTempDir();
  4180. });
  4181. afterEach(() => {
  4182. if (cg) cg.close();
  4183. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4184. });
  4185. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  4186. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  4187. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  4188. // looked unused. The JSON is now indexed and its `type`s linked.
  4189. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  4190. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  4191. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  4192. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  4193. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  4194. // Nested template dir (templates/customers/login.json) must resolve too.
  4195. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  4196. cg = CodeGraph.initSync(tempDir);
  4197. await cg.indexAll();
  4198. cg.resolveReferences();
  4199. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  4200. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  4201. expect(product, 'main-product section').toBeDefined();
  4202. expect(login, 'main-login section').toBeDefined();
  4203. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  4204. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  4205. });
  4206. });
  4207. describe('Lua/Luau require resolution', () => {
  4208. let tempDir: string;
  4209. let cg: CodeGraph;
  4210. beforeEach(() => {
  4211. tempDir = createTempDir();
  4212. });
  4213. afterEach(() => {
  4214. if (cg) cg.close();
  4215. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4216. });
  4217. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  4218. // The require is the ONLY link (no method call), so coverage here proves the
  4219. // require resolver specifically, not method-call name-matching.
  4220. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  4221. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  4222. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  4223. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  4224. // Luau Roblox instance-path require (only the leaf survives extraction):
  4225. // require(script.Util.helper) → src/Util/helper.luau.
  4226. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  4227. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  4228. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  4229. cg = CodeGraph.initSync(tempDir);
  4230. await cg.indexAll();
  4231. cg.resolveReferences();
  4232. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  4233. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  4234. expect(config, 'config.lua file node').toBeDefined();
  4235. expect(helper, 'helper.luau file node').toBeDefined();
  4236. const cfgDeps = cg.getFileDependents(config!.filePath);
  4237. const helpDeps = cg.getFileDependents(helper!.filePath);
  4238. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  4239. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  4240. });
  4241. });
  4242. describe('Rust module-path call resolution', () => {
  4243. let tempDir: string;
  4244. let cg: CodeGraph;
  4245. beforeEach(() => {
  4246. tempDir = createTempDir();
  4247. });
  4248. afterEach(() => {
  4249. if (cg) cg.close();
  4250. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4251. });
  4252. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  4253. // The canonical Axum router-assembly pattern: a parent module calls each
  4254. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  4255. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  4256. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  4257. // resolved crate-relative only (looking for `src/users.rs`), so it found
  4258. // nothing and the handler modules looked dependent-less.
  4259. const http = path.join(tempDir, 'src/http');
  4260. fs.mkdirSync(http, { recursive: true });
  4261. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  4262. fs.writeFileSync(
  4263. path.join(http, 'mod.rs'),
  4264. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  4265. );
  4266. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  4267. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  4268. cg = CodeGraph.initSync(tempDir);
  4269. await cg.indexAll();
  4270. cg.resolveReferences();
  4271. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  4272. // proving the bare prefix resolved self-relative AND disambiguated the
  4273. // colliding `router` name to the correct file (not an arbitrary one).
  4274. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  4275. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  4276. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  4277. expect(usersRouter, 'users.rs router fn').toBeDefined();
  4278. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  4279. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4280. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4281. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  4282. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  4283. });
  4284. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  4285. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  4286. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  4287. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  4288. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  4289. // Rust path resolver and the leaf module looked dependent-less.
  4290. const routes = path.join(tempDir, 'src/routes');
  4291. const database = path.join(tempDir, 'src/database');
  4292. fs.mkdirSync(routes, { recursive: true });
  4293. fs.mkdirSync(database, { recursive: true });
  4294. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  4295. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  4296. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  4297. fs.writeFileSync(
  4298. path.join(routes, 'mod.rs'),
  4299. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  4300. );
  4301. cg = CodeGraph.initSync(tempDir);
  4302. await cg.indexAll();
  4303. cg.resolveReferences();
  4304. const find = cg
  4305. .getNodesByKind('function')
  4306. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  4307. expect(find, 'database/profiles.rs find fn').toBeDefined();
  4308. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4309. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  4310. });
  4311. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  4312. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  4313. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  4314. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  4315. // like they have no caller. The route-macro extractor reconstructs each path
  4316. // and emits a reference, which the Rust path resolver links to the handler.
  4317. const routes = path.join(tempDir, 'src/routes');
  4318. fs.mkdirSync(routes, { recursive: true });
  4319. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  4320. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  4321. ` rocket::build()\n` +
  4322. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  4323. ` .register("/", catchers![not_found]);\n}\n`);
  4324. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  4325. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  4326. cg = CodeGraph.initSync(tempDir);
  4327. await cg.indexAll();
  4328. cg.resolveReferences();
  4329. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  4330. expect(handlers.length, 'both handler fns indexed').toBe(2);
  4331. for (const h of handlers) {
  4332. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4333. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  4334. }
  4335. });
  4336. });
  4337. describe('SvelteKit load → page synthesizer', () => {
  4338. let tempDir: string;
  4339. let cg: CodeGraph;
  4340. beforeEach(() => {
  4341. tempDir = createTempDir();
  4342. });
  4343. afterEach(() => {
  4344. if (cg) cg.close();
  4345. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4346. });
  4347. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  4348. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  4349. // PATH — there is no static import — so editing a loader showed no impact on
  4350. // the page it feeds. The synthesizer links each page component to the `load`
  4351. // in its OWN directory (path-deterministic, so it never crosses routes).
  4352. const login = path.join(tempDir, 'src/routes/login');
  4353. const register = path.join(tempDir, 'src/routes/register');
  4354. fs.mkdirSync(login, { recursive: true });
  4355. fs.mkdirSync(register, { recursive: true });
  4356. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  4357. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  4358. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  4359. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  4360. cg = CodeGraph.initSync(tempDir);
  4361. await cg.indexAll();
  4362. cg.resolveReferences();
  4363. const loginLoad = cg
  4364. .getNodesByKind('function')
  4365. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  4366. expect(loginLoad, 'login load fn').toBeDefined();
  4367. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  4368. // editing login's load surfaces login's page (the framework-wired data flow)…
  4369. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  4370. // …but never register's page (same-directory only).
  4371. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  4372. });
  4373. });
  4374. describe('Nuxt nested auto-imported component resolution', () => {
  4375. let tempDir: string;
  4376. let cg: CodeGraph;
  4377. beforeEach(() => {
  4378. tempDir = createTempDir();
  4379. });
  4380. afterEach(() => {
  4381. if (cg) cg.close();
  4382. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4383. });
  4384. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  4385. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  4386. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  4387. // component node is named by basename (`Card`), so the PascalCase usage
  4388. // didn't resolve and the nested component looked unused.
  4389. const media = path.join(tempDir, 'components/media');
  4390. fs.mkdirSync(media, { recursive: true });
  4391. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  4392. fs.writeFileSync(
  4393. path.join(tempDir, 'components/Grid.vue'),
  4394. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  4395. );
  4396. cg = CodeGraph.initSync(tempDir);
  4397. await cg.indexAll();
  4398. cg.resolveReferences();
  4399. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  4400. expect(card, 'media/Card.vue component').toBeDefined();
  4401. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4402. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  4403. });
  4404. });
  4405. describe('Swift property-wrapper attribute type references', () => {
  4406. let tempDir: string;
  4407. let cg: CodeGraph;
  4408. beforeEach(() => {
  4409. tempDir = createTempDir();
  4410. });
  4411. afterEach(() => {
  4412. if (cg) cg.close();
  4413. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4414. });
  4415. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  4416. // A many-to-many pivot/join model is referenced ONLY through the relationship
  4417. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  4418. // query. The wrapper type was captured but the argument expression wasn't
  4419. // walked, so the pivot model looked like nothing depended on it.
  4420. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  4421. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  4422. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  4423. `import Fluent\nfinal class Acronym: Model {\n` +
  4424. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  4425. ` var categories: [Category]\n}\n`);
  4426. cg = CodeGraph.initSync(tempDir);
  4427. await cg.indexAll();
  4428. cg.resolveReferences();
  4429. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  4430. expect(pivot, 'pivot model class').toBeDefined();
  4431. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4432. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  4433. });
  4434. });
  4435. describe('Objective-C messages, class receivers, and #import', () => {
  4436. let tempDir: string;
  4437. let cg: CodeGraph;
  4438. beforeEach(() => {
  4439. tempDir = createTempDir();
  4440. });
  4441. afterEach(() => {
  4442. if (cg) cg.close();
  4443. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4444. });
  4445. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  4446. fs.writeFileSync(
  4447. path.join(tempDir, 'SDImageCache.h'),
  4448. `#import <Foundation/Foundation.h>
  4449. @interface SDImageCache : NSObject
  4450. + (instancetype)sharedCache;
  4451. + (void)storeImage:(NSString *)key;
  4452. @end
  4453. `
  4454. );
  4455. fs.writeFileSync(
  4456. path.join(tempDir, 'SDImageCache.m'),
  4457. `#import "SDImageCache.h"
  4458. @implementation SDImageCache
  4459. + (instancetype)sharedCache { return nil; }
  4460. + (void)storeImage:(NSString *)key { }
  4461. @end
  4462. `
  4463. );
  4464. fs.writeFileSync(
  4465. path.join(tempDir, 'SDManager.m'),
  4466. `#import "SDImageCache.h"
  4467. @interface SDManager : NSObject
  4468. @end
  4469. @implementation SDManager
  4470. - (void)run {
  4471. [SDImageCache sharedCache];
  4472. [SDImageCache storeImage:@"k"];
  4473. }
  4474. @end
  4475. `
  4476. );
  4477. cg = CodeGraph.initSync(tempDir);
  4478. await cg.indexAll();
  4479. cg.resolveReferences();
  4480. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  4481. // to the `storeImage:` method — named WITH its colon both at the call site
  4482. // and the definition (before the fix the call site dropped the colon).
  4483. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  4484. expect(storeImage, 'storeImage: method').toBeDefined();
  4485. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4486. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4487. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  4488. // SDImageCache class (whose @interface lives in the header).
  4489. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  4490. expect(cache, 'SDImageCache class').toBeDefined();
  4491. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4492. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4493. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  4494. // surfaces both importers.
  4495. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  4496. expect(header, 'SDImageCache.h indexed').toBeDefined();
  4497. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4498. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4499. });
  4500. });
  4501. describe('Full Indexing', () => {
  4502. let tempDir: string;
  4503. beforeEach(() => {
  4504. tempDir = createTempDir();
  4505. });
  4506. afterEach(() => {
  4507. cleanupTempDir(tempDir);
  4508. });
  4509. it('should index a TypeScript file', async () => {
  4510. // Create test file
  4511. const srcDir = path.join(tempDir, 'src');
  4512. fs.mkdirSync(srcDir);
  4513. fs.writeFileSync(
  4514. path.join(srcDir, 'utils.ts'),
  4515. `
  4516. export function add(a: number, b: number): number {
  4517. return a + b;
  4518. }
  4519. export function multiply(a: number, b: number): number {
  4520. return a * b;
  4521. }
  4522. `
  4523. );
  4524. // Initialize and index
  4525. const cg = CodeGraph.initSync(tempDir);
  4526. const result = await cg.indexAll();
  4527. expect(result.success).toBe(true);
  4528. expect(result.filesIndexed).toBe(1);
  4529. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  4530. // Check nodes were stored
  4531. const nodes = cg.getNodesInFile('src/utils.ts');
  4532. expect(nodes.length).toBeGreaterThanOrEqual(2);
  4533. const addFunc = nodes.find((n) => n.name === 'add');
  4534. expect(addFunc).toBeDefined();
  4535. expect(addFunc?.kind).toBe('function');
  4536. cg.close();
  4537. });
  4538. it('should index multiple files', async () => {
  4539. // Create test files
  4540. const srcDir = path.join(tempDir, 'src');
  4541. fs.mkdirSync(srcDir);
  4542. fs.writeFileSync(
  4543. path.join(srcDir, 'math.ts'),
  4544. `export function add(a: number, b: number) { return a + b; }`
  4545. );
  4546. fs.writeFileSync(
  4547. path.join(srcDir, 'string.ts'),
  4548. `export function capitalize(s: string) { return s.toUpperCase(); }`
  4549. );
  4550. // Initialize and index
  4551. const cg = CodeGraph.initSync(tempDir);
  4552. const result = await cg.indexAll();
  4553. expect(result.success).toBe(true);
  4554. expect(result.filesIndexed).toBe(2);
  4555. const files = cg.getFiles();
  4556. expect(files.length).toBe(2);
  4557. cg.close();
  4558. });
  4559. it('should track file hashes for incremental updates', async () => {
  4560. // Create initial file
  4561. const srcDir = path.join(tempDir, 'src');
  4562. fs.mkdirSync(srcDir);
  4563. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4564. // Initialize and index
  4565. const cg = CodeGraph.initSync(tempDir);
  4566. await cg.indexAll();
  4567. // Check file is tracked
  4568. const file = cg.getFile('src/main.ts');
  4569. expect(file).toBeDefined();
  4570. expect(file?.contentHash).toBeDefined();
  4571. // Modify file
  4572. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4573. // Check for changes
  4574. const changes = cg.getChangedFiles();
  4575. expect(changes.modified).toContain('src/main.ts');
  4576. cg.close();
  4577. });
  4578. it('should sync and detect changes', async () => {
  4579. // Create initial file
  4580. const srcDir = path.join(tempDir, 'src');
  4581. fs.mkdirSync(srcDir);
  4582. fs.writeFileSync(
  4583. path.join(srcDir, 'main.ts'),
  4584. `export function original() { return 1; }`
  4585. );
  4586. // Initialize and index
  4587. const cg = CodeGraph.initSync(tempDir);
  4588. await cg.indexAll();
  4589. const initialNodes = cg.getNodesInFile('src/main.ts');
  4590. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4591. // Modify file
  4592. fs.writeFileSync(
  4593. path.join(srcDir, 'main.ts'),
  4594. `export function updated() { return 2; }`
  4595. );
  4596. // Sync
  4597. const syncResult = await cg.sync();
  4598. expect(syncResult.filesModified).toBe(1);
  4599. // Check nodes were updated
  4600. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4601. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4602. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4603. cg.close();
  4604. });
  4605. it('should count file-level tracked YAML files as indexed', async () => {
  4606. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4607. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4608. const cg = CodeGraph.initSync(tempDir);
  4609. const result = await cg.indexAll();
  4610. expect(result.success).toBe(true);
  4611. expect(result.filesIndexed).toBe(2);
  4612. expect(result.filesSkipped).toBe(0);
  4613. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4614. cg.close();
  4615. });
  4616. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4617. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4618. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4619. const cg = CodeGraph.initSync(tempDir);
  4620. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4621. expect(result.success).toBe(true);
  4622. expect(result.filesIndexed).toBe(2);
  4623. expect(result.filesSkipped).toBe(0);
  4624. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4625. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4626. cg.close();
  4627. });
  4628. it('should count file-level tracked .properties files as indexed', async () => {
  4629. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4630. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4631. const cg = CodeGraph.initSync(tempDir);
  4632. const result = await cg.indexAll();
  4633. expect(result.success).toBe(true);
  4634. expect(result.filesIndexed).toBe(2);
  4635. expect(result.filesSkipped).toBe(0);
  4636. cg.close();
  4637. });
  4638. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4639. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4640. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4641. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4642. const cg = CodeGraph.initSync(tempDir);
  4643. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4644. expect(result.success).toBe(true);
  4645. expect(result.filesIndexed).toBe(3);
  4646. expect(result.filesSkipped).toBe(0);
  4647. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4648. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4649. cg.close();
  4650. });
  4651. });
  4652. describe('Path Normalization', () => {
  4653. it('should convert backslashes to forward slashes', () => {
  4654. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4655. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4656. });
  4657. it('should leave forward-slash paths unchanged', () => {
  4658. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4659. });
  4660. it('should handle empty string', () => {
  4661. expect(normalizePath('')).toBe('');
  4662. });
  4663. });
  4664. describe('Directory Exclusion', () => {
  4665. let tempDir: string;
  4666. beforeEach(() => {
  4667. tempDir = createTempDir();
  4668. });
  4669. afterEach(() => {
  4670. cleanupTempDir(tempDir);
  4671. });
  4672. it('should exclude directories listed in .gitignore', () => {
  4673. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4674. const srcDir = path.join(tempDir, 'src');
  4675. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4676. fs.mkdirSync(srcDir, { recursive: true });
  4677. fs.mkdirSync(nmDir, { recursive: true });
  4678. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4679. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4680. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4681. const files = scanDirectory(tempDir);
  4682. expect(files).toContain('src/index.ts');
  4683. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4684. });
  4685. it('should exclude nested node_modules via a root .gitignore', () => {
  4686. // A trailing-slash pattern with no leading slash matches at any depth.
  4687. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4688. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4689. fs.mkdirSync(srcDir, { recursive: true });
  4690. fs.mkdirSync(nmDir, { recursive: true });
  4691. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4692. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4693. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4694. const files = scanDirectory(tempDir);
  4695. expect(files).toContain('packages/app/src/index.ts');
  4696. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4697. });
  4698. it('should apply a nested .gitignore only to its own subtree', () => {
  4699. const appSrc = path.join(tempDir, 'app', 'src');
  4700. fs.mkdirSync(appSrc, { recursive: true });
  4701. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4702. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4703. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4704. // A sibling with the same name outside app/ must NOT be ignored.
  4705. const otherDir = path.join(tempDir, 'other', 'src');
  4706. fs.mkdirSync(otherDir, { recursive: true });
  4707. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4708. const files = scanDirectory(tempDir);
  4709. expect(files).toContain('app/src/keep.ts');
  4710. expect(files).not.toContain('app/src/skip.ts');
  4711. expect(files).toContain('other/src/skip.ts');
  4712. });
  4713. it('should always skip .git directories', () => {
  4714. const srcDir = path.join(tempDir, 'src');
  4715. const gitDir = path.join(tempDir, '.git', 'objects');
  4716. fs.mkdirSync(srcDir, { recursive: true });
  4717. fs.mkdirSync(gitDir, { recursive: true });
  4718. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4719. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  4720. const files = scanDirectory(tempDir);
  4721. expect(files).toContain('src/index.ts');
  4722. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  4723. });
  4724. it('should return forward-slash paths on all platforms', () => {
  4725. const srcDir = path.join(tempDir, 'src', 'components');
  4726. fs.mkdirSync(srcDir, { recursive: true });
  4727. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  4728. const files = scanDirectory(tempDir);
  4729. expect(files.length).toBe(1);
  4730. expect(files[0]).toBe('src/components/Button.tsx');
  4731. expect(files[0]).not.toContain('\\');
  4732. });
  4733. });
  4734. describe('Git Submodules', () => {
  4735. let tempDir: string;
  4736. beforeEach(() => {
  4737. tempDir = createTempDir();
  4738. });
  4739. afterEach(() => {
  4740. cleanupTempDir(tempDir);
  4741. });
  4742. it('should index files inside git submodules (issue #147)', async () => {
  4743. const { execFileSync } = await import('child_process');
  4744. const git = (cwd: string, ...args: string[]) =>
  4745. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4746. // Build a separate "library" repo to use as a submodule source.
  4747. const libDir = path.join(tempDir, '_lib');
  4748. fs.mkdirSync(libDir, { recursive: true });
  4749. git(libDir, 'init', '-q');
  4750. git(libDir, 'config', 'user.email', 'test@test.com');
  4751. git(libDir, 'config', 'user.name', 'Test');
  4752. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  4753. git(libDir, 'add', '-A');
  4754. git(libDir, 'commit', '-q', '-m', 'lib init');
  4755. // Build the main repo and add the lib repo as a submodule.
  4756. const mainDir = path.join(tempDir, 'main');
  4757. fs.mkdirSync(mainDir, { recursive: true });
  4758. git(mainDir, 'init', '-q');
  4759. git(mainDir, 'config', 'user.email', 'test@test.com');
  4760. git(mainDir, 'config', 'user.name', 'Test');
  4761. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  4762. git(mainDir, 'add', '-A');
  4763. git(mainDir, 'commit', '-q', '-m', 'app init');
  4764. // protocol.file.allow=always is required to add a local-path submodule on
  4765. // recent git versions (CVE-2022-39253 mitigation).
  4766. execFileSync(
  4767. 'git',
  4768. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  4769. { cwd: mainDir, stdio: 'pipe' }
  4770. );
  4771. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  4772. const files = scanDirectory(mainDir);
  4773. expect(files).toContain('app.ts');
  4774. expect(files).toContain('libs/lib/lib.ts');
  4775. });
  4776. });
  4777. describe('Nested gitlink repos (#1031, #1033)', () => {
  4778. let tempDir: string;
  4779. // Helper: make a self-contained git repo at `dir` with one committed TS file.
  4780. const makeRepo = async (dir: string, base: string) => {
  4781. const { execFileSync } = await import('child_process');
  4782. const git = (...args: string[]) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
  4783. fs.mkdirSync(dir, { recursive: true });
  4784. git('init', '-q');
  4785. git('config', 'user.email', 'test@test.com');
  4786. git('config', 'user.name', 'Test');
  4787. fs.writeFileSync(path.join(dir, `${base}.ts`), `export const ${base} = 1;`);
  4788. git('add', '-A');
  4789. git('commit', '-q', '-m', `${base} init`);
  4790. };
  4791. beforeEach(() => {
  4792. tempDir = createTempDir();
  4793. });
  4794. afterEach(() => {
  4795. cleanupTempDir(tempDir);
  4796. });
  4797. // The #1031 case: a nested repo `git add`ed inside the super-repo becomes a
  4798. // gitlink (mode 160000) with NO `.gitmodules`. It is tracked (so it never shows
  4799. // in the untracked `-o` listing) yet not an active submodule (so
  4800. // `--recurse-submodules` won't expand it) — it used to fall through both passes
  4801. // and only the super-repo's own files got indexed.
  4802. it('indexes a bare gitlink (git add\'ed embedded repo, no .gitmodules), recursively', async () => {
  4803. const { execFileSync } = await import('child_process');
  4804. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4805. const root = path.join(tempDir, 'root');
  4806. await makeRepo(root, 'app');
  4807. // An embedded clone, itself holding a further nested clone (untracked inside it).
  4808. await makeRepo(path.join(root, 'embedded'), 'inner');
  4809. await makeRepo(path.join(root, 'embedded', 'deep'), 'deep');
  4810. // `git add embedded` records it as a 160000 gitlink (no fetch, no .gitmodules).
  4811. git(root, 'add', 'embedded');
  4812. git(root, 'commit', '-q', '-m', 'add embedded as gitlink');
  4813. expect(fs.existsSync(path.join(root, '.gitmodules'))).toBe(false);
  4814. const files = scanDirectory(root);
  4815. expect(files).toContain('app.ts');
  4816. expect(files).toContain('embedded/inner.ts'); // the gitlink's own source
  4817. expect(files).toContain('embedded/deep/deep.ts'); // recursion continues into its nested repo
  4818. });
  4819. // The -c → -s switch must not regress active submodules (#147): a repo can hold
  4820. // BOTH an active submodule (expanded by --recurse-submodules) and a bare gitlink
  4821. // (handled by the new pass), and the mixed 160000/100644 modes must parse right.
  4822. it('indexes a gitlink alongside an active submodule', async () => {
  4823. const { execFileSync } = await import('child_process');
  4824. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4825. const lib = path.join(tempDir, '_lib');
  4826. await makeRepo(lib, 'lib');
  4827. const root = path.join(tempDir, 'root');
  4828. await makeRepo(root, 'app');
  4829. // A proper, active submodule.
  4830. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: root, stdio: 'pipe' });
  4831. git(root, 'commit', '-q', '-m', 'add submodule');
  4832. // A bare gitlink in the same repo (under a non-ignored dir name).
  4833. await makeRepo(path.join(root, 'external', 'tool'), 'tool');
  4834. git(root, 'add', 'external/tool');
  4835. git(root, 'commit', '-q', '-m', 'add gitlink');
  4836. const files = scanDirectory(root);
  4837. expect(files).toContain('app.ts');
  4838. expect(files).toContain('libs/lib/lib.ts'); // active submodule still expands (#147)
  4839. expect(files).toContain('external/tool/tool.ts'); // bare gitlink now indexed
  4840. });
  4841. // A gitlink under a built-in default-ignored directory (vendor/, node_modules/,
  4842. // …) stays excluded — a committed dependency doesn't become project code just
  4843. // because it's a nested repo. Mirrors how the untracked-embedded path treats
  4844. // the same dirs (#407), so the two passes agree.
  4845. it('does not index a gitlink under a default-ignored directory (e.g. vendor/)', async () => {
  4846. const { execFileSync } = await import('child_process');
  4847. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4848. const root = path.join(tempDir, 'root');
  4849. await makeRepo(root, 'app');
  4850. await makeRepo(path.join(root, 'vendor', 'pkg'), 'dep');
  4851. git(root, 'add', 'vendor/pkg');
  4852. git(root, 'commit', '-q', '-m', 'add vendored gitlink');
  4853. const files = scanDirectory(root);
  4854. expect(files).toContain('app.ts');
  4855. expect(files).not.toContain('vendor/pkg/dep.ts');
  4856. });
  4857. // A gitlink with NO working tree on disk (the common "cloned without
  4858. // --recurse-submodules" state) has nothing to index — we must leave it alone,
  4859. // not fabricate entries, and must not break the rest of the scan.
  4860. it('leaves an uninitialized submodule (no checkout on disk) alone', async () => {
  4861. const { execFileSync } = await import('child_process');
  4862. const lib = path.join(tempDir, '_lib');
  4863. await makeRepo(lib, 'lib');
  4864. const sup = path.join(tempDir, 'super');
  4865. await makeRepo(sup, 'app');
  4866. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: sup, stdio: 'pipe' });
  4867. execFileSync('git', ['commit', '-q', '-m', 'add submodule'], { cwd: sup, stdio: 'pipe' });
  4868. // Clone the super-repo WITHOUT --recurse-submodules → libs/lib is an empty
  4869. // gitlink dir (mode 160000, no `.git` inside, no files).
  4870. const clone = path.join(tempDir, 'clone');
  4871. execFileSync('git', ['clone', '-q', sup, clone], { stdio: 'pipe' });
  4872. expect(fs.readdirSync(path.join(clone, 'libs', 'lib'))).toHaveLength(0);
  4873. const files = scanDirectory(clone);
  4874. expect(files).toContain('app.ts');
  4875. expect(files).not.toContain('libs/lib/lib.ts'); // not on disk → correctly absent
  4876. });
  4877. // #1065: a gitlink under a path the super-repo's OWN `.gitignore` covers is the
  4878. // tracked-gitlink twin of the untracked-ignored embedded repo (#514, #970). The
  4879. // gitlink-discovery pass must honor that `.gitignore` the same way — otherwise a
  4880. // gitignored reference/benchmark corpus full of `git add`ed clones gets pulled
  4881. // into the index (the 138k-file blow-up the reporter hit). Respect it by default;
  4882. // re-include only via `codegraph.json` `includeIgnored`.
  4883. it('does not index a gitlink under a gitignored directory by default (#1065)', async () => {
  4884. const { execFileSync } = await import('child_process');
  4885. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4886. const root = path.join(tempDir, 'root');
  4887. await makeRepo(root, 'app');
  4888. // An embedded clone under a path the super-repo gitignores (a benchmark corpus).
  4889. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  4890. git(root, 'add', 'benchmark/repos/ref'); // tracked as a 160000 gitlink
  4891. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  4892. git(root, 'add', '.gitignore');
  4893. git(root, 'commit', '-q', '-m', 'add gitignored gitlink + ignore rule');
  4894. const files = scanDirectory(root);
  4895. expect(files).toContain('app.ts');
  4896. expect(files).not.toContain('benchmark/repos/ref/ref.ts'); // gitignored → excluded
  4897. // The watcher path agrees: the ignored root is never discovered, and the dir is
  4898. // pruned (the reporter's exact clue — `ignores('benchmark/repos/')` was false).
  4899. expect(discoverEmbeddedRepoRoots(root)).toEqual([]);
  4900. expect(buildScopeIgnore(root).ignores('benchmark/repos/')).toBe(true);
  4901. expect(buildScopeIgnore(root).ignores('benchmark/repos/ref/ref.ts')).toBe(true);
  4902. });
  4903. it('re-includes a gitignored gitlink when codegraph.json includeIgnored opts in (#1065)', async () => {
  4904. const { execFileSync } = await import('child_process');
  4905. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4906. const root = path.join(tempDir, 'root');
  4907. await makeRepo(root, 'app');
  4908. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  4909. git(root, 'add', 'benchmark/repos/ref');
  4910. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  4911. fs.writeFileSync(path.join(root, 'codegraph.json'), JSON.stringify({ includeIgnored: ['benchmark/repos/'] }));
  4912. git(root, 'add', '.gitignore', 'codegraph.json');
  4913. git(root, 'commit', '-q', '-m', 'opt the gitignored gitlink back in');
  4914. const files = scanDirectory(root);
  4915. expect(files).toContain('app.ts');
  4916. expect(files).toContain('benchmark/repos/ref/ref.ts'); // opted in → indexed
  4917. expect(discoverEmbeddedRepoRoots(root)).toContain('benchmark/repos/ref/');
  4918. });
  4919. });
  4920. describe('Nested non-submodule git repos', () => {
  4921. let tempDir: string;
  4922. beforeEach(() => {
  4923. tempDir = createTempDir();
  4924. });
  4925. afterEach(() => {
  4926. cleanupTempDir(tempDir);
  4927. });
  4928. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  4929. const { execFileSync } = await import('child_process');
  4930. const git = (cwd: string, ...args: string[]) =>
  4931. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4932. // Top-level workspace is itself a git repo, holding no source directly —
  4933. // the CMake "super-repo" layout from the issue.
  4934. const root = path.join(tempDir, 'root');
  4935. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  4936. git(root, 'init', '-q');
  4937. git(root, 'config', 'user.email', 'test@test.com');
  4938. git(root, 'config', 'user.name', 'Test');
  4939. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  4940. // Two independent clones living inside the workspace (NOT submodules):
  4941. // one with committed source, one with only untracked source.
  4942. const sub1 = path.join(root, 'sub_repo1', 'src');
  4943. fs.mkdirSync(sub1, { recursive: true });
  4944. git(path.join(root, 'sub_repo1'), 'init', '-q');
  4945. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  4946. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  4947. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  4948. git(path.join(root, 'sub_repo1'), 'add', '-A');
  4949. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  4950. const sub2 = path.join(root, 'sub_repo2', 'src');
  4951. fs.mkdirSync(sub2, { recursive: true });
  4952. git(path.join(root, 'sub_repo2'), 'init', '-q');
  4953. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  4954. const files = scanDirectory(root);
  4955. // Both committed and untracked source from the nested repos must be found.
  4956. expect(files).toContain('sub_repo1/src/one.ts');
  4957. expect(files).toContain('sub_repo2/src/two.ts');
  4958. });
  4959. it('should respect each embedded repo\'s own .gitignore', async () => {
  4960. const { execFileSync } = await import('child_process');
  4961. const git = (cwd: string, ...args: string[]) =>
  4962. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4963. const root = path.join(tempDir, 'root');
  4964. fs.mkdirSync(root, { recursive: true });
  4965. git(root, 'init', '-q');
  4966. const sub = path.join(root, 'sub_repo', 'src');
  4967. fs.mkdirSync(sub, { recursive: true });
  4968. git(path.join(root, 'sub_repo'), 'init', '-q');
  4969. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  4970. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  4971. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  4972. const files = scanDirectory(root);
  4973. expect(files).toContain('sub_repo/src/real.ts');
  4974. expect(files).not.toContain('sub_repo/src/generated.ts');
  4975. });
  4976. // A .gitignore the `ignore` library can't compile to a regex must not abort
  4977. // the whole scan — the bad pattern is dropped, valid ones still apply (#682).
  4978. it('does not crash on a .gitignore with an uncompilable pattern (#682)', () => {
  4979. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  4980. fs.mkdirSync(path.join(tempDir, 'build'), { recursive: true });
  4981. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  4982. fs.writeFileSync(path.join(tempDir, 'build', 'out.ts'), 'export const y = 2;');
  4983. // `\\[` makes the matcher build an unterminated character class — the throw
  4984. // is lazy (at match time), which is what escaped and killed sync.
  4985. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'build/\n\\\\[\n');
  4986. let files: string[] = [];
  4987. expect(() => {
  4988. files = scanDirectory(tempDir);
  4989. }).not.toThrow();
  4990. expect(files).toContain('src/real.ts');
  4991. // The still-valid `build/` rule is honored; only the bad line was dropped.
  4992. expect(files.some((f) => f.startsWith('build/'))).toBe(false);
  4993. });
  4994. // A .gitignore that isn't valid UTF-8 — e.g. encrypted in place by corporate
  4995. // DLP / endpoint software (UTF-16 header + ciphertext) — is skipped whole,
  4996. // not fed to the matcher as garbage patterns (#682).
  4997. it('does not crash on a non-UTF-8 (DLP-encrypted) .gitignore (#682)', () => {
  4998. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  4999. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  5000. const header = Buffer.concat([
  5001. Buffer.from([0x00, 0x00]),
  5002. Buffer.from('[notice][user]', 'utf16le'),
  5003. ]);
  5004. const junk = Buffer.from([0x5b, 0x99, 0xc3, 0x28, 0x5c, 0x5b, 0xff, 0xfd]);
  5005. fs.writeFileSync(path.join(tempDir, '.gitignore'), Buffer.concat([header, junk]));
  5006. let files: string[] = [];
  5007. expect(() => {
  5008. files = scanDirectory(tempDir);
  5009. }).not.toThrow();
  5010. expect(files).toContain('src/real.ts');
  5011. });
  5012. it('buildDefaultIgnore survives a bad .gitignore and still applies valid rules (#682)', () => {
  5013. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'dist/\n\\\\[\n');
  5014. const ig = buildDefaultIgnore(tempDir);
  5015. expect(() => ig.ignores('src/app.ts')).not.toThrow();
  5016. expect(ig.ignores('dist/')).toBe(true); // valid rule survives
  5017. expect(ig.ignores('src/app.ts')).toBe(false);
  5018. });
  5019. });
  5020. // =============================================================================
  5021. // Scala
  5022. // =============================================================================
  5023. describe('Scala Extraction', () => {
  5024. describe('Language detection', () => {
  5025. it('should detect Scala files', () => {
  5026. expect(detectLanguage('Main.scala')).toBe('scala');
  5027. expect(detectLanguage('script.sc')).toBe('scala');
  5028. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  5029. });
  5030. it('should report Scala as supported', () => {
  5031. expect(isLanguageSupported('scala')).toBe(true);
  5032. expect(getSupportedLanguages()).toContain('scala');
  5033. });
  5034. });
  5035. describe('Class extraction', () => {
  5036. it('should extract class definitions', () => {
  5037. const code = `
  5038. class UserService(private val repo: UserRepository) {
  5039. def findUser(id: String): Option[String] = Some(id)
  5040. }
  5041. `;
  5042. const result = extractFromSource('UserService.scala', code);
  5043. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  5044. expect(cls).toBeDefined();
  5045. expect(cls?.language).toBe('scala');
  5046. });
  5047. it('should extract object definitions as class kind', () => {
  5048. const code = `
  5049. object DatabaseConfig {
  5050. val url = "jdbc:postgresql://localhost/mydb"
  5051. }
  5052. `;
  5053. const result = extractFromSource('Config.scala', code);
  5054. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  5055. expect(obj).toBeDefined();
  5056. });
  5057. it('should extract trait definitions as trait kind', () => {
  5058. const code = `
  5059. trait Repository[A] {
  5060. def findById(id: String): Option[A]
  5061. def save(entity: A): Unit
  5062. }
  5063. `;
  5064. const result = extractFromSource('Repository.scala', code);
  5065. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  5066. expect(trait_).toBeDefined();
  5067. });
  5068. });
  5069. describe('Method and function extraction', () => {
  5070. it('should extract method definitions inside a class', () => {
  5071. const code = `
  5072. class Calculator {
  5073. def add(a: Int, b: Int): Int = a + b
  5074. def divide(a: Double, b: Double): Double = a / b
  5075. }
  5076. `;
  5077. const result = extractFromSource('Calculator.scala', code);
  5078. const methods = result.nodes.filter((n) => n.kind === 'method');
  5079. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  5080. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  5081. });
  5082. it('should extract method signatures', () => {
  5083. const code = `
  5084. class Greeter {
  5085. def greet(name: String): String = s"Hello, \${name}!"
  5086. }
  5087. `;
  5088. const result = extractFromSource('Greeter.scala', code);
  5089. const method = result.nodes.find((n) => n.name === 'greet');
  5090. expect(method?.signature).toContain('name: String');
  5091. expect(method?.signature).toContain('String');
  5092. });
  5093. it('should extract top-level function definitions as functions', () => {
  5094. const code = `
  5095. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  5096. def greet(name: String): String = s"Hello, \${name}!"
  5097. `;
  5098. const result = extractFromSource('utils.scala', code);
  5099. const fns = result.nodes.filter((n) => n.kind === 'function');
  5100. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  5101. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  5102. });
  5103. });
  5104. describe('Val and var extraction', () => {
  5105. it('should extract val inside a class as field', () => {
  5106. const code = `
  5107. class Config {
  5108. val timeout: Int = 30
  5109. val host: String = "localhost"
  5110. }
  5111. `;
  5112. const result = extractFromSource('Config.scala', code);
  5113. const fields = result.nodes.filter((n) => n.kind === 'field');
  5114. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  5115. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  5116. });
  5117. it('should extract var inside a class as field', () => {
  5118. const code = `
  5119. class Counter {
  5120. var count: Int = 0
  5121. }
  5122. `;
  5123. const result = extractFromSource('Counter.scala', code);
  5124. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  5125. expect(field).toBeDefined();
  5126. });
  5127. it('should extract top-level val as constant', () => {
  5128. const code = `
  5129. val MaxConnections: Int = 100
  5130. val DefaultTimeout = 30
  5131. `;
  5132. const result = extractFromSource('constants.scala', code);
  5133. const consts = result.nodes.filter((n) => n.kind === 'constant');
  5134. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  5135. });
  5136. it('should extract top-level var as variable', () => {
  5137. const code = `
  5138. var retries: Int = 3
  5139. `;
  5140. const result = extractFromSource('state.scala', code);
  5141. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  5142. expect(v).toBeDefined();
  5143. });
  5144. it('should include type in val/var signature', () => {
  5145. const code = `
  5146. class Service {
  5147. val timeout: Int = 30
  5148. }
  5149. `;
  5150. const result = extractFromSource('Service.scala', code);
  5151. const field = result.nodes.find((n) => n.name === 'timeout');
  5152. expect(field?.signature).toContain('timeout');
  5153. expect(field?.signature).toContain('Int');
  5154. });
  5155. });
  5156. describe('Enum extraction', () => {
  5157. it('should extract enum definitions', () => {
  5158. const code = `
  5159. enum Color:
  5160. case Red
  5161. case Green
  5162. case Blue
  5163. `;
  5164. const result = extractFromSource('Color.scala', code);
  5165. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  5166. expect(enumNode).toBeDefined();
  5167. });
  5168. it('should extract enum cases as enum_member', () => {
  5169. const code = `
  5170. enum Direction:
  5171. case North
  5172. case South
  5173. case East
  5174. case West
  5175. `;
  5176. const result = extractFromSource('Direction.scala', code);
  5177. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  5178. expect(members.find((m) => m.name === 'North')).toBeDefined();
  5179. expect(members.find((m) => m.name === 'South')).toBeDefined();
  5180. expect(members.length).toBeGreaterThanOrEqual(4);
  5181. });
  5182. });
  5183. describe('Type alias extraction', () => {
  5184. it('should extract type aliases', () => {
  5185. const code = `
  5186. type UserId = String
  5187. type UserMap = Map[String, String]
  5188. `;
  5189. const result = extractFromSource('types.scala', code);
  5190. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5191. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  5192. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  5193. });
  5194. });
  5195. describe('Import extraction', () => {
  5196. it('should extract import declarations', () => {
  5197. const code = `
  5198. import scala.collection.mutable.ListBuffer
  5199. import scala.concurrent.Future
  5200. `;
  5201. const result = extractFromSource('imports.scala', code);
  5202. const imports = result.nodes.filter((n) => n.kind === 'import');
  5203. expect(imports.length).toBeGreaterThanOrEqual(2);
  5204. });
  5205. });
  5206. describe('Visibility modifiers', () => {
  5207. it('should extract private visibility', () => {
  5208. const code = `
  5209. class Service {
  5210. private val secret: String = "abc"
  5211. private def helper(): Unit = {}
  5212. }
  5213. `;
  5214. const result = extractFromSource('Service.scala', code);
  5215. const secretField = result.nodes.find((n) => n.name === 'secret');
  5216. expect(secretField?.visibility).toBe('private');
  5217. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  5218. expect(helperMethod?.visibility).toBe('private');
  5219. });
  5220. it('should extract protected visibility', () => {
  5221. const code = `
  5222. class Base {
  5223. protected def helperMethod(): Unit = {}
  5224. }
  5225. `;
  5226. const result = extractFromSource('Base.scala', code);
  5227. const method = result.nodes.find((n) => n.name === 'helperMethod');
  5228. expect(method?.visibility).toBe('protected');
  5229. });
  5230. it('should default to public visibility', () => {
  5231. const code = `
  5232. class Greeter {
  5233. def hello(): Unit = {}
  5234. }
  5235. `;
  5236. const result = extractFromSource('Greeter.scala', code);
  5237. const method = result.nodes.find((n) => n.name === 'hello');
  5238. expect(method?.visibility).toBe('public');
  5239. });
  5240. });
  5241. describe('Inheritance', () => {
  5242. it('should extract extends relationships', () => {
  5243. const code = `
  5244. class AdminUser extends User {
  5245. def adminAction(): Unit = {}
  5246. }
  5247. `;
  5248. const result = extractFromSource('AdminUser.scala', code);
  5249. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5250. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  5251. });
  5252. });
  5253. describe('Call extraction', () => {
  5254. it('should extract function call expressions', () => {
  5255. const code = `
  5256. def processData(): Unit = {
  5257. val result = computeResult()
  5258. println(result)
  5259. }
  5260. `;
  5261. const result = extractFromSource('processor.scala', code);
  5262. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  5263. expect(calls.length).toBeGreaterThan(0);
  5264. });
  5265. });
  5266. });
  5267. describe('Vue Extraction', () => {
  5268. it('should detect Vue files', () => {
  5269. expect(detectLanguage('App.vue')).toBe('vue');
  5270. expect(detectLanguage('components/Button.vue')).toBe('vue');
  5271. expect(isLanguageSupported('vue')).toBe(true);
  5272. });
  5273. it('should extract component node from a Vue SFC', () => {
  5274. const code = `<template>
  5275. <div>{{ message }}</div>
  5276. </template>
  5277. <script>
  5278. export default {
  5279. data() {
  5280. return { message: 'Hello' };
  5281. }
  5282. }
  5283. </script>
  5284. `;
  5285. const result = extractFromSource('HelloWorld.vue', code);
  5286. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5287. expect(componentNode).toBeDefined();
  5288. expect(componentNode?.name).toBe('HelloWorld');
  5289. expect(componentNode?.language).toBe('vue');
  5290. expect(componentNode?.isExported).toBe(true);
  5291. });
  5292. it('should extract functions from <script> block', () => {
  5293. const code = `<template>
  5294. <button @click="handleClick">Click</button>
  5295. </template>
  5296. <script>
  5297. function handleClick() {
  5298. console.log('clicked');
  5299. }
  5300. const count = 0;
  5301. </script>
  5302. `;
  5303. const result = extractFromSource('Button.vue', code);
  5304. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5305. expect(componentNode).toBeDefined();
  5306. expect(componentNode?.name).toBe('Button');
  5307. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  5308. expect(funcNode).toBeDefined();
  5309. expect(funcNode?.language).toBe('vue');
  5310. });
  5311. it('should extract from <script setup lang="ts"> block', () => {
  5312. const code = `<template>
  5313. <div>{{ count }}</div>
  5314. </template>
  5315. <script setup lang="ts">
  5316. import { ref } from 'vue';
  5317. const count = ref(0);
  5318. function increment(): void {
  5319. count.value++;
  5320. }
  5321. </script>
  5322. `;
  5323. const result = extractFromSource('Counter.vue', code);
  5324. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5325. expect(componentNode).toBeDefined();
  5326. expect(componentNode?.name).toBe('Counter');
  5327. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  5328. expect(funcNode).toBeDefined();
  5329. expect(funcNode?.language).toBe('vue');
  5330. // All nodes should be marked as vue language
  5331. for (const node of result.nodes) {
  5332. expect(node.language).toBe('vue');
  5333. }
  5334. });
  5335. it('should extract calls from top-level <script setup> initializers', () => {
  5336. const code = `<template>
  5337. <div>{{ token }}</div>
  5338. </template>
  5339. <script setup lang="ts">
  5340. import { getTokenMp } from './api/upload';
  5341. const token = getTokenMp();
  5342. </script>
  5343. `;
  5344. const result = extractFromSource('Issue425Setup.vue', code);
  5345. const call = result.unresolvedReferences.find(
  5346. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5347. );
  5348. expect(call).toBeDefined();
  5349. });
  5350. it('should extract calls from Vue Options API object methods', () => {
  5351. const code = `<template>
  5352. <button @click="save">Save</button>
  5353. </template>
  5354. <script>
  5355. import { getTokenMp } from './api/upload';
  5356. export default {
  5357. methods: {
  5358. save() {
  5359. return getTokenMp();
  5360. }
  5361. },
  5362. setup() {
  5363. return getTokenMp();
  5364. }
  5365. }
  5366. </script>
  5367. `;
  5368. const result = extractFromSource('Issue425Options.vue', code);
  5369. const calls = result.unresolvedReferences.filter(
  5370. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5371. );
  5372. expect(calls).toHaveLength(2);
  5373. });
  5374. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  5375. const code = `<template>
  5376. <div class="wrap">
  5377. <UserCard :user="u" />
  5378. <my-button>Click</my-button>
  5379. <Transition><span>x</span></Transition>
  5380. </div>
  5381. </template>
  5382. <script setup lang="ts">
  5383. import UserCard from './UserCard.vue';
  5384. import MyButton from './MyButton.vue';
  5385. </script>
  5386. `;
  5387. const result = extractFromSource('Host.vue', code);
  5388. const refs = result.unresolvedReferences
  5389. .filter((r) => r.referenceKind === 'references')
  5390. .map((r) => r.referenceName);
  5391. expect(refs).toContain('UserCard'); // PascalCase tag
  5392. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  5393. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  5394. expect(refs).not.toContain('Div'); // native HTML element skipped
  5395. expect(refs).not.toContain('Span');
  5396. });
  5397. it('should extract from both <script> and <script setup> blocks', () => {
  5398. const code = `<template>
  5399. <div>{{ msg }}</div>
  5400. </template>
  5401. <script>
  5402. export default {
  5403. name: 'DualScript'
  5404. }
  5405. </script>
  5406. <script setup>
  5407. const msg = 'hello';
  5408. function greet() {
  5409. return msg;
  5410. }
  5411. </script>
  5412. `;
  5413. const result = extractFromSource('DualScript.vue', code);
  5414. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5415. expect(componentNode).toBeDefined();
  5416. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  5417. expect(greetFunc).toBeDefined();
  5418. });
  5419. it('should create component node for template-only Vue file', () => {
  5420. const code = `<template>
  5421. <div>Static content</div>
  5422. </template>
  5423. `;
  5424. const result = extractFromSource('Static.vue', code);
  5425. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5426. expect(componentNode).toBeDefined();
  5427. expect(componentNode?.name).toBe('Static');
  5428. expect(componentNode?.language).toBe('vue');
  5429. // Only the component node should exist (no script nodes)
  5430. expect(result.nodes.length).toBe(1);
  5431. });
  5432. it('should create containment edges from component to script nodes', () => {
  5433. const code = `<template>
  5434. <div>{{ value }}</div>
  5435. </template>
  5436. <script setup lang="ts">
  5437. const value = 42;
  5438. </script>
  5439. `;
  5440. const result = extractFromSource('Contained.vue', code);
  5441. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5442. expect(componentNode).toBeDefined();
  5443. // Should have containment edges from component to child nodes
  5444. const containEdges = result.edges.filter(
  5445. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5446. );
  5447. expect(containEdges.length).toBeGreaterThan(0);
  5448. });
  5449. });
  5450. describe('Astro Extraction', () => {
  5451. it('should detect Astro files', () => {
  5452. expect(detectLanguage('src/pages/index.astro')).toBe('astro');
  5453. expect(detectLanguage('Layout.astro')).toBe('astro');
  5454. expect(isLanguageSupported('astro')).toBe(true);
  5455. });
  5456. it('should extract component node from an .astro file', () => {
  5457. const code = `---
  5458. const title = 'Hello';
  5459. ---
  5460. <h1>{title}</h1>
  5461. `;
  5462. const result = extractFromSource('Card.astro', code);
  5463. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5464. expect(componentNode).toBeDefined();
  5465. expect(componentNode?.name).toBe('Card');
  5466. expect(componentNode?.language).toBe('astro');
  5467. expect(componentNode?.isExported).toBe(true);
  5468. });
  5469. it('should extract frontmatter symbols with correct line numbers (#768)', () => {
  5470. const code = `---
  5471. import { formatDate } from '../utils/format';
  5472. function getIconNode(name: string): string {
  5473. return name;
  5474. }
  5475. const { title } = Astro.props;
  5476. ---
  5477. <span>{title}</span>
  5478. `;
  5479. const result = extractFromSource('navs.astro', code);
  5480. // The #768 repro: a function defined in frontmatter must be found
  5481. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getIconNode');
  5482. expect(fn).toBeDefined();
  5483. expect(fn?.language).toBe('astro');
  5484. expect(fn?.startLine).toBe(4);
  5485. const imp = result.nodes.find((n) => n.kind === 'import');
  5486. expect(imp).toBeDefined();
  5487. expect(imp?.startLine).toBe(2);
  5488. });
  5489. it('should extract exported getStaticPaths from frontmatter', () => {
  5490. const code = `---
  5491. export async function getStaticPaths() {
  5492. return [];
  5493. }
  5494. const { slug } = Astro.params;
  5495. ---
  5496. <p>{slug}</p>
  5497. `;
  5498. const result = extractFromSource('[slug].astro', code);
  5499. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getStaticPaths');
  5500. expect(fn).toBeDefined();
  5501. expect(fn?.isExported).toBe(true);
  5502. });
  5503. it('should extract calls from template expressions', () => {
  5504. const code = `---
  5505. import { formatDate } from '../utils/format';
  5506. const date = new Date();
  5507. ---
  5508. <time>{formatDate(date)}</time>
  5509. `;
  5510. const result = extractFromSource('Stamp.astro', code);
  5511. const call = result.unresolvedReferences.find(
  5512. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'formatDate' && ref.line === 5
  5513. );
  5514. expect(call).toBeDefined();
  5515. });
  5516. it('should extract calls from a multiline expression opening line', () => {
  5517. const code = `---
  5518. const posts = [];
  5519. ---
  5520. <ul>
  5521. {posts.map((post) => (
  5522. <li>{render(post)}</li>
  5523. ))}
  5524. </ul>
  5525. `;
  5526. const result = extractFromSource('List.astro', code);
  5527. const mapCall = result.unresolvedReferences.find(
  5528. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'posts.map'
  5529. );
  5530. expect(mapCall).toBeDefined();
  5531. const innerCall = result.unresolvedReferences.find(
  5532. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'render'
  5533. );
  5534. expect(innerCall).toBeDefined();
  5535. });
  5536. it('should extract PascalCase component usages from the template', () => {
  5537. const code = `---
  5538. import Layout from '../layouts/Layout.astro';
  5539. import PostCard from '../components/PostCard.astro';
  5540. ---
  5541. <Layout title="Home">
  5542. <PostCard />
  5543. <Fragment slot="head" />
  5544. <div class="plain-html" />
  5545. </Layout>
  5546. `;
  5547. const result = extractFromSource('index.astro', code);
  5548. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  5549. const names = refs.map((r) => r.referenceName);
  5550. expect(names).toContain('Layout');
  5551. expect(names).toContain('PostCard');
  5552. // Astro built-ins and lowercase HTML are not component references
  5553. expect(names).not.toContain('Fragment');
  5554. expect(names).not.toContain('div');
  5555. });
  5556. it('should not extract template patterns from frontmatter, script, or style content', () => {
  5557. const code = `---
  5558. // <FakeComponent /> inside frontmatter comment
  5559. const x = { y: maybeCall(1) };
  5560. ---
  5561. <div>real</div>
  5562. <script>
  5563. const z = { w: scriptCall(2) };
  5564. </script>
  5565. <style>
  5566. .a { color: red; }
  5567. </style>
  5568. `;
  5569. const result = extractFromSource('Guard.astro', code);
  5570. const templateRefs = result.unresolvedReferences.filter(
  5571. (r) => r.referenceKind === 'references' && r.referenceName === 'FakeComponent'
  5572. );
  5573. expect(templateRefs).toHaveLength(0);
  5574. // maybeCall/scriptCall come from the delegated TS extraction (once),
  5575. // not double-counted by the template scanner
  5576. const maybeCalls = result.unresolvedReferences.filter(
  5577. (r) => r.referenceName === 'maybeCall' && r.referenceKind === 'calls'
  5578. );
  5579. expect(maybeCalls.length).toBeLessThanOrEqual(1);
  5580. });
  5581. it('should extract <script> block symbols with correct line numbers', () => {
  5582. const code = `---
  5583. const a = 1;
  5584. ---
  5585. <div>hi</div>
  5586. <script>
  5587. function trackView(page: string) {
  5588. console.log(page);
  5589. }
  5590. </script>
  5591. `;
  5592. const result = extractFromSource('Tracker.astro', code);
  5593. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'trackView');
  5594. expect(fn).toBeDefined();
  5595. expect(fn?.startLine).toBe(6);
  5596. expect(fn?.language).toBe('astro');
  5597. });
  5598. it('should create component node for a frontmatter-less template-only file', () => {
  5599. const code = `<div>Static content</div>
  5600. `;
  5601. const result = extractFromSource('Static.astro', code);
  5602. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5603. expect(componentNode).toBeDefined();
  5604. expect(componentNode?.name).toBe('Static');
  5605. expect(componentNode?.language).toBe('astro');
  5606. });
  5607. it('should treat an unclosed frontmatter fence as no frontmatter', () => {
  5608. const code = `---
  5609. const broken = true;
  5610. <div>never closed</div>
  5611. `;
  5612. const result = extractFromSource('Broken.astro', code);
  5613. // No TS delegation happened (the fence never closes), but the component
  5614. // node still exists and nothing throws.
  5615. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5616. expect(componentNode).toBeDefined();
  5617. expect(result.nodes.find((n) => n.name === 'broken')).toBeUndefined();
  5618. });
  5619. it('should create containment edges from component to frontmatter nodes', () => {
  5620. const code = `---
  5621. const value = 42;
  5622. ---
  5623. <div>{value}</div>
  5624. `;
  5625. const result = extractFromSource('Contained.astro', code);
  5626. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5627. expect(componentNode).toBeDefined();
  5628. const containEdges = result.edges.filter(
  5629. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5630. );
  5631. expect(containEdges.length).toBeGreaterThan(0);
  5632. });
  5633. });
  5634. describe('Instantiates + Decorates edge extraction', () => {
  5635. it('emits an instantiates ref for `new Foo()`', () => {
  5636. const code = `
  5637. class Foo {}
  5638. function bootstrap() { return new Foo(); }
  5639. `;
  5640. const result = extractFromSource('app.ts', code);
  5641. const ref = result.unresolvedReferences.find(
  5642. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  5643. );
  5644. expect(ref).toBeDefined();
  5645. });
  5646. it('strips type-argument suffix from generic constructors', () => {
  5647. const code = `
  5648. class Container<T> { constructor(_: T) {} }
  5649. function go() { return new Container<string>('x'); }
  5650. `;
  5651. const result = extractFromSource('app.ts', code);
  5652. const ref = result.unresolvedReferences.find(
  5653. (r) => r.referenceKind === 'instantiates'
  5654. );
  5655. expect(ref).toBeDefined();
  5656. // Container<string> must be normalised to "Container" — otherwise
  5657. // resolution can never match the class node.
  5658. expect(ref!.referenceName).toBe('Container');
  5659. });
  5660. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  5661. const code = `
  5662. const ns = { Foo: class {} };
  5663. function go() { return new ns.Foo(); }
  5664. `;
  5665. const result = extractFromSource('app.ts', code);
  5666. const ref = result.unresolvedReferences.find(
  5667. (r) => r.referenceKind === 'instantiates'
  5668. );
  5669. // We can't always resolve which Foo, but the name should be the
  5670. // simple identifier so name-matching has a chance.
  5671. expect(ref?.referenceName).toBe('Foo');
  5672. });
  5673. it('emits a decorates ref for `@Foo class X {}`', () => {
  5674. const code = `
  5675. function Foo(_arg: string) { return (cls: any) => cls; }
  5676. @Foo('x')
  5677. class X {}
  5678. `;
  5679. const result = extractFromSource('app.ts', code);
  5680. const decorClass = result.unresolvedReferences.find(
  5681. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  5682. );
  5683. expect(decorClass).toBeDefined();
  5684. });
  5685. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  5686. // Regression: the sibling-walk must stop at the first non-
  5687. // decorator separator. `@A class Foo {} @B class Bar {}` must
  5688. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  5689. // `decorates(Bar, A)`.
  5690. const code = `
  5691. function A(cls: any) { return cls; }
  5692. function B(cls: any) { return cls; }
  5693. @A
  5694. class Foo {}
  5695. @B
  5696. class Bar {}
  5697. `;
  5698. const result = extractFromSource('app.ts', code);
  5699. const decoratesEdges = result.unresolvedReferences.filter(
  5700. (r) => r.referenceKind === 'decorates'
  5701. );
  5702. // Exactly one decorates ref per decorated class, no cross-attribution.
  5703. const fromBar = decoratesEdges.filter((r) =>
  5704. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  5705. );
  5706. expect(fromBar.length).toBe(1);
  5707. expect(fromBar[0]!.referenceName).toBe('B');
  5708. });
  5709. it('emits a decorates ref for `@Foo method() {}`', () => {
  5710. const code = `
  5711. function Get(p: string) { return (t: any, k: string) => t; }
  5712. class Svc {
  5713. @Get('/x') method() { return 1; }
  5714. }
  5715. `;
  5716. const result = extractFromSource('app.ts', code);
  5717. const decorMethod = result.unresolvedReferences.find(
  5718. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  5719. );
  5720. expect(decorMethod).toBeDefined();
  5721. // The decorated symbol must be `method`, not the constructor or class.
  5722. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  5723. expect(decoratedNode?.name).toBe('method');
  5724. });
  5725. });
  5726. // =============================================================================
  5727. // Lua
  5728. // =============================================================================
  5729. describe('Lua Extraction', () => {
  5730. describe('Language detection', () => {
  5731. it('should detect Lua files', () => {
  5732. expect(detectLanguage('init.lua')).toBe('lua');
  5733. expect(detectLanguage('src/util.lua')).toBe('lua');
  5734. });
  5735. it('should report Lua as supported', () => {
  5736. expect(isLanguageSupported('lua')).toBe(true);
  5737. expect(getSupportedLanguages()).toContain('lua');
  5738. });
  5739. });
  5740. describe('Function extraction', () => {
  5741. it('should extract global and local functions', () => {
  5742. const code = `
  5743. function configure(opts) return opts end
  5744. local function helper(x) return x * 2 end
  5745. `;
  5746. const result = extractFromSource('init.lua', code);
  5747. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5748. expect(funcs).toContain('configure');
  5749. expect(funcs).toContain('helper');
  5750. const configure = result.nodes.find((n) => n.name === 'configure');
  5751. expect(configure?.language).toBe('lua');
  5752. expect(configure?.signature).toBe('(opts)');
  5753. });
  5754. it('should split table/method functions into a receiver and method name', () => {
  5755. const code = `
  5756. function M.connect(host, port) return host end
  5757. function M:send(data) return self end
  5758. `;
  5759. const result = extractFromSource('init.lua', code);
  5760. const methods = result.nodes.filter((n) => n.kind === 'method');
  5761. const connect = methods.find((m) => m.name === 'connect');
  5762. expect(connect?.qualifiedName).toBe('M::connect');
  5763. const send = methods.find((m) => m.name === 'send');
  5764. expect(send?.qualifiedName).toBe('M::send');
  5765. });
  5766. });
  5767. describe('Variable extraction', () => {
  5768. it('should extract local variable declarations', () => {
  5769. const code = `
  5770. local M = {}
  5771. local count = 0
  5772. `;
  5773. const result = extractFromSource('mod.lua', code);
  5774. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5775. expect(vars).toContain('M');
  5776. expect(vars).toContain('count');
  5777. });
  5778. });
  5779. describe('Import extraction (require)', () => {
  5780. it('should extract require() in local declarations and bare calls', () => {
  5781. const code = `
  5782. local socket = require("socket")
  5783. local http = require "resty.http"
  5784. require("side.effect")
  5785. `;
  5786. const result = extractFromSource('net.lua', code);
  5787. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5788. expect(imports).toContain('socket');
  5789. expect(imports).toContain('resty.http');
  5790. expect(imports).toContain('side.effect');
  5791. const ref = result.unresolvedReferences.find(
  5792. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  5793. );
  5794. expect(ref).toBeDefined();
  5795. });
  5796. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  5797. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  5798. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  5799. // by extracting several sources in sequence and asserting the LAST still works.
  5800. it('should keep extracting require across many sequential parses', () => {
  5801. let last;
  5802. for (let i = 0; i < 8; i++) {
  5803. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  5804. }
  5805. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5806. expect(imports).toContain('module.7');
  5807. });
  5808. });
  5809. describe('Call extraction', () => {
  5810. it('should record intra-file calls as resolvable references', () => {
  5811. const code = `
  5812. local function helper(x) return x end
  5813. local function run(y) return helper(y) end
  5814. `;
  5815. const result = extractFromSource('calls.lua', code);
  5816. const call = result.unresolvedReferences.find(
  5817. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  5818. );
  5819. expect(call).toBeDefined();
  5820. });
  5821. });
  5822. });
  5823. // =============================================================================
  5824. // Luau (typed superset of Lua — https://luau.org)
  5825. // =============================================================================
  5826. describe('Luau Extraction', () => {
  5827. describe('Language detection', () => {
  5828. it('should detect Luau files', () => {
  5829. expect(detectLanguage('init.luau')).toBe('luau');
  5830. expect(detectLanguage('src/Client.luau')).toBe('luau');
  5831. });
  5832. it('should report Luau as supported', () => {
  5833. expect(isLanguageSupported('luau')).toBe(true);
  5834. expect(getSupportedLanguages()).toContain('luau');
  5835. });
  5836. });
  5837. describe('Type aliases', () => {
  5838. it('should extract `type` and `export type` definitions', () => {
  5839. const code = `
  5840. export type Vector = { x: number, y: number }
  5841. type Handler = (msg: string) -> boolean
  5842. `;
  5843. const result = extractFromSource('types.luau', code);
  5844. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5845. const vector = aliases.find((a) => a.name === 'Vector');
  5846. expect(vector).toBeDefined();
  5847. expect(vector?.isExported).toBe(true);
  5848. const handler = aliases.find((a) => a.name === 'Handler');
  5849. expect(handler).toBeDefined();
  5850. expect(handler?.isExported).toBe(false);
  5851. });
  5852. });
  5853. describe('Typed functions and methods', () => {
  5854. it('should capture typed signatures and split methods by receiver', () => {
  5855. const code = `
  5856. function configure(opts: { debug: boolean }): boolean
  5857. return opts.debug
  5858. end
  5859. function Client:fetch(path: string): Response
  5860. return path
  5861. end
  5862. `;
  5863. const result = extractFromSource('client.luau', code);
  5864. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  5865. expect(configure?.language).toBe('luau');
  5866. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  5867. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  5868. expect(fetch?.qualifiedName).toBe('Client::fetch');
  5869. });
  5870. });
  5871. describe('Imports and variables', () => {
  5872. it('should extract string and Roblox instance-path require imports', () => {
  5873. const code = `
  5874. local http = require("http")
  5875. local Signal = require(script.Parent.Signal)
  5876. local count = 0
  5877. `;
  5878. const result = extractFromSource('mod.luau', code);
  5879. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5880. expect(imports).toContain('http'); // string require
  5881. expect(imports).toContain('Signal'); // Roblox instance-path require
  5882. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5883. expect(vars).toContain('count');
  5884. });
  5885. });
  5886. });
  5887. // =============================================================================
  5888. // Objective-C
  5889. // =============================================================================
  5890. describe('Objective-C Extraction', () => {
  5891. const sample = `
  5892. #import <Foundation/Foundation.h>
  5893. #import "MyClass.h"
  5894. @interface MyClass : NSObject <NSCopying>
  5895. @property (nonatomic, copy) NSString *name;
  5896. - (void)greet;
  5897. - (void)doThing:(id)x with:(id)y;
  5898. + (instancetype)shared;
  5899. @end
  5900. @implementation MyClass
  5901. - (void)greet {
  5902. NSLog(@"Hello");
  5903. [self doWork];
  5904. }
  5905. - (void)doThing:(id)x with:(id)y {
  5906. [self notify:x];
  5907. }
  5908. + (instancetype)shared {
  5909. return [[MyClass alloc] init];
  5910. }
  5911. @end
  5912. void helperFunction(int count) {
  5913. MyClass *obj = [MyClass shared];
  5914. [obj greet];
  5915. }
  5916. `;
  5917. it('should extract classes, methods, functions, and imports', () => {
  5918. const result = extractFromSource('App.m', sample);
  5919. const classes = result.nodes.filter((n) => n.kind === 'class');
  5920. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  5921. const methods = result.nodes.filter((n) => n.kind === 'method');
  5922. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  5923. const shared = methods.find((m) => m.name === 'shared');
  5924. expect(shared?.isStatic).toBe(true);
  5925. const properties = result.nodes.filter((n) => n.kind === 'property');
  5926. expect(properties.some((p) => p.name === 'name')).toBe(true);
  5927. const functions = result.nodes.filter((n) => n.kind === 'function');
  5928. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  5929. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5930. expect(imports).toContain('Foundation/Foundation.h');
  5931. expect(imports).toContain('MyClass.h');
  5932. });
  5933. it('should record inheritance and protocol conformance', () => {
  5934. const result = extractFromSource('App.m', sample);
  5935. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5936. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  5937. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  5938. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  5939. });
  5940. it('should record message sends and C calls', () => {
  5941. const result = extractFromSource('App.m', sample);
  5942. const calls = result.unresolvedReferences
  5943. .filter((r) => r.referenceKind === 'calls')
  5944. .map((r) => r.referenceName);
  5945. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  5946. });
  5947. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  5948. // Regression for the gap discovered post-#165: message_expression's
  5949. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  5950. // so calls never resolved to multi-part method definitions like
  5951. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  5952. // must match the method-definition name with full keywords + trailing colons.
  5953. const code = `
  5954. @implementation Caller
  5955. - (void)demo {
  5956. NSMutableDictionary *d = [NSMutableDictionary new];
  5957. [d setObject:@"v" forKey:@"k"];
  5958. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  5959. [self touchesBegan:nil withEvent:nil];
  5960. }
  5961. @end
  5962. `;
  5963. const result = extractFromSource('Caller.m', code);
  5964. const calls = result.unresolvedReferences
  5965. .filter((r) => r.referenceKind === 'calls')
  5966. .map((r) => r.referenceName);
  5967. expect(calls).toEqual(
  5968. expect.arrayContaining([
  5969. 'd.setObject:forKey:',
  5970. 'd.setObject:forKey:withRetry:',
  5971. 'touchesBegan:withEvent:',
  5972. ])
  5973. );
  5974. });
  5975. it('should not classify pure C headers with @end in comments as objc', () => {
  5976. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  5977. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  5978. });
  5979. it('should extract protocol declarations', () => {
  5980. const code = `
  5981. @protocol DataSource <NSObject>
  5982. - (NSInteger)numberOfItems;
  5983. @end
  5984. `;
  5985. const result = extractFromSource('DataSource.h', code);
  5986. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  5987. expect(protocol).toBeDefined();
  5988. });
  5989. it('should report Objective-C as supported', () => {
  5990. expect(isLanguageSupported('objc')).toBe(true);
  5991. expect(getSupportedLanguages()).toContain('objc');
  5992. });
  5993. });
  5994. describe('Regression: issue-specific extraction fixes', () => {
  5995. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  5996. const code = `
  5997. define(['dep'], function (dep) {
  5998. function innerHelper(x) { return x + 1; }
  5999. function compute(y) { return innerHelper(y); }
  6000. return { compute: compute };
  6001. });
  6002. `;
  6003. const result = extractFromSource('amd-module.js', code);
  6004. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6005. expect(fns).toContain('innerHelper');
  6006. expect(fns).toContain('compute');
  6007. });
  6008. it('attaches Go methods on generic receivers to their type (#583)', () => {
  6009. const code = `
  6010. package main
  6011. type Stack[T any] struct { items []T }
  6012. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  6013. func (s Stack[T]) Len() int { return len(s.items) }
  6014. `;
  6015. const result = extractFromSource('stack.go', code);
  6016. const methods = result.nodes.filter((n) => n.kind === 'method');
  6017. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  6018. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  6019. });
  6020. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  6021. expect(isSourceFile('mod.mts')).toBe(true);
  6022. expect(isSourceFile('mod.cts')).toBe(true);
  6023. expect(isSourceFile('service.xsjs')).toBe(true);
  6024. expect(isSourceFile('lib.xsjslib')).toBe(true);
  6025. expect(detectLanguage('mod.mts')).toBe('typescript');
  6026. expect(detectLanguage('service.xsjs')).toBe('javascript');
  6027. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  6028. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  6029. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  6030. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  6031. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  6032. });
  6033. });
  6034. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  6035. // An import IS a dependency, but extraction only emits references for calls,
  6036. // instantiations, type annotations, and inheritance — so a symbol imported and
  6037. // then merely re-exported, placed in a registry array, passed as an argument,
  6038. // or used in JSX produced no cross-file edge, leaving the providing file with a
  6039. // false "0 dependents". These tests pin the import/re-export binding linking.
  6040. it('emits an imports reference per named, aliased, and default import binding', () => {
  6041. const code = `
  6042. import { widget, helper as h } from './foo';
  6043. import Thing from './thing';
  6044. import * as NS from './ns';
  6045. export const registry = [widget];
  6046. `;
  6047. const result = extractFromSource('bar.ts', code);
  6048. const names = result.unresolvedReferences
  6049. .filter((r) => r.referenceKind === 'imports')
  6050. .map((r) => r.referenceName);
  6051. expect(names).toContain('widget'); // named import → local name
  6052. expect(names).toContain('h'); // aliased import → local alias
  6053. expect(names).toContain('Thing'); // default import
  6054. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  6055. });
  6056. it('emits an imports reference per re-exported binding', () => {
  6057. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  6058. const names = result.unresolvedReferences
  6059. .filter((r) => r.referenceKind === 'imports')
  6060. .map((r) => r.referenceName);
  6061. // Re-export links the SOURCE-side name, not the local alias.
  6062. expect(names).toContain('alpha');
  6063. expect(names).toContain('beta');
  6064. });
  6065. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  6066. const dir = createTempDir();
  6067. try {
  6068. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6069. fs.writeFileSync(
  6070. path.join(dir, 'src', 'foo.ts'),
  6071. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  6072. );
  6073. // bar uses widget ONLY in an array and re-exports helper — neither is
  6074. // called/typed, so before import-linking bar had no edge to foo at all.
  6075. fs.writeFileSync(
  6076. path.join(dir, 'src', 'bar.ts'),
  6077. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  6078. );
  6079. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6080. await cg.indexAll();
  6081. cg.resolveReferences();
  6082. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6083. cg.destroy();
  6084. } finally {
  6085. cleanupTempDir(dir);
  6086. }
  6087. });
  6088. it('a namespace import touched only via a value-member read still links the module file', async () => {
  6089. const dir = createTempDir();
  6090. try {
  6091. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6092. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  6093. // `foo` is imported as a namespace and used ONLY via a value-member read
  6094. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  6095. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  6096. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  6097. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6098. await cg.indexAll();
  6099. cg.resolveReferences();
  6100. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6101. cg.destroy();
  6102. } finally {
  6103. cleanupTempDir(dir);
  6104. }
  6105. });
  6106. });
  6107. describe('Python import dependency linking (blast-radius recall)', () => {
  6108. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  6109. // name brought in with `from module import X` and then merely stored, used as
  6110. // a decorator/argument, or re-exported through an `__init__.py` produced no
  6111. // cross-file edge — the providing module showed a false "0 dependents".
  6112. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  6113. const code = [
  6114. 'from foo import helper, widget',
  6115. 'from foo import Thing as T',
  6116. 'from . import sibling',
  6117. 'from bar import *',
  6118. ].join('\n');
  6119. const names = extractFromSource('mod.py', code)
  6120. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  6121. .map((r) => r.referenceName);
  6122. expect(names).toContain('helper');
  6123. expect(names).toContain('widget'); // value import
  6124. expect(names).toContain('T'); // aliased import → local name
  6125. expect(names).toContain('sibling'); // `from . import <name>`
  6126. expect(names).not.toContain('*'); // wildcard import has no names
  6127. });
  6128. it('a Python value imported but never called still makes the importer a dependent', async () => {
  6129. const dir = createTempDir();
  6130. try {
  6131. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6132. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  6133. // bar imports widget+helper but only stores widget in a list — nothing is
  6134. // called, so before import-linking bar had no edge to foo.
  6135. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  6136. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6137. await cg.indexAll();
  6138. cg.resolveReferences();
  6139. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  6140. cg.destroy();
  6141. } finally {
  6142. cleanupTempDir(dir);
  6143. }
  6144. });
  6145. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  6146. const dir = createTempDir();
  6147. try {
  6148. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6149. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6150. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  6151. // certs is an imported MODULE (a file), and certs.where() is a qualified
  6152. // call through it — the receiver isn't a symbol, so plain name-matching
  6153. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  6154. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  6155. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6156. await cg.indexAll();
  6157. cg.resolveReferences();
  6158. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6159. cg.destroy();
  6160. } finally {
  6161. cleanupTempDir(dir);
  6162. }
  6163. });
  6164. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  6165. const dir = createTempDir();
  6166. try {
  6167. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6168. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6169. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  6170. // member resolution can't find it — the module-import backstop must still
  6171. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  6172. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  6173. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  6174. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6175. await cg.indexAll();
  6176. cg.resolveReferences();
  6177. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6178. cg.destroy();
  6179. } finally {
  6180. cleanupTempDir(dir);
  6181. }
  6182. });
  6183. });
  6184. describe('Go cross-package composite literals (blast-radius recall)', () => {
  6185. // Go function calls and type references across packages already resolved, but
  6186. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  6187. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  6188. // (gin's render/binding implementations) showed 0 dependents.
  6189. it('links a cross-package struct composite literal to the defining package', async () => {
  6190. const dir = createTempDir();
  6191. try {
  6192. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6193. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6194. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  6195. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  6196. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6197. await cg.indexAll();
  6198. cg.resolveReferences();
  6199. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  6200. cg.destroy();
  6201. } finally {
  6202. cleanupTempDir(dir);
  6203. }
  6204. });
  6205. it('links a composite literal in a package-level var registry', async () => {
  6206. const dir = createTempDir();
  6207. try {
  6208. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6209. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6210. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  6211. // The implementation is registered only in a top-level `var registry = {...}`
  6212. // map literal — the body walker doesn't cover top-level declarations, so this
  6213. // exercises the var-initializer walking added for Go.
  6214. 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`);
  6215. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6216. await cg.indexAll();
  6217. cg.resolveReferences();
  6218. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  6219. cg.destroy();
  6220. } finally {
  6221. cleanupTempDir(dir);
  6222. }
  6223. });
  6224. it('attributes a call inside a top-level closure (cobra RunE) to the var, not the file (#693)', async () => {
  6225. const dir = createTempDir();
  6226. try {
  6227. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6228. // Wire is called ONLY from the anonymous RunE closure inside a top-level
  6229. // `var rootCmd = &Cmd{...}` — previously the call leaked to the file node,
  6230. // so `callers(Wire)` surfaced a file (or read as "no caller"). It must now
  6231. // attribute to the enclosing var.
  6232. fs.writeFileSync(path.join(dir, 'factory.go'), `package main\n\nfunc Wire() error { return nil }\n`);
  6233. fs.writeFileSync(
  6234. path.join(dir, 'root.go'),
  6235. `package main\n\ntype Cmd struct{ RunE func() error }\n\nvar rootCmd = &Cmd{\n\tRunE: func() error { return Wire() },\n}\n`
  6236. );
  6237. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6238. await cg.indexAll();
  6239. cg.resolveReferences();
  6240. const wire = cg.getNodesByName('Wire').find((n) => n.kind === 'function');
  6241. expect(wire).toBeDefined();
  6242. const callers = cg.getCallers(wire!.id).map((c) => c.node);
  6243. expect(callers.some((n) => n.kind === 'variable' && n.name === 'rootCmd')).toBe(true);
  6244. expect(callers.some((n) => n.kind === 'file')).toBe(false);
  6245. cg.destroy();
  6246. } finally {
  6247. cleanupTempDir(dir);
  6248. }
  6249. });
  6250. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  6251. const dir = createTempDir();
  6252. try {
  6253. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6254. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  6255. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  6256. // `(*Wrapped)` — without normalization it dropped on the floor.
  6257. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  6258. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6259. await cg.indexAll();
  6260. cg.resolveReferences();
  6261. expect(cg.getFileDependents('types.go')).toContain('use.go');
  6262. cg.destroy();
  6263. } finally {
  6264. cleanupTempDir(dir);
  6265. }
  6266. });
  6267. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  6268. const dir = createTempDir();
  6269. try {
  6270. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6271. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  6272. 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`);
  6273. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  6274. // reached ONLY through the interface (API.Marshal). Without implicit
  6275. // interface satisfaction + dispatch, json.go shows 0 dependents.
  6276. 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`);
  6277. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6278. await cg.indexAll();
  6279. cg.resolveReferences();
  6280. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  6281. cg.destroy();
  6282. } finally {
  6283. cleanupTempDir(dir);
  6284. }
  6285. });
  6286. });
  6287. describe('C# records (blast-radius recall)', () => {
  6288. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  6289. // but `record` / `record struct` declarations weren't extracted as types — so
  6290. // every reference, generic-type-argument, and `new` of a record dropped on the
  6291. // floor and the defining file showed 0 dependents. (#237)
  6292. it('extracts a record as a graph node (record class + record struct)', () => {
  6293. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  6294. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6295. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6296. });
  6297. it('resolves references / instantiations of a record across files', async () => {
  6298. const dir = createTempDir();
  6299. try {
  6300. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  6301. // Box is used as a generic type argument and instantiated — both require
  6302. // Box to be a node to resolve.
  6303. fs.writeFileSync(
  6304. path.join(dir, 'use.cs'),
  6305. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  6306. );
  6307. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  6308. await cg.indexAll();
  6309. cg.resolveReferences();
  6310. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  6311. cg.destroy();
  6312. } finally {
  6313. cleanupTempDir(dir);
  6314. }
  6315. });
  6316. });
  6317. describe('Rust cross-module recall', () => {
  6318. function rustProject(files: Record<string, string>): string {
  6319. const dir = createTempDir();
  6320. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  6321. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6322. for (const [rel, content] of Object.entries(files)) {
  6323. const full = path.join(dir, 'src', rel);
  6324. fs.mkdirSync(path.dirname(full), { recursive: true });
  6325. fs.writeFileSync(full, content);
  6326. }
  6327. return dir;
  6328. }
  6329. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  6330. const dir = rustProject({
  6331. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6332. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  6333. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  6334. });
  6335. try {
  6336. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6337. await cg.indexAll();
  6338. cg.resolveReferences();
  6339. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6340. cg.destroy();
  6341. } finally { cleanupTempDir(dir); }
  6342. });
  6343. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  6344. const dir = rustProject({
  6345. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6346. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  6347. // Mine implements Render structurally; reached via &dyn Render dispatch.
  6348. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  6349. });
  6350. try {
  6351. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6352. await cg.indexAll();
  6353. cg.resolveReferences();
  6354. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  6355. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6356. cg.destroy();
  6357. } finally { cleanupTempDir(dir); }
  6358. });
  6359. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  6360. const dir = rustProject({
  6361. 'lib.rs': 'pub mod api;\n',
  6362. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  6363. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  6364. });
  6365. try {
  6366. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6367. await cg.indexAll();
  6368. cg.resolveReferences();
  6369. // The re-export hub depends on the module it re-exports from.
  6370. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  6371. cg.destroy();
  6372. } finally { cleanupTempDir(dir); }
  6373. });
  6374. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  6375. const dir = rustProject({
  6376. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  6377. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  6378. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  6379. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  6380. // send this re-export to fast.rs specifically, not name-match either.
  6381. 'hub.rs': 'pub use crate::fast::read;\n',
  6382. });
  6383. try {
  6384. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6385. await cg.indexAll();
  6386. cg.resolveReferences();
  6387. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  6388. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  6389. cg.destroy();
  6390. } finally { cleanupTempDir(dir); }
  6391. });
  6392. });
  6393. describe('Java annotations (blast-radius recall)', () => {
  6394. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  6395. const dir = createTempDir();
  6396. try {
  6397. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  6398. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  6399. // live inside a `modifiers` node on the class/field/method) must extract.
  6400. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  6401. fs.writeFileSync(
  6402. path.join(dir, 'p', 'User.java'),
  6403. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  6404. );
  6405. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  6406. await cg.indexAll();
  6407. cg.resolveReferences();
  6408. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  6409. cg.destroy();
  6410. } finally { cleanupTempDir(dir); }
  6411. });
  6412. });
  6413. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  6414. it('links a @propertyWrapper usage to the wrapper type', async () => {
  6415. const dir = createTempDir();
  6416. try {
  6417. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  6418. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  6419. // `@Argument` is a Swift attribute on a stored property — it lives in the
  6420. // property's `modifiers` and Swift doesn't extract instance properties as
  6421. // their own nodes, so without the fix the wrapper type has no users.
  6422. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  6423. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  6424. await cg.indexAll();
  6425. cg.resolveReferences();
  6426. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  6427. cg.destroy();
  6428. } finally { cleanupTempDir(dir); }
  6429. });
  6430. });
  6431. describe('R Extraction', () => {
  6432. describe('Language detection', () => {
  6433. it('should detect R files (both extension cases)', () => {
  6434. expect(detectLanguage('analysis.R')).toBe('r');
  6435. expect(detectLanguage('scripts/clean.r')).toBe('r');
  6436. });
  6437. it('should report R as supported', () => {
  6438. expect(isLanguageSupported('r')).toBe(true);
  6439. expect(getSupportedLanguages()).toContain('r');
  6440. });
  6441. });
  6442. describe('Function extraction', () => {
  6443. it('extracts every assignment form, lambdas, and nested functions', () => {
  6444. const code = `
  6445. clean_data <- function(df, threshold = 0.5) {
  6446. helper <- function(d) scale(d)
  6447. helper(df)
  6448. }
  6449. normalize = function(v) (v - mean(v)) / sd(v)
  6450. double_it <- \\(x) x * 2
  6451. `;
  6452. const result = extractFromSource('analysis.R', code);
  6453. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6454. expect(funcs).toContain('clean_data');
  6455. expect(funcs).toContain('normalize');
  6456. expect(funcs).toContain('double_it');
  6457. expect(funcs).toContain('helper'); // nested, inside clean_data's scope
  6458. const cleanData = result.nodes.find((n) => n.name === 'clean_data');
  6459. expect(cleanData?.language).toBe('r');
  6460. expect(cleanData?.signature).toBe('(df, threshold = 0.5)');
  6461. });
  6462. it('attributes body calls to the enclosing function', () => {
  6463. const code = `
  6464. prep <- function(d) scale(d)
  6465. fit_model <- function(data) {
  6466. lm(y ~ x, data = prep(data))
  6467. }
  6468. `;
  6469. const result = extractFromSource('models.R', code);
  6470. const prepCall = result.unresolvedReferences.find(
  6471. (r) => r.referenceName === 'prep' && r.referenceKind === 'calls'
  6472. );
  6473. expect(prepCall).toBeDefined();
  6474. const fitModel = result.nodes.find((n) => n.name === 'fit_model');
  6475. expect(prepCall?.fromNodeId).toBe(fitModel?.id);
  6476. });
  6477. });
  6478. describe('Imports', () => {
  6479. it('extracts library/require/source as imports, not calls', () => {
  6480. const code = `
  6481. library(dplyr)
  6482. require(stats)
  6483. requireNamespace("jsonlite")
  6484. source("helpers.R")
  6485. `;
  6486. const result = extractFromSource('main.R', code);
  6487. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6488. expect(imports).toContain('dplyr');
  6489. expect(imports).toContain('stats');
  6490. expect(imports).toContain('jsonlite');
  6491. expect(imports).toContain('helpers.R');
  6492. // Claimed by the hook — no call references to the import machinery.
  6493. const libCalls = result.unresolvedReferences.filter(
  6494. (r) => r.referenceKind === 'calls' && (r.referenceName === 'library' || r.referenceName === 'source')
  6495. );
  6496. expect(libCalls).toHaveLength(0);
  6497. });
  6498. });
  6499. describe('Variables and constants', () => {
  6500. it('extracts top-level assignments; ALL_CAPS as constants; right-assign too', () => {
  6501. const code = `
  6502. ALPHA <- 0.05
  6503. max_iter = 100
  6504. compute_stats(df) -> stats_result
  6505. inner <- function() {
  6506. local_var <- 1
  6507. }
  6508. `;
  6509. const result = extractFromSource('config.R', code);
  6510. const constant = result.nodes.find((n) => n.name === 'ALPHA');
  6511. expect(constant?.kind).toBe('constant');
  6512. const variable = result.nodes.find((n) => n.name === 'max_iter');
  6513. expect(variable?.kind).toBe('variable');
  6514. const rightAssigned = result.nodes.find((n) => n.name === 'stats_result');
  6515. expect(rightAssigned?.kind).toBe('variable');
  6516. // Locals inside functions are deliberately NOT extracted.
  6517. expect(result.nodes.find((n) => n.name === 'local_var')).toBeUndefined();
  6518. });
  6519. });
  6520. describe('Classes', () => {
  6521. it('extracts S4/R5/R6 class calls as classes with their list methods', () => {
  6522. const code = `
  6523. setClass("Patient", representation(id = "character"))
  6524. Account <- setRefClass("Account",
  6525. fields = list(balance = "numeric"),
  6526. methods = list(deposit = function(x) { balance <<- balance + x })
  6527. )
  6528. Stack <- R6Class("Stack",
  6529. public = list(push = function(v) invisible(v))
  6530. )
  6531. setGeneric("describe", function(obj) standardGeneric("describe"))
  6532. setMethod("describe", "Patient", function(obj) paste(obj@id))
  6533. `;
  6534. const result = extractFromSource('classes.R', code);
  6535. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  6536. expect(classes).toContain('Patient');
  6537. expect(classes).toContain('Account');
  6538. expect(classes).toContain('Stack');
  6539. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  6540. expect(methods).toContain('deposit');
  6541. expect(methods).toContain('push');
  6542. // setGeneric/setMethod produce functions named by their string argument.
  6543. const describes = result.nodes.filter((n) => n.name === 'describe' && n.kind === 'function');
  6544. expect(describes.length).toBeGreaterThanOrEqual(2);
  6545. // The class-assignment idiom must not ALSO produce a variable node.
  6546. expect(result.nodes.find((n) => n.name === 'Account' && n.kind === 'variable')).toBeUndefined();
  6547. });
  6548. it('extracts ggproto classes with direct-arg methods and the parent as extends', () => {
  6549. // ggplot2's OO system — every Geom/Stat/Scale in the ecosystem uses it.
  6550. const code = `
  6551. GeomPoint <- ggproto("GeomPoint", Geom,
  6552. required_aes = c("x", "y"),
  6553. draw_panel = function(data, panel_params, coord) {
  6554. coords <- coord$transform(data, panel_params)
  6555. grid::pointsGrob(coords$x, coords$y)
  6556. },
  6557. draw_key = draw_key_point
  6558. )
  6559. `;
  6560. const result = extractFromSource('geom-point.R', code);
  6561. const cls = result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'class');
  6562. expect(cls).toBeDefined();
  6563. const method = result.nodes.find((n) => n.name === 'draw_panel' && n.kind === 'method');
  6564. expect(method).toBeDefined();
  6565. const ext = result.unresolvedReferences.find(
  6566. (r) => r.referenceKind === 'extends' && r.referenceName === 'Geom'
  6567. );
  6568. expect(ext?.fromNodeId).toBe(cls?.id);
  6569. // No twin variable for the assignment.
  6570. expect(result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'variable')).toBeUndefined();
  6571. });
  6572. });
  6573. });