extraction.test.ts 288 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829
  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, blankCppInlineMacros } 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++ reference-return method/function names (#1093 follow-up)', () => {
  2421. // An inline method/function returning a reference parses with a
  2422. // `reference_declarator` wrapping the `function_declarator`. That wrapper
  2423. // wasn't unwrapped (only `pointer_declarator` was), so the name captured the
  2424. // whole declarator — `const int& getRef() const {…}` became the method named
  2425. // "& getRef() const" instead of "getRef", polluting search and callers. Very
  2426. // common in Unreal Engine headers (`const FGameplayTagContainer& GetActiveTags() const`).
  2427. const namesOf = (code: string) =>
  2428. extractFromSource('r.cpp', code).nodes
  2429. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2430. .map((n) => n.name);
  2431. it('names an inline reference-returning method by its identifier, not the declarator', () => {
  2432. const names = namesOf('class C {\npublic:\n const int& getRef() const { return x; }\n int& mutRef() { return x; }\n int x;\n};');
  2433. expect(names).toContain('getRef');
  2434. expect(names).toContain('mutRef');
  2435. // No name leaks the reference sigil or the parameter/qualifier tail.
  2436. expect(names.some((n) => /[&()]/.test(n))).toBe(false);
  2437. });
  2438. it('handles rvalue-reference returns and reference-returning free functions', () => {
  2439. expect(namesOf('class C { int&& take() { return 1; } };')).toContain('take');
  2440. expect(namesOf('const int& globalRef() { static int x; return x; }')).toContain('globalRef');
  2441. });
  2442. it('leaves pointer, value, and out-of-line reference returns unchanged (controls)', () => {
  2443. expect(namesOf('class C { int* getPtr() { return &x; } int x; };')).toContain('getPtr');
  2444. expect(namesOf('class C { int getVal() const { return x; } int x; };')).toContain('getVal');
  2445. // Out-of-line `T& C::f()` already resolves via the qualified-name hook.
  2446. expect(namesOf('const int& C::getRef() const { return x; }')).toContain('getRef');
  2447. });
  2448. });
  2449. describe('C++ user-defined conversion operator names (#1093 follow-up)', () => {
  2450. // A conversion operator's declarator is an `operator_cast` (target type +
  2451. // `() const` tail). It was named with the whole declarator —
  2452. // `operator EALSMovementState() const` — so it didn't match the symbolic-
  2453. // overload style (`operator+`) and carried parameter noise. It's now named
  2454. // `operator <type>`. Common in Unreal Engine enum-wrapper structs.
  2455. const namesOf = (code: string) =>
  2456. extractFromSource('o.cpp', code).nodes
  2457. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2458. .map((n) => n.name);
  2459. it('names a conversion operator as "operator <type>", not the full declarator', () => {
  2460. const names = namesOf('struct S {\n operator int() const { return 1; }\n operator bool() { return true; }\n int x;\n};');
  2461. expect(names).toContain('operator int');
  2462. expect(names).toContain('operator bool');
  2463. expect(names.some((n) => n.includes('(') || n.includes('const'))).toBe(false);
  2464. });
  2465. it('handles a user-type conversion operator', () => {
  2466. expect(
  2467. namesOf('struct FALSMovementState {\n operator EALSMovementState() const { return State; }\n EALSMovementState State;\n};')
  2468. ).toContain('operator EALSMovementState');
  2469. });
  2470. it('leaves symbolic operator overloads unchanged (control)', () => {
  2471. const names = namesOf('struct S {\n S operator+(const S& o) const { return o; }\n int& operator[](int i) { return x; }\n int x;\n};');
  2472. expect(names).toContain('operator+');
  2473. expect(names).toContain('operator[]'); // reference-returning subscript, name still clean
  2474. });
  2475. });
  2476. describe('C++ macro-prefixed function names (#1093 follow-up)', () => {
  2477. // An unknown inline-specifier macro before the return type
  2478. // (`FORCEINLINE FString GetName(…)`) threw tree-sitter into error recovery:
  2479. // the macro became the return type and — for a non-primitive return — the
  2480. // return type was glued onto the name (`"FString GetName"`), so the function
  2481. // was unfindable by name and its callers didn't link. `blankCppInlineMacros`
  2482. // blanks the known UE inline macros before parsing (offset-preserving), the
  2483. // same recover-don't-drop approach as the macro-annotated-class fix. Pervasive
  2484. // in Unreal Engine (`FORCEINLINE`).
  2485. const infoOf = (code: string) =>
  2486. extractFromSource('m.cpp', code).nodes
  2487. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2488. .map((n) => ({ name: n.name, ret: n.returnType }));
  2489. it('recovers the real name AND return type of a FORCEINLINE function', () => {
  2490. expect(infoOf('static FORCEINLINE FString GetName(int V) { return H(V); }')).toEqual([
  2491. { name: 'GetName', ret: 'FString' },
  2492. ]);
  2493. });
  2494. it('handles the templated UE helper shape (GetEnumerationToString)', () => {
  2495. const names = infoOf(
  2496. 'template <typename E> static FORCEINLINE FString GetEnumerationToString(const E V) { return H(V); }'
  2497. ).map((x) => x.name);
  2498. expect(names).toContain('GetEnumerationToString');
  2499. });
  2500. it('handles FORCENOINLINE / FORCEINLINE_DEBUGGABLE, methods, void, and reference returns', () => {
  2501. expect(infoOf('FORCENOINLINE FString A(int V){return H(V);}').map((x) => x.name)).toContain('A');
  2502. expect(infoOf('FORCEINLINE_DEBUGGABLE FString B(int V){return H(V);}').map((x) => x.name)).toContain('B');
  2503. expect(infoOf('struct S { FORCEINLINE FString GetName(int V) { return H(V); } };').map((x) => x.name)).toContain('GetName');
  2504. expect(infoOf('static FORCEINLINE void DoThing(int V) { H(V); }').map((x) => x.name)).toContain('DoThing');
  2505. expect(infoOf('static FORCEINLINE const FString& GetRef(int V) { return H(V); }').map((x) => x.name)).toContain('GetRef');
  2506. });
  2507. it('handles common third-party inline macros (pugixml, Godot, Boost, generic)', () => {
  2508. // pugixml: PUGI__FN before the return type; PUGIXML_FUNCTION (linkage)
  2509. // between the return type and the name — both recovered.
  2510. expect(infoOf('PUGI__FN void* default_allocate(size_t n) { return H(n); }').map((x) => x.name)).toContain('default_allocate');
  2511. expect(infoOf('PUGI__FN_NO_INLINE bool strequal(const char_t* a) { return H(a); }').map((x) => x.name)).toContain('strequal');
  2512. expect(infoOf('std::string PUGIXML_FUNCTION as_utf8(const wchar_t* s) { return H(s); }').map((x) => x.name)).toContain('as_utf8');
  2513. // Godot / Boost / generic inline hints
  2514. expect(infoOf('_FORCE_INLINE_ String get_name() const { return H(); }').map((x) => x.name)).toContain('get_name');
  2515. expect(infoOf('_ALWAYS_INLINE_ Vector2 get_pos() { return H(); }').map((x) => x.name)).toContain('get_pos');
  2516. expect(infoOf('BOOST_FORCEINLINE result_type call() { return H(); }').map((x) => x.name)).toContain('call');
  2517. expect(infoOf('ALWAYS_INLINE MyType compute() { return H(); }').map((x) => x.name)).toContain('compute');
  2518. });
  2519. it('leaves ordinary functions and real all-caps return types untouched (controls)', () => {
  2520. expect(infoOf('FString GetName(int V) { return H(V); }')).toEqual([{ name: 'GetName', ret: 'FString' }]);
  2521. // A real all-caps type that is NOT a listed inline macro stays the return type.
  2522. expect(infoOf('HRESULT DoIt(int V) { return H(V); }')).toEqual([{ name: 'DoIt', ret: 'HRESULT' }]);
  2523. });
  2524. it('blankCppInlineMacros preserves offsets and only touches specifier-position macros', () => {
  2525. // Blanked with equal-length spaces (byte offsets preserved).
  2526. expect(blankCppInlineMacros('FORCEINLINE FString F()')).toBe(' FString F()');
  2527. expect(blankCppInlineMacros('FORCEINLINE FString F()')).toHaveLength('FORCEINLINE FString F()'.length);
  2528. // Not in specifier position → untouched: string literals, expressions,
  2529. // longer word (`FORCEINLINE_COUNT`), and the fast path.
  2530. expect(blankCppInlineMacros('const char* s = "FORCEINLINE";')).toBe('const char* s = "FORCEINLINE";');
  2531. expect(blankCppInlineMacros('x = FORCEINLINE + 1;')).toBe('x = FORCEINLINE + 1;');
  2532. expect(blankCppInlineMacros('int FORCEINLINE_COUNT = 3;')).toBe('int FORCEINLINE_COUNT = 3;');
  2533. expect(blankCppInlineMacros('no macros here')).toBe('no macros here');
  2534. });
  2535. });
  2536. describe('C++ templated base-class inheritance (#1043)', () => {
  2537. // Inheriting from a template (`class D : public Base<int>`) recorded the base
  2538. // ref as the full instantiation `Base<int>`, which never name-matched the
  2539. // template indexed as the bare node `Base`. The `<…>` args are stripped so the
  2540. // `extends` reference matches.
  2541. it('strips template args from a templated base so the extends ref is the bare name', () => {
  2542. const code = `
  2543. template<typename T> class Base {};
  2544. template<typename D> class CRTPBase {};
  2545. namespace ns { template<typename T> class Tpl {}; }
  2546. class Plain {};
  2547. class Widget : public Base<int> {};
  2548. class App : public CRTPBase<App> {};
  2549. class Q : public ns::Tpl<int> {};
  2550. class Both : public Base<char>, public Plain {};
  2551. `;
  2552. const extendsRefs = extractFromSource('f.cpp', code).unresolvedReferences.filter(
  2553. (r) => r.referenceKind === 'extends'
  2554. );
  2555. const names = extendsRefs.map((r) => r.referenceName);
  2556. // Templated bases carry the bare name, NOT the `<…>` instantiation.
  2557. expect(names).toContain('Base'); // from Base<int> / Base<char>
  2558. expect(names).toContain('CRTPBase'); // from CRTPBase<App> (CRTP)
  2559. expect(names).toContain('ns::Tpl'); // qualified head preserved, args dropped
  2560. expect(names).toContain('Plain'); // non-templated base unchanged
  2561. // No reference still carries angle brackets.
  2562. expect(names.find((n) => n.includes('<'))).toBeUndefined();
  2563. });
  2564. it('stripCppTemplateArgs removes balanced <…> at any depth and is a no-op without them', () => {
  2565. expect(stripCppTemplateArgs('Base<int>')).toBe('Base');
  2566. expect(stripCppTemplateArgs('ns::Tpl<int>')).toBe('ns::Tpl');
  2567. expect(stripCppTemplateArgs('ns::Tpl<Foo<int>>')).toBe('ns::Tpl'); // nested
  2568. expect(stripCppTemplateArgs('Outer<int>::Inner')).toBe('Outer::Inner'); // mid-name
  2569. expect(stripCppTemplateArgs('Base')).toBe('Base'); // no-op
  2570. expect(stripCppTemplateArgs('ns::Plain')).toBe('ns::Plain'); // no-op qualified
  2571. });
  2572. });
  2573. describe('C++ stack-allocation construction (#1035)', () => {
  2574. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init) carry
  2575. // the constructor args directly on the declarator — no call/new node — so
  2576. // they emitted no constructor reference, unlike heap `new Calculator(0)`. An
  2577. // `instantiates` ref to the constructed type is now emitted for both.
  2578. const instNames = (code: string) =>
  2579. extractFromSource('f.cpp', `void run() {\n${code}\n}`)
  2580. .unresolvedReferences.filter((r) => r.referenceKind === 'instantiates')
  2581. .map((r) => r.referenceName);
  2582. it('emits an instantiates ref for direct-init and brace-init', () => {
  2583. expect(instNames('Calculator calc(0);')).toEqual(['Calculator']);
  2584. expect(instNames('Widget w{1, 2};')).toEqual(['Widget']);
  2585. });
  2586. it('strips template args and namespace to the bare class name', () => {
  2587. // `std::vector<int> v(10)` → `vector`; `ns::Widget w(0)` → `Widget`.
  2588. expect(instNames('std::vector<int> v(10);')).toEqual(['vector']);
  2589. expect(instNames('ns::Widget w(0);')).toEqual(['Widget']);
  2590. });
  2591. it('does not emit for primitives, default construction, or the most-vexing parse', () => {
  2592. expect(instNames('int x(5);')).toEqual([]); // primitive direct-init
  2593. expect(instNames('int y{6};')).toEqual([]); // primitive brace-init
  2594. expect(instNames('auto z = make();')).toEqual([]); // auto + call (handled elsewhere)
  2595. expect(instNames('Calculator deferred;')).toEqual([]); // default construction, no args
  2596. expect(instNames('Calculator calc();')).toEqual([]); // function declaration (most-vexing parse)
  2597. });
  2598. it('emits a single instantiates ref for a multi-declarator statement', () => {
  2599. // `Calculator a(1), b(2);` shares one `type` field; both construct a
  2600. // Calculator, so one ref suffices (it dedups to one edge regardless).
  2601. expect(instNames('Calculator a(1), b(2);')).toEqual(['Calculator']);
  2602. });
  2603. });
  2604. describe('C/C++ imports', () => {
  2605. it('should extract system include', () => {
  2606. const code = `#include <iostream>`;
  2607. const result = extractFromSource('main.cpp', code);
  2608. const importNode = result.nodes.find((n) => n.kind === 'import');
  2609. expect(importNode).toBeDefined();
  2610. expect(importNode?.name).toBe('iostream');
  2611. expect(importNode?.signature).toBe('#include <iostream>');
  2612. });
  2613. it('should extract system include with path', () => {
  2614. const code = `#include <nlohmann/json.hpp>`;
  2615. const result = extractFromSource('app.cpp', code);
  2616. const importNode = result.nodes.find((n) => n.kind === 'import');
  2617. expect(importNode).toBeDefined();
  2618. expect(importNode?.name).toBe('nlohmann/json.hpp');
  2619. });
  2620. it('should extract local include', () => {
  2621. const code = `#include "myheader.h"`;
  2622. const result = extractFromSource('main.cpp', code);
  2623. const importNode = result.nodes.find((n) => n.kind === 'import');
  2624. expect(importNode).toBeDefined();
  2625. expect(importNode?.name).toBe('myheader.h');
  2626. });
  2627. it('should extract C header', () => {
  2628. const code = `#include <stdio.h>`;
  2629. const result = extractFromSource('main.c', code);
  2630. const importNode = result.nodes.find((n) => n.kind === 'import');
  2631. expect(importNode).toBeDefined();
  2632. expect(importNode?.name).toBe('stdio.h');
  2633. });
  2634. it('should extract multiple includes', () => {
  2635. const code = `
  2636. #include <iostream>
  2637. #include <vector>
  2638. #include "config.h"
  2639. `;
  2640. const result = extractFromSource('app.cpp', code);
  2641. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2642. expect(importNodes.length).toBe(3);
  2643. const names = importNodes.map((n) => n.name);
  2644. expect(names).toContain('iostream');
  2645. expect(names).toContain('vector');
  2646. expect(names).toContain('config.h');
  2647. });
  2648. it('should create unresolved references for local includes', () => {
  2649. const code = `#include "myheader.h"`;
  2650. const result = extractFromSource('main.cpp', code);
  2651. const importRef = result.unresolvedReferences.find(
  2652. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  2653. );
  2654. expect(importRef).toBeDefined();
  2655. expect(importRef?.line).toBe(1);
  2656. });
  2657. it('should create unresolved references for system includes', () => {
  2658. const code = `#include <iostream>`;
  2659. const result = extractFromSource('main.cpp', code);
  2660. const importRef = result.unresolvedReferences.find(
  2661. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  2662. );
  2663. expect(importRef).toBeDefined();
  2664. });
  2665. });
  2666. describe('Dart imports', () => {
  2667. it('should extract dart: import', () => {
  2668. const code = `import 'dart:async';`;
  2669. const result = extractFromSource('main.dart', code);
  2670. const importNode = result.nodes.find((n) => n.kind === 'import');
  2671. expect(importNode).toBeDefined();
  2672. expect(importNode?.name).toBe('dart:async');
  2673. expect(importNode?.signature).toBe("import 'dart:async';");
  2674. });
  2675. it('should extract package import', () => {
  2676. const code = `import 'package:flutter/material.dart';`;
  2677. const result = extractFromSource('app.dart', code);
  2678. const importNode = result.nodes.find((n) => n.kind === 'import');
  2679. expect(importNode).toBeDefined();
  2680. expect(importNode?.name).toBe('package:flutter/material.dart');
  2681. });
  2682. it('should extract aliased import', () => {
  2683. const code = `import 'package:http/http.dart' as http;`;
  2684. const result = extractFromSource('api.dart', code);
  2685. const importNode = result.nodes.find((n) => n.kind === 'import');
  2686. expect(importNode).toBeDefined();
  2687. expect(importNode?.name).toBe('package:http/http.dart');
  2688. expect(importNode?.signature).toContain('as http');
  2689. });
  2690. it('should extract multiple imports', () => {
  2691. const code = `
  2692. import 'dart:async';
  2693. import 'dart:convert';
  2694. import 'package:flutter/material.dart';
  2695. `;
  2696. const result = extractFromSource('main.dart', code);
  2697. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2698. expect(importNodes.length).toBe(3);
  2699. const names = importNodes.map((n) => n.name);
  2700. expect(names).toContain('dart:async');
  2701. expect(names).toContain('dart:convert');
  2702. expect(names).toContain('package:flutter/material.dart');
  2703. });
  2704. it('should extract relative import', () => {
  2705. const code = `import '../utils/helpers.dart';`;
  2706. const result = extractFromSource('lib/main.dart', code);
  2707. const importNode = result.nodes.find((n) => n.kind === 'import');
  2708. expect(importNode).toBeDefined();
  2709. expect(importNode?.name).toBe('../utils/helpers.dart');
  2710. });
  2711. });
  2712. describe('Liquid imports', () => {
  2713. it('should extract render tag', () => {
  2714. const code = `{% render 'loading-spinner' %}`;
  2715. const result = extractFromSource('template.liquid', code);
  2716. const importNode = result.nodes.find((n) => n.kind === 'import');
  2717. expect(importNode).toBeDefined();
  2718. expect(importNode?.name).toBe('loading-spinner');
  2719. expect(importNode?.signature).toContain('render');
  2720. });
  2721. it('should extract section tag', () => {
  2722. const code = `{% section 'header' %}`;
  2723. const result = extractFromSource('layout/theme.liquid', code);
  2724. const importNode = result.nodes.find((n) => n.kind === 'import');
  2725. expect(importNode).toBeDefined();
  2726. expect(importNode?.name).toBe('header');
  2727. expect(importNode?.signature).toContain('section');
  2728. });
  2729. it('should extract include tag', () => {
  2730. const code = `{% include 'icon-cart' %}`;
  2731. const result = extractFromSource('snippets/header.liquid', code);
  2732. const importNode = result.nodes.find((n) => n.kind === 'import');
  2733. expect(importNode).toBeDefined();
  2734. expect(importNode?.name).toBe('icon-cart');
  2735. expect(importNode?.signature).toContain('include');
  2736. });
  2737. it('should extract render with whitespace control', () => {
  2738. const code = `{%- render 'price' -%}`;
  2739. const result = extractFromSource('snippets/product.liquid', code);
  2740. const importNode = result.nodes.find((n) => n.kind === 'import');
  2741. expect(importNode).toBeDefined();
  2742. expect(importNode?.name).toBe('price');
  2743. });
  2744. it('should extract multiple imports', () => {
  2745. const code = `
  2746. {% section 'header' %}
  2747. {% render 'loading-spinner' %}
  2748. {% render 'cart-drawer' %}
  2749. `;
  2750. const result = extractFromSource('layout/theme.liquid', code);
  2751. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2752. expect(importNodes.length).toBe(3);
  2753. const names = importNodes.map((n) => n.name);
  2754. expect(names).toContain('header');
  2755. expect(names).toContain('loading-spinner');
  2756. expect(names).toContain('cart-drawer');
  2757. });
  2758. });
  2759. });
  2760. // =============================================================================
  2761. // Pascal / Delphi Extraction
  2762. // =============================================================================
  2763. describe('Pascal / Delphi Extraction', () => {
  2764. describe('Language detection', () => {
  2765. it('should detect Pascal files', () => {
  2766. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2767. expect(detectLanguage('App.dpr')).toBe('pascal');
  2768. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2769. expect(detectLanguage('App.lpr')).toBe('pascal');
  2770. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2771. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2772. });
  2773. it('should report Pascal as supported', () => {
  2774. expect(isLanguageSupported('pascal')).toBe(true);
  2775. expect(getSupportedLanguages()).toContain('pascal');
  2776. });
  2777. });
  2778. describe('Unit extraction', () => {
  2779. it('should extract unit as module', () => {
  2780. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2781. const result = extractFromSource('MyUnit.pas', code);
  2782. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2783. expect(moduleNode).toBeDefined();
  2784. expect(moduleNode?.name).toBe('MyUnit');
  2785. expect(moduleNode?.language).toBe('pascal');
  2786. });
  2787. it('should extract program as module', () => {
  2788. const code = `program MyApp;\nbegin\nend.`;
  2789. const result = extractFromSource('MyApp.dpr', code);
  2790. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2791. expect(moduleNode).toBeDefined();
  2792. expect(moduleNode?.name).toBe('MyApp');
  2793. });
  2794. it('should fallback to filename when module name is empty', () => {
  2795. // Some .dpr templates use "program;" without a name
  2796. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2797. const result = extractFromSource('Console.dpr', code);
  2798. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2799. expect(moduleNode).toBeDefined();
  2800. expect(moduleNode?.name).toBe('Console');
  2801. });
  2802. });
  2803. describe('Uses clause (imports)', () => {
  2804. it('should extract uses as individual imports', () => {
  2805. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2806. const result = extractFromSource('Test.pas', code);
  2807. const imports = result.nodes.filter((n) => n.kind === 'import');
  2808. expect(imports.length).toBe(2);
  2809. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2810. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2811. });
  2812. it('should create unresolved references for imports', () => {
  2813. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2814. const result = extractFromSource('Test.pas', code);
  2815. const importRef = result.unresolvedReferences.find(
  2816. (r) => r.referenceKind === 'imports'
  2817. );
  2818. expect(importRef).toBeDefined();
  2819. expect(importRef?.referenceName).toBe('UAuth');
  2820. });
  2821. });
  2822. describe('Class extraction', () => {
  2823. it('should extract class declarations', () => {
  2824. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2825. const result = extractFromSource('Test.pas', code);
  2826. const classNode = result.nodes.find((n) => n.kind === 'class');
  2827. expect(classNode).toBeDefined();
  2828. expect(classNode?.name).toBe('TMyClass');
  2829. });
  2830. it('should extract class with inheritance', () => {
  2831. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2832. const result = extractFromSource('Test.pas', code);
  2833. const extendsRef = result.unresolvedReferences.find(
  2834. (r) => r.referenceKind === 'extends'
  2835. );
  2836. expect(extendsRef).toBeDefined();
  2837. expect(extendsRef?.referenceName).toBe('TParent');
  2838. });
  2839. it('should extract class with interface implementation', () => {
  2840. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2841. const result = extractFromSource('Test.pas', code);
  2842. const extendsRef = result.unresolvedReferences.find(
  2843. (r) => r.referenceKind === 'extends'
  2844. );
  2845. const implementsRef = result.unresolvedReferences.find(
  2846. (r) => r.referenceKind === 'implements'
  2847. );
  2848. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2849. expect(implementsRef?.referenceName).toBe('ILogger');
  2850. });
  2851. });
  2852. describe('Record extraction', () => {
  2853. it('should extract records as class nodes', () => {
  2854. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2855. const result = extractFromSource('Test.pas', code);
  2856. const classNode = result.nodes.find((n) => n.kind === 'class');
  2857. expect(classNode).toBeDefined();
  2858. expect(classNode?.name).toBe('TPoint');
  2859. const fields = result.nodes.filter((n) => n.kind === 'field');
  2860. expect(fields.length).toBe(2);
  2861. expect(fields.map((f) => f.name)).toContain('X');
  2862. expect(fields.map((f) => f.name)).toContain('Y');
  2863. });
  2864. });
  2865. describe('Interface extraction', () => {
  2866. it('should extract interface declarations', () => {
  2867. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2868. const result = extractFromSource('Test.pas', code);
  2869. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2870. expect(ifaceNode).toBeDefined();
  2871. expect(ifaceNode?.name).toBe('ILogger');
  2872. });
  2873. });
  2874. describe('Method extraction', () => {
  2875. it('should extract methods with visibility', () => {
  2876. 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.`;
  2877. const result = extractFromSource('Test.pas', code);
  2878. const methods = result.nodes.filter((n) => n.kind === 'method');
  2879. expect(methods.length).toBe(2);
  2880. const createMethod = methods.find((m) => m.name === 'Create');
  2881. expect(createMethod?.visibility).toBe('public');
  2882. const getValue = methods.find((m) => m.name === 'GetValue');
  2883. expect(getValue?.visibility).toBe('public');
  2884. const fields = result.nodes.filter((n) => n.kind === 'field');
  2885. const fValue = fields.find((f) => f.name === 'FValue');
  2886. expect(fValue?.visibility).toBe('private');
  2887. });
  2888. it('should detect static methods (class methods)', () => {
  2889. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2890. const result = extractFromSource('Test.pas', code);
  2891. const methods = result.nodes.filter((n) => n.kind === 'method');
  2892. const staticMethod = methods.find((m) => m.name === 'Create');
  2893. expect(staticMethod?.isStatic).toBe(true);
  2894. });
  2895. });
  2896. describe('Enum extraction', () => {
  2897. it('should extract enums with members', () => {
  2898. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2899. const result = extractFromSource('Test.pas', code);
  2900. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2901. expect(enumNode).toBeDefined();
  2902. expect(enumNode?.name).toBe('TColor');
  2903. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2904. expect(members.length).toBe(3);
  2905. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2906. });
  2907. });
  2908. describe('Property extraction', () => {
  2909. it('should extract properties', () => {
  2910. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2911. const result = extractFromSource('Test.pas', code);
  2912. const propNode = result.nodes.find((n) => n.kind === 'property');
  2913. expect(propNode).toBeDefined();
  2914. expect(propNode?.name).toBe('Name');
  2915. expect(propNode?.visibility).toBe('public');
  2916. });
  2917. });
  2918. describe('Constant extraction', () => {
  2919. it('should extract constants', () => {
  2920. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2921. const result = extractFromSource('Test.pas', code);
  2922. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2923. expect(constants.length).toBe(2);
  2924. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2925. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2926. });
  2927. });
  2928. describe('Type alias extraction', () => {
  2929. it('should extract type aliases', () => {
  2930. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2931. const result = extractFromSource('Test.pas', code);
  2932. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2933. expect(aliasNode).toBeDefined();
  2934. expect(aliasNode?.name).toBe('TUserName');
  2935. });
  2936. });
  2937. describe('Call extraction', () => {
  2938. it('should extract calls from implementation bodies', () => {
  2939. 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.`;
  2940. const result = extractFromSource('Test.pas', code);
  2941. const callRef = result.unresolvedReferences.find(
  2942. (r) => r.referenceKind === 'calls'
  2943. );
  2944. expect(callRef).toBeDefined();
  2945. expect(callRef?.referenceName).toBe('WriteLn');
  2946. });
  2947. });
  2948. describe('Containment edges', () => {
  2949. it('should create contains edges for class members', () => {
  2950. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2951. const result = extractFromSource('Test.pas', code);
  2952. const classNode = result.nodes.find((n) => n.kind === 'class');
  2953. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2954. expect(classNode).toBeDefined();
  2955. expect(methodNode).toBeDefined();
  2956. const containsEdge = result.edges.find(
  2957. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2958. );
  2959. expect(containsEdge).toBeDefined();
  2960. });
  2961. });
  2962. describe('Full fixture: UAuth.pas', () => {
  2963. const code = `unit UAuth;
  2964. interface
  2965. uses
  2966. System.SysUtils,
  2967. System.Classes;
  2968. type
  2969. ITokenValidator = interface
  2970. ['{11111111-1111-1111-1111-111111111111}']
  2971. function Validate(const AToken: string): Boolean;
  2972. end;
  2973. TAuthService = class(TInterfacedObject, ITokenValidator)
  2974. private
  2975. FToken: string;
  2976. FLoginCount: Integer;
  2977. procedure IncLoginCount;
  2978. protected
  2979. function GetToken: string;
  2980. public
  2981. constructor Create;
  2982. destructor Destroy; override;
  2983. function Validate(const AToken: string): Boolean;
  2984. function Login(const AUser, APass: string): string;
  2985. property Token: string read GetToken;
  2986. property LoginCount: Integer read FLoginCount;
  2987. end;
  2988. implementation
  2989. constructor TAuthService.Create;
  2990. begin
  2991. inherited Create;
  2992. FToken := '';
  2993. FLoginCount := 0;
  2994. end;
  2995. destructor TAuthService.Destroy;
  2996. begin
  2997. FToken := '';
  2998. inherited Destroy;
  2999. end;
  3000. procedure TAuthService.IncLoginCount;
  3001. begin
  3002. Inc(FLoginCount);
  3003. end;
  3004. function TAuthService.GetToken: string;
  3005. begin
  3006. Result := FToken;
  3007. end;
  3008. function TAuthService.Validate(const AToken: string): Boolean;
  3009. begin
  3010. Result := AToken <> '';
  3011. end;
  3012. function TAuthService.Login(const AUser, APass: string): string;
  3013. begin
  3014. IncLoginCount;
  3015. if Validate(AUser + ':' + APass) then
  3016. begin
  3017. FToken := AUser;
  3018. Result := 'ok';
  3019. end
  3020. else
  3021. Result := '';
  3022. end;
  3023. end.`;
  3024. it('should extract all expected nodes', () => {
  3025. const result = extractFromSource('UAuth.pas', code);
  3026. expect(result.errors).toHaveLength(0);
  3027. // Module
  3028. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  3029. expect(moduleNode?.name).toBe('UAuth');
  3030. // Imports
  3031. const imports = result.nodes.filter((n) => n.kind === 'import');
  3032. expect(imports.length).toBe(2);
  3033. // Interface
  3034. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  3035. expect(ifaceNode?.name).toBe('ITokenValidator');
  3036. // Class
  3037. const classNode = result.nodes.find((n) => n.kind === 'class');
  3038. expect(classNode?.name).toBe('TAuthService');
  3039. // Methods
  3040. const methods = result.nodes.filter((n) => n.kind === 'method');
  3041. expect(methods.length).toBeGreaterThanOrEqual(6);
  3042. expect(methods.map((m) => m.name)).toContain('Create');
  3043. expect(methods.map((m) => m.name)).toContain('Destroy');
  3044. expect(methods.map((m) => m.name)).toContain('Login');
  3045. // Fields
  3046. const fields = result.nodes.filter((n) => n.kind === 'field');
  3047. expect(fields.length).toBe(2);
  3048. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  3049. // Properties
  3050. const props = result.nodes.filter((n) => n.kind === 'property');
  3051. expect(props.length).toBe(2);
  3052. expect(props.map((p) => p.name)).toContain('Token');
  3053. expect(props.map((p) => p.name)).toContain('LoginCount');
  3054. });
  3055. it('should extract inheritance and interface implementation', () => {
  3056. const result = extractFromSource('UAuth.pas', code);
  3057. const extendsRef = result.unresolvedReferences.find(
  3058. (r) => r.referenceKind === 'extends'
  3059. );
  3060. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  3061. const implementsRef = result.unresolvedReferences.find(
  3062. (r) => r.referenceKind === 'implements'
  3063. );
  3064. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  3065. });
  3066. it('should extract calls from implementation', () => {
  3067. const result = extractFromSource('UAuth.pas', code);
  3068. const callRefs = result.unresolvedReferences.filter(
  3069. (r) => r.referenceKind === 'calls'
  3070. );
  3071. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  3072. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  3073. });
  3074. });
  3075. describe('Full fixture: UTypes.pas', () => {
  3076. const code = `unit UTypes;
  3077. interface
  3078. uses
  3079. System.SysUtils;
  3080. const
  3081. C_MAX_RETRIES = 3;
  3082. C_DEFAULT_NAME = 'Guest';
  3083. type
  3084. TUserRole = (urAdmin, urEditor, urViewer);
  3085. TPoint2D = record
  3086. X: Double;
  3087. Y: Double;
  3088. end;
  3089. TUserName = string;
  3090. TUserInfo = class
  3091. public
  3092. type
  3093. TAddress = record
  3094. Street: string;
  3095. City: string;
  3096. Zip: string;
  3097. end;
  3098. private
  3099. FName: TUserName;
  3100. FRole: TUserRole;
  3101. FAddress: TAddress;
  3102. public
  3103. constructor Create(const AName: TUserName; ARole: TUserRole);
  3104. function GetDisplayName: string;
  3105. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  3106. property Name: TUserName read FName write FName;
  3107. property Role: TUserRole read FRole;
  3108. property Address: TAddress read FAddress write FAddress;
  3109. end;
  3110. implementation
  3111. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  3112. begin
  3113. FName := AName;
  3114. FRole := ARole;
  3115. end;
  3116. function TUserInfo.GetDisplayName: string;
  3117. begin
  3118. if FRole = urAdmin then
  3119. Result := '[Admin] ' + FName
  3120. else
  3121. Result := FName;
  3122. end;
  3123. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  3124. begin
  3125. Result := TUserInfo.Create(AName, urAdmin);
  3126. end;
  3127. end.`;
  3128. it('should extract enums with members', () => {
  3129. const result = extractFromSource('UTypes.pas', code);
  3130. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  3131. expect(enumNode?.name).toBe('TUserRole');
  3132. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3133. expect(members.length).toBe(3);
  3134. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  3135. });
  3136. it('should extract constants', () => {
  3137. const result = extractFromSource('UTypes.pas', code);
  3138. const constants = result.nodes.filter((n) => n.kind === 'constant');
  3139. expect(constants.length).toBe(2);
  3140. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  3141. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  3142. });
  3143. it('should extract type aliases', () => {
  3144. const result = extractFromSource('UTypes.pas', code);
  3145. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3146. expect(aliases.map((a) => a.name)).toContain('TUserName');
  3147. });
  3148. it('should extract records as classes with fields', () => {
  3149. const result = extractFromSource('UTypes.pas', code);
  3150. const classes = result.nodes.filter((n) => n.kind === 'class');
  3151. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  3152. // TPoint2D fields
  3153. const fields = result.nodes.filter((n) => n.kind === 'field');
  3154. expect(fields.map((f) => f.name)).toContain('X');
  3155. expect(fields.map((f) => f.name)).toContain('Y');
  3156. });
  3157. it('should extract static class methods', () => {
  3158. const result = extractFromSource('UTypes.pas', code);
  3159. const methods = result.nodes.filter((n) => n.kind === 'method');
  3160. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  3161. expect(staticMethod).toBeDefined();
  3162. expect(staticMethod?.isStatic).toBe(true);
  3163. });
  3164. it('should extract nested types', () => {
  3165. const result = extractFromSource('UTypes.pas', code);
  3166. const classes = result.nodes.filter((n) => n.kind === 'class');
  3167. expect(classes.map((c) => c.name)).toContain('TAddress');
  3168. });
  3169. });
  3170. });
  3171. // =============================================================================
  3172. // DFM/FMX Extraction
  3173. // =============================================================================
  3174. describe('DFM/FMX Extraction', () => {
  3175. it('should extract components from DFM', () => {
  3176. const code = `object Form1: TForm1
  3177. Left = 0
  3178. Top = 0
  3179. Caption = 'My Form'
  3180. object Button1: TButton
  3181. Left = 10
  3182. Top = 10
  3183. Caption = 'Click Me'
  3184. end
  3185. end`;
  3186. const result = extractFromSource('Form1.dfm', code);
  3187. const components = result.nodes.filter((n) => n.kind === 'component');
  3188. expect(components.length).toBe(2);
  3189. expect(components.map((c) => c.name)).toContain('Form1');
  3190. expect(components.map((c) => c.name)).toContain('Button1');
  3191. const button = components.find((c) => c.name === 'Button1');
  3192. expect(button?.signature).toBe('TButton');
  3193. });
  3194. it('should extract nested component hierarchy', () => {
  3195. const code = `object Form1: TForm1
  3196. object Panel1: TPanel
  3197. object Label1: TLabel
  3198. Caption = 'Hello'
  3199. end
  3200. end
  3201. end`;
  3202. const result = extractFromSource('Form1.dfm', code);
  3203. const components = result.nodes.filter((n) => n.kind === 'component');
  3204. expect(components.length).toBe(3);
  3205. // Check nesting: Panel1 contains Label1
  3206. const panel = components.find((c) => c.name === 'Panel1');
  3207. const label = components.find((c) => c.name === 'Label1');
  3208. const containsEdge = result.edges.find(
  3209. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  3210. );
  3211. expect(containsEdge).toBeDefined();
  3212. });
  3213. it('should extract event handler references', () => {
  3214. const code = `object Form1: TForm1
  3215. OnCreate = FormCreate
  3216. OnDestroy = FormDestroy
  3217. object Button1: TButton
  3218. OnClick = Button1Click
  3219. end
  3220. end`;
  3221. const result = extractFromSource('Form1.dfm', code);
  3222. const refs = result.unresolvedReferences;
  3223. expect(refs.length).toBe(3);
  3224. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  3225. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  3226. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  3227. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  3228. });
  3229. it('should handle multi-line properties', () => {
  3230. const code = `object Form1: TForm1
  3231. SQL.Strings = (
  3232. 'SELECT * FROM users'
  3233. 'WHERE active = 1')
  3234. object Button1: TButton
  3235. OnClick = Button1Click
  3236. end
  3237. end`;
  3238. const result = extractFromSource('Form1.dfm', code);
  3239. const components = result.nodes.filter((n) => n.kind === 'component');
  3240. expect(components.length).toBe(2);
  3241. const refs = result.unresolvedReferences;
  3242. expect(refs.length).toBe(1);
  3243. expect(refs[0]?.referenceName).toBe('Button1Click');
  3244. });
  3245. it('should handle inherited keyword', () => {
  3246. const code = `inherited Form1: TForm1
  3247. Caption = 'Inherited Form'
  3248. object Button1: TButton
  3249. OnClick = Button1Click
  3250. end
  3251. end`;
  3252. const result = extractFromSource('Form1.dfm', code);
  3253. const components = result.nodes.filter((n) => n.kind === 'component');
  3254. expect(components.length).toBe(2);
  3255. expect(components.map((c) => c.name)).toContain('Form1');
  3256. });
  3257. it('should handle item collection properties', () => {
  3258. const code = `object Form1: TForm1
  3259. object StatusBar1: TStatusBar
  3260. Panels = <
  3261. item
  3262. Width = 200
  3263. end
  3264. item
  3265. Width = 200
  3266. end>
  3267. end
  3268. end`;
  3269. const result = extractFromSource('Form1.dfm', code);
  3270. const components = result.nodes.filter((n) => n.kind === 'component');
  3271. expect(components.length).toBe(2);
  3272. });
  3273. describe('Full fixture: MainForm.dfm', () => {
  3274. const code = `object frmMain: TfrmMain
  3275. Left = 0
  3276. Top = 0
  3277. Caption = 'CodeGraph DFM Fixture'
  3278. ClientHeight = 480
  3279. ClientWidth = 640
  3280. OnCreate = FormCreate
  3281. OnDestroy = FormDestroy
  3282. object pnlTop: TPanel
  3283. Left = 0
  3284. Top = 0
  3285. Width = 640
  3286. Height = 50
  3287. object lblTitle: TLabel
  3288. Left = 16
  3289. Top = 16
  3290. Caption = 'Authentication Service'
  3291. end
  3292. object btnLogin: TButton
  3293. Left = 540
  3294. Top = 12
  3295. OnClick = btnLoginClick
  3296. end
  3297. end
  3298. object pnlContent: TPanel
  3299. Left = 0
  3300. Top = 50
  3301. object edtUsername: TEdit
  3302. Left = 16
  3303. Top = 16
  3304. OnChange = edtUsernameChange
  3305. end
  3306. object edtPassword: TEdit
  3307. Left = 16
  3308. Top = 48
  3309. OnKeyPress = edtPasswordKeyPress
  3310. end
  3311. object mmoLog: TMemo
  3312. Left = 16
  3313. Top = 88
  3314. end
  3315. end
  3316. object pnlStatus: TStatusBar
  3317. Left = 0
  3318. Top = 440
  3319. Panels = <
  3320. item
  3321. Width = 200
  3322. end
  3323. item
  3324. Width = 200
  3325. end>
  3326. end
  3327. end`;
  3328. it('should extract all components', () => {
  3329. const result = extractFromSource('MainForm.dfm', code);
  3330. const components = result.nodes.filter((n) => n.kind === 'component');
  3331. expect(components.length).toBe(9);
  3332. expect(components.map((c) => c.name)).toEqual(
  3333. expect.arrayContaining([
  3334. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  3335. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  3336. ])
  3337. );
  3338. });
  3339. it('should extract all event handlers', () => {
  3340. const result = extractFromSource('MainForm.dfm', code);
  3341. const refs = result.unresolvedReferences;
  3342. expect(refs.length).toBe(5);
  3343. expect(refs.map((r) => r.referenceName)).toEqual(
  3344. expect.arrayContaining([
  3345. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  3346. 'edtUsernameChange', 'edtPasswordKeyPress',
  3347. ])
  3348. );
  3349. });
  3350. });
  3351. });
  3352. describe('Kotlin Multiplatform expect/actual', () => {
  3353. let tempDir: string;
  3354. let cg: CodeGraph;
  3355. beforeEach(() => {
  3356. tempDir = createTempDir();
  3357. });
  3358. afterEach(() => {
  3359. if (cg) cg.close();
  3360. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3361. });
  3362. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  3363. const common = path.join(tempDir, 'src', 'commonMain');
  3364. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3365. fs.mkdirSync(common, { recursive: true });
  3366. fs.mkdirSync(jvm, { recursive: true });
  3367. // common source set: expect declarations + a caller that uses them
  3368. fs.writeFileSync(
  3369. path.join(common, 'SystemProps.kt'),
  3370. `package demo.internal
  3371. expect fun systemProp(name: String): String?
  3372. expect class Platform {
  3373. fun describe(): String
  3374. }
  3375. `
  3376. );
  3377. fs.writeFileSync(
  3378. path.join(common, 'Caller.kt'),
  3379. `package demo
  3380. import demo.internal.systemProp
  3381. import demo.internal.Platform
  3382. fun useIt(): String {
  3383. val v = systemProp("os.name")
  3384. return Platform().describe() + v
  3385. }
  3386. `
  3387. );
  3388. // jvm source set: actual implementations
  3389. fs.writeFileSync(
  3390. path.join(jvm, 'SystemProps.kt'),
  3391. `package demo.internal
  3392. actual fun systemProp(name: String): String? = System.getProperty(name)
  3393. actual class Platform {
  3394. actual fun describe(): String = "JVM"
  3395. }
  3396. `
  3397. );
  3398. cg = CodeGraph.initSync(tempDir);
  3399. await cg.indexAll();
  3400. cg.resolveReferences();
  3401. // The expect/actual markers are captured onto the node's decorators.
  3402. const fns = cg.getNodesByKind('function');
  3403. const actualFn = fns.find(
  3404. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  3405. );
  3406. const expectFn = fns.find(
  3407. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  3408. );
  3409. expect(actualFn).toBeDefined();
  3410. expect(expectFn).toBeDefined();
  3411. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  3412. // Editing the JVM actual must surface the common expect AND its caller —
  3413. // before the expect/actual bridge the actual had zero dependents.
  3414. const impact = cg.getImpactRadius(actualFn!.id, 3);
  3415. const impacted = [...impact.nodes.values()].map((n) => n.name);
  3416. expect(impacted).toContain('systemProp'); // the common expect
  3417. expect(impacted).toContain('useIt'); // the caller, reached transitively
  3418. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  3419. const bridge = impact.edges.find(
  3420. (e) =>
  3421. e.target === actualFn!.id &&
  3422. e.provenance === 'heuristic' &&
  3423. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3424. 'kotlin-expect-actual'
  3425. );
  3426. expect(bridge).toBeDefined();
  3427. expect(bridge!.source).toBe(expectFn!.id);
  3428. });
  3429. it('links an expect class to an actual typealias (different node kinds)', async () => {
  3430. const common = path.join(tempDir, 'src', 'commonMain');
  3431. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3432. fs.mkdirSync(common, { recursive: true });
  3433. fs.mkdirSync(jvm, { recursive: true });
  3434. fs.writeFileSync(
  3435. path.join(common, 'Lock.kt'),
  3436. `package demo
  3437. expect class Lock {
  3438. fun acquire()
  3439. }
  3440. `
  3441. );
  3442. fs.writeFileSync(
  3443. path.join(jvm, 'Lock.kt'),
  3444. `package demo
  3445. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  3446. `
  3447. );
  3448. cg = CodeGraph.initSync(tempDir);
  3449. await cg.indexAll();
  3450. cg.resolveReferences();
  3451. const aliasNode = cg
  3452. .getNodesByKind('type_alias')
  3453. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  3454. expect(aliasNode).toBeDefined();
  3455. // The actual typealias is now a cross-file dependency target (linked from
  3456. // the expect class), so it participates in impact rather than being orphaned.
  3457. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  3458. const bridge = impact.edges.find(
  3459. (e) =>
  3460. e.target === aliasNode!.id &&
  3461. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3462. 'kotlin-expect-actual'
  3463. );
  3464. expect(bridge).toBeDefined();
  3465. });
  3466. });
  3467. describe('Scala cross-file dependencies', () => {
  3468. let tempDir: string;
  3469. let cg: CodeGraph;
  3470. beforeEach(() => {
  3471. tempDir = createTempDir();
  3472. });
  3473. afterEach(() => {
  3474. if (cg) cg.close();
  3475. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3476. });
  3477. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  3478. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  3479. fs.mkdirSync(src, { recursive: true });
  3480. fs.writeFileSync(
  3481. path.join(src, 'Semigroup.scala'),
  3482. `package demo
  3483. trait Semigroup[A] {
  3484. def combine(x: A, y: A): A
  3485. }
  3486. `
  3487. );
  3488. fs.writeFileSync(
  3489. path.join(src, 'Monoid.scala'),
  3490. `package demo
  3491. trait Monoid[A] extends Semigroup[A] {
  3492. def empty: A
  3493. }
  3494. `
  3495. );
  3496. fs.writeFileSync(
  3497. path.join(src, 'Instances.scala'),
  3498. `package demo
  3499. object Instances {
  3500. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  3501. def empty: Int = 0
  3502. def combine(x: Int, y: Int): Int = x + y
  3503. }
  3504. }
  3505. `
  3506. );
  3507. fs.writeFileSync(
  3508. path.join(src, 'Folding.scala'),
  3509. `package demo
  3510. object Folding {
  3511. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  3512. xs.foldLeft(M.empty)(M.combine)
  3513. }
  3514. `
  3515. );
  3516. cg = CodeGraph.initSync(tempDir);
  3517. await cg.indexAll();
  3518. cg.resolveReferences();
  3519. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  3520. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  3521. expect(monoid).toBeDefined();
  3522. expect(semigroup).toBeDefined();
  3523. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  3524. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  3525. // the whole point of the fix (the `[A]` used to defeat name matching).
  3526. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  3527. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  3528. // Editing Monoid surfaces the cross-file users: the instance val typed
  3529. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  3530. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  3531. expect(impacted).toContain('intMonoid'); // field type annotation
  3532. expect(impacted).toContain('fold'); // trailing implicit parameter list
  3533. });
  3534. });
  3535. describe('PHP namespace + import resolution', () => {
  3536. let tempDir: string;
  3537. let cg: CodeGraph;
  3538. beforeEach(() => {
  3539. tempDir = createTempDir();
  3540. });
  3541. afterEach(() => {
  3542. if (cg) cg.close();
  3543. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3544. });
  3545. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  3546. const src = path.join(tempDir, 'src');
  3547. // Two interfaces with the SAME simple name in different namespaces — the
  3548. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  3549. // resolve. The namespace qualifies them; the `use` import disambiguates.
  3550. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  3551. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  3552. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  3553. fs.writeFileSync(
  3554. path.join(src, 'Cache', 'Factory.php'),
  3555. `<?php
  3556. namespace Contracts\\Cache;
  3557. interface Factory {
  3558. public function store(): object;
  3559. }
  3560. `
  3561. );
  3562. fs.writeFileSync(
  3563. path.join(src, 'Mail', 'Factory.php'),
  3564. `<?php
  3565. namespace Contracts\\Mail;
  3566. interface Factory {
  3567. public function mailer(): object;
  3568. }
  3569. `
  3570. );
  3571. fs.writeFileSync(
  3572. path.join(src, 'App', 'Service.php'),
  3573. `<?php
  3574. namespace App;
  3575. use Contracts\\Cache\\Factory;
  3576. class Service {
  3577. public function make(): Factory {
  3578. return resolve(Factory::class);
  3579. }
  3580. }
  3581. `
  3582. );
  3583. cg = CodeGraph.initSync(tempDir);
  3584. await cg.indexAll();
  3585. cg.resolveReferences();
  3586. // The PHP namespace is captured into the qualified name, so the two
  3587. // same-named interfaces are distinguishable.
  3588. const cacheFactory = cg
  3589. .getNodesByKind('interface')
  3590. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  3591. const mailFactory = cg
  3592. .getNodesByKind('interface')
  3593. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  3594. expect(cacheFactory).toBeDefined();
  3595. expect(mailFactory).toBeDefined();
  3596. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  3597. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  3598. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  3599. const serviceFile = 'src/App/Service.php';
  3600. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  3601. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3602. );
  3603. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  3604. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3605. );
  3606. expect(cacheReaches).toBe(true);
  3607. expect(mailReaches).toBe(false);
  3608. });
  3609. });
  3610. describe('Ruby mixins (include/extend/prepend)', () => {
  3611. let tempDir: string;
  3612. let cg: CodeGraph;
  3613. beforeEach(() => {
  3614. tempDir = createTempDir();
  3615. });
  3616. afterEach(() => {
  3617. if (cg) cg.close();
  3618. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3619. });
  3620. it('links include/extend/prepend to the mixed-in module across files', async () => {
  3621. const lib = path.join(tempDir, 'lib');
  3622. fs.mkdirSync(lib, { recursive: true });
  3623. fs.writeFileSync(
  3624. path.join(lib, 'concerns.rb'),
  3625. `module Trackable
  3626. def track; end
  3627. end
  3628. module Cacheable
  3629. def cache; end
  3630. end
  3631. module Loggable
  3632. def log; end
  3633. end
  3634. `
  3635. );
  3636. fs.writeFileSync(
  3637. path.join(lib, 'model.rb'),
  3638. `class Model
  3639. include Trackable
  3640. prepend Cacheable
  3641. extend Loggable
  3642. end
  3643. `
  3644. );
  3645. cg = CodeGraph.initSync(tempDir);
  3646. await cg.indexAll();
  3647. cg.resolveReferences();
  3648. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  3649. expect(model).toBeDefined();
  3650. // All three mixin forms create an `implements` edge Model → module, so
  3651. // editing a concern surfaces every class that mixes it in (across files).
  3652. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  3653. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  3654. expect(mod, moduleName).toBeDefined();
  3655. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  3656. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  3657. }
  3658. });
  3659. it('resolves require / require_relative to the required file', async () => {
  3660. const lib = path.join(tempDir, 'lib');
  3661. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  3662. // A leaf file whose class is referenced only dynamically — so without
  3663. // require resolution it would look like nothing depends on it.
  3664. fs.writeFileSync(
  3665. path.join(lib, 'app', 'fetcher.rb'),
  3666. `module App
  3667. class Fetcher
  3668. def fetch; end
  3669. end
  3670. end
  3671. `
  3672. );
  3673. // Pulled in by a load-path `require` …
  3674. fs.writeFileSync(
  3675. path.join(lib, 'app', 'worker.rb'),
  3676. `require "app/fetcher"
  3677. module App
  3678. class Worker; end
  3679. end
  3680. `
  3681. );
  3682. // … and a sibling pulled in by `require_relative`.
  3683. fs.writeFileSync(
  3684. path.join(lib, 'app', 'boot.rb'),
  3685. `require_relative "fetcher"
  3686. `
  3687. );
  3688. cg = CodeGraph.initSync(tempDir);
  3689. await cg.indexAll();
  3690. cg.resolveReferences();
  3691. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3692. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3693. // (boot.rb) — without require resolution its file would have no dependents.
  3694. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3695. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3696. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3697. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3698. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3699. });
  3700. });
  3701. describe('C++ free-function name extraction', () => {
  3702. let tempDir: string;
  3703. let cg: CodeGraph;
  3704. beforeEach(() => {
  3705. tempDir = createTempDir();
  3706. });
  3707. afterEach(() => {
  3708. if (cg) cg.close();
  3709. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3710. });
  3711. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3712. const src = path.join(tempDir, 'src');
  3713. fs.mkdirSync(src, { recursive: true });
  3714. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3715. // `auto … -> std::string` trailing return type. Both used to be named
  3716. // `string` (picked up from the parameter / return type), so callers never
  3717. // resolved and the defining file looked like nothing depended on it.
  3718. fs.writeFileSync(
  3719. path.join(src, 'names.cc'),
  3720. `#include <string>
  3721. std::string TableFileName(const std::string& dbname, int number) {
  3722. return dbname;
  3723. }
  3724. auto BuildName(const std::string& a) -> std::string {
  3725. return a;
  3726. }
  3727. `
  3728. );
  3729. fs.writeFileSync(
  3730. path.join(src, 'user.cc'),
  3731. `#include <string>
  3732. std::string use() {
  3733. return TableFileName("db", 1) + BuildName("x");
  3734. }
  3735. `
  3736. );
  3737. cg = CodeGraph.initSync(tempDir);
  3738. await cg.indexAll();
  3739. cg.resolveReferences();
  3740. // The functions are extracted under their real names, not `string`.
  3741. const fns = cg.getNodesByKind('function');
  3742. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3743. const buildFn = fns.find((n) => n.name === 'BuildName');
  3744. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3745. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3746. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3747. for (const fn of [tableFn!, buildFn!]) {
  3748. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3749. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3750. }
  3751. });
  3752. });
  3753. describe('Dart mixins and type references', () => {
  3754. let tempDir: string;
  3755. let cg: CodeGraph;
  3756. beforeEach(() => {
  3757. tempDir = createTempDir();
  3758. });
  3759. afterEach(() => {
  3760. if (cg) cg.close();
  3761. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3762. });
  3763. it('links `with` mixins and method parameter/return types across files', async () => {
  3764. const lib = path.join(tempDir, 'lib');
  3765. fs.mkdirSync(lib, { recursive: true });
  3766. fs.writeFileSync(
  3767. path.join(lib, 'models.dart'),
  3768. `class User {
  3769. final String name;
  3770. User(this.name);
  3771. }
  3772. mixin Loggable {
  3773. void log() {}
  3774. }
  3775. abstract class Repository {
  3776. User find(int id);
  3777. }
  3778. `
  3779. );
  3780. fs.writeFileSync(
  3781. path.join(lib, 'service.dart'),
  3782. `import 'models.dart';
  3783. class UserService extends Repository with Loggable {
  3784. @override
  3785. User find(int id) => User('x');
  3786. List<User> all() => [];
  3787. }
  3788. `
  3789. );
  3790. cg = CodeGraph.initSync(tempDir);
  3791. await cg.indexAll();
  3792. cg.resolveReferences();
  3793. const inModels = (name: string) =>
  3794. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3795. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3796. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3797. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3798. // as a class-like node.
  3799. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3800. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3801. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3802. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3803. expect(mixinUsers).toContain('UserService');
  3804. // `User` is used only as a method parameter/return type in service.dart —
  3805. // editing it must still surface service.dart via the type references.
  3806. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3807. expect(user, 'User indexed').toBeDefined();
  3808. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3809. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3810. });
  3811. });
  3812. describe('Static-member / value-read references', () => {
  3813. let tempDir: string;
  3814. let cg: CodeGraph;
  3815. beforeEach(() => {
  3816. tempDir = createTempDir();
  3817. });
  3818. afterEach(() => {
  3819. if (cg) cg.close();
  3820. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3821. });
  3822. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3823. fs.writeFileSync(
  3824. path.join(tempDir, 'JsonScope.java'),
  3825. `class JsonScope {
  3826. static final int EMPTY_DOCUMENT = 1;
  3827. }
  3828. `
  3829. );
  3830. fs.writeFileSync(
  3831. path.join(tempDir, 'Reader.java'),
  3832. `class Reader {
  3833. private int helper;
  3834. int peek() {
  3835. return JsonScope.EMPTY_DOCUMENT;
  3836. }
  3837. int noop() {
  3838. return this.helper;
  3839. }
  3840. }
  3841. `
  3842. );
  3843. cg = CodeGraph.initSync(tempDir);
  3844. await cg.indexAll();
  3845. cg.resolveReferences();
  3846. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3847. // read — never constructed or called), so before the static-member pass it
  3848. // had no dependents. Editing it now surfaces Reader.java.
  3849. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3850. expect(scope, 'JsonScope indexed').toBeDefined();
  3851. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3852. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3853. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3854. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3855. // should appear as a reference target from peek/noop beyond JsonScope.
  3856. const refTargets = cg
  3857. .getNodesByKind('class')
  3858. .filter((n) => n.name === 'this' || n.name === 'helper');
  3859. expect(refTargets.length).toBe(0);
  3860. });
  3861. it('does not link a static-member read across language families (coincidental name)', async () => {
  3862. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3863. // NOT link to a coincidentally same-named TS class (the cross-language false
  3864. // positive that name-matching produces; `references` edges are language-local).
  3865. fs.writeFileSync(
  3866. path.join(tempDir, 'Build.ts'),
  3867. `export class Build {\n static version = 1;\n}\n`
  3868. );
  3869. fs.writeFileSync(
  3870. path.join(tempDir, 'Device.kt'),
  3871. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3872. );
  3873. cg = CodeGraph.initSync(tempDir);
  3874. await cg.indexAll();
  3875. cg.resolveReferences();
  3876. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3877. expect(tsBuild).toBeDefined();
  3878. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3879. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3880. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3881. });
  3882. });
  3883. describe('Cross-language type/import gate (RN name collisions)', () => {
  3884. let tempDir: string;
  3885. let cg: CodeGraph;
  3886. beforeEach(() => {
  3887. tempDir = createTempDir();
  3888. });
  3889. afterEach(() => {
  3890. if (cg) cg.close();
  3891. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3892. });
  3893. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3894. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3895. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3896. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3897. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3898. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3899. // is intentionally NOT imported: a clean relative import would mask the bug
  3900. // by resolving via the import map before the framework strategy can win.
  3901. fs.writeFileSync(
  3902. path.join(tempDir, 'package.json'),
  3903. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3904. );
  3905. fs.writeFileSync(
  3906. path.join(tempDir, 'useTests.ts'),
  3907. `export type TestRunner = { run: () => void };\n`
  3908. );
  3909. fs.writeFileSync(
  3910. path.join(tempDir, 'basic.tsx'),
  3911. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3912. );
  3913. fs.writeFileSync(
  3914. path.join(tempDir, 'TestUtils.kt'),
  3915. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3916. );
  3917. cg = CodeGraph.initSync(tempDir);
  3918. await cg.indexAll();
  3919. cg.resolveReferences();
  3920. const ktRunner = cg
  3921. .getNodesByKind('class')
  3922. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3923. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3924. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3925. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3926. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3927. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3928. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3929. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3930. });
  3931. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3932. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3933. // create a web→apple dependency — but a sibling TS module imported by
  3934. // another TS file (same family) must still resolve (no over-gating).
  3935. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3936. fs.writeFileSync(
  3937. path.join(tempDir, 'widget.ts'),
  3938. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3939. );
  3940. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3941. fs.writeFileSync(
  3942. path.join(tempDir, 'app.ts'),
  3943. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3944. );
  3945. cg = CodeGraph.initSync(tempDir);
  3946. await cg.indexAll();
  3947. cg.resolveReferences();
  3948. const swiftWidget = cg
  3949. .getNodesByKind('class')
  3950. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3951. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3952. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3953. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3954. // Same-family control — the TS Helper must still see its TS dependent.
  3955. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3956. expect(helper, 'TS Helper class').toBeDefined();
  3957. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3958. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3959. });
  3960. });
  3961. describe('Python absolute module import resolution', () => {
  3962. let tempDir: string;
  3963. let cg: CodeGraph;
  3964. beforeEach(() => {
  3965. tempDir = createTempDir();
  3966. });
  3967. afterEach(() => {
  3968. if (cg) cg.close();
  3969. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3970. });
  3971. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3972. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3973. // dotted absolute module import) had no edge to the module file — only
  3974. // `from x import y` was linked — so a module imported by its dotted path
  3975. // looked like nothing depended on it.
  3976. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3977. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3978. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3979. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3980. fs.writeFileSync(
  3981. path.join(tempDir, 'conduit/apps/app.py'),
  3982. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3983. );
  3984. cg = CodeGraph.initSync(tempDir);
  3985. await cg.indexAll();
  3986. cg.resolveReferences();
  3987. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3988. expect(signals, 'signals.py indexed').toBeDefined();
  3989. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3990. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3991. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3992. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3993. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3994. });
  3995. it('Django include() links the root URLconf to the included app urls module', async () => {
  3996. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3997. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3998. // surfaces the project urlconf that mounts them.
  3999. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  4000. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  4001. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  4002. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  4003. fs.writeFileSync(
  4004. path.join(tempDir, 'app/urls.py'),
  4005. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  4006. );
  4007. fs.writeFileSync(
  4008. path.join(tempDir, 'urls.py'),
  4009. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  4010. );
  4011. cg = CodeGraph.initSync(tempDir);
  4012. await cg.indexAll();
  4013. cg.resolveReferences();
  4014. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  4015. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  4016. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4017. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  4018. });
  4019. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  4020. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  4021. // with same-named modules in sibling packages must resolve via the import's
  4022. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  4023. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  4024. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  4025. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  4026. fs.writeFileSync(path.join(tempDir, p), '');
  4027. }
  4028. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  4029. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  4030. fs.writeFileSync(
  4031. path.join(tempDir, 'app/api/routes/api.py'),
  4032. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  4033. );
  4034. cg = CodeGraph.initSync(tempDir);
  4035. await cg.indexAll();
  4036. cg.resolveReferences();
  4037. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  4038. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  4039. expect(routesAuth && depsAuth).toBeTruthy();
  4040. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4041. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4042. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  4043. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  4044. });
  4045. });
  4046. describe('Razor / Blazor markup extraction', () => {
  4047. let tempDir: string;
  4048. let cg: CodeGraph;
  4049. beforeEach(() => {
  4050. tempDir = createTempDir();
  4051. });
  4052. afterEach(() => {
  4053. if (cg) cg.close();
  4054. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4055. });
  4056. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  4057. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  4058. fs.writeFileSync(
  4059. path.join(tempDir, 'LoginViewModel.cs'),
  4060. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  4061. );
  4062. fs.writeFileSync(
  4063. path.join(tempDir, 'ToastComponent.cs'),
  4064. `namespace App { public class ToastComponent { } }`
  4065. );
  4066. fs.writeFileSync(
  4067. path.join(tempDir, 'Views/Login.cshtml'),
  4068. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  4069. );
  4070. fs.writeFileSync(
  4071. path.join(tempDir, 'Index.razor'),
  4072. `<div>\n <ToastComponent />\n</div>\n`
  4073. );
  4074. cg = CodeGraph.initSync(tempDir);
  4075. await cg.indexAll();
  4076. cg.resolveReferences();
  4077. // `@model LoginViewModel` → the view-model class.
  4078. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  4079. expect(vm, 'LoginViewModel class').toBeDefined();
  4080. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4081. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  4082. // `<ToastComponent />` → the component class.
  4083. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  4084. expect(toast, 'ToastComponent class').toBeDefined();
  4085. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4086. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  4087. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  4088. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  4089. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  4090. });
  4091. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  4092. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  4093. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  4094. cg = CodeGraph.initSync(tempDir);
  4095. await cg.indexAll();
  4096. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  4097. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  4098. const qns = brands.map((b) => b.qualifiedName).sort();
  4099. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  4100. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  4101. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  4102. });
  4103. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  4104. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  4105. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  4106. // ref must resolve to the DTO, not the same-named entity.
  4107. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  4108. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  4109. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  4110. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  4111. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  4112. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  4113. fs.writeFileSync(
  4114. path.join(tempDir, 'Pages/List.razor'),
  4115. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  4116. );
  4117. cg = CodeGraph.initSync(tempDir);
  4118. await cg.indexAll();
  4119. cg.resolveReferences();
  4120. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  4121. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  4122. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  4123. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4124. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4125. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  4126. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  4127. });
  4128. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  4129. fs.writeFileSync(
  4130. path.join(tempDir, 'CatalogService.cs'),
  4131. `namespace App { public class CatalogService { public void Load() { } } }`
  4132. );
  4133. fs.writeFileSync(
  4134. path.join(tempDir, 'List.razor'),
  4135. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  4136. );
  4137. cg = CodeGraph.initSync(tempDir);
  4138. await cg.indexAll();
  4139. cg.resolveReferences();
  4140. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  4141. expect(svc, 'CatalogService class').toBeDefined();
  4142. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4143. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  4144. });
  4145. });
  4146. describe('Default import resolution (renamed default export)', () => {
  4147. let tempDir: string;
  4148. let cg: CodeGraph;
  4149. beforeEach(() => {
  4150. tempDir = createTempDir();
  4151. });
  4152. afterEach(() => {
  4153. if (cg) cg.close();
  4154. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4155. });
  4156. it('links a renamed default import to the module file', async () => {
  4157. // Express route aggregator: `import articlesController from './controller'`
  4158. // where the module does `export default router`. The renamed local can't be
  4159. // found as a symbol, so the controller file had no dependent — the dependency
  4160. // is on the module file regardless of the default export's name.
  4161. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  4162. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  4163. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  4164. cg = CodeGraph.initSync(tempDir);
  4165. await cg.indexAll();
  4166. cg.resolveReferences();
  4167. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  4168. expect(controller, 'controller.ts indexed').toBeDefined();
  4169. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4170. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  4171. });
  4172. });
  4173. describe('Chained method-call resolution (C# extension methods)', () => {
  4174. let tempDir: string;
  4175. let cg: CodeGraph;
  4176. beforeEach(() => {
  4177. tempDir = createTempDir();
  4178. });
  4179. afterEach(() => {
  4180. if (cg) cg.close();
  4181. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4182. });
  4183. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  4184. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  4185. // static extension method elsewhere. A multi-dot receiver chain matched no
  4186. // method-call pattern before, so the extension method had no caller.
  4187. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  4188. fs.writeFileSync(
  4189. path.join(tempDir, 'cfg/Ext.cs'),
  4190. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  4191. );
  4192. fs.writeFileSync(
  4193. path.join(tempDir, 'Program.cs'),
  4194. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  4195. );
  4196. cg = CodeGraph.initSync(tempDir);
  4197. await cg.indexAll();
  4198. cg.resolveReferences();
  4199. const ext = cg
  4200. .getNodesByKind('method')
  4201. .find((n) => n.name === 'AddCoreServices')
  4202. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  4203. expect(ext, 'AddCoreServices defined').toBeDefined();
  4204. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4205. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  4206. });
  4207. });
  4208. describe('Same-directory include + KMP import resolution', () => {
  4209. let tempDir: string;
  4210. let cg: CodeGraph;
  4211. beforeEach(() => {
  4212. tempDir = createTempDir();
  4213. });
  4214. afterEach(() => {
  4215. if (cg) cg.close();
  4216. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4217. });
  4218. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  4219. // A multi-platform native module has a header of the same basename per
  4220. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  4221. // sibling header — not `apple/Storage.h` (which sorts first and so was
  4222. // picked arbitrarily before, leaving the real local header with 0 deps).
  4223. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  4224. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  4225. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4226. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4227. fs.writeFileSync(
  4228. path.join(tempDir, 'windows', 'Provider.cpp'),
  4229. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  4230. );
  4231. cg = CodeGraph.initSync(tempDir);
  4232. await cg.indexAll();
  4233. cg.resolveReferences();
  4234. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  4235. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  4236. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  4237. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  4238. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4239. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4240. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  4241. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  4242. });
  4243. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  4244. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  4245. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  4246. fs.mkdirSync(common, { recursive: true });
  4247. fs.mkdirSync(android, { recursive: true });
  4248. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  4249. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  4250. fs.writeFileSync(
  4251. path.join(common, 'Db.kt'),
  4252. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  4253. );
  4254. cg = CodeGraph.initSync(tempDir);
  4255. await cg.indexAll();
  4256. cg.resolveReferences();
  4257. const expectCtx = cg
  4258. .getNodesByKind('class')
  4259. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  4260. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  4261. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4262. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  4263. });
  4264. });
  4265. describe('Delphi form code-behind pairing', () => {
  4266. let tempDir: string;
  4267. let cg: CodeGraph;
  4268. beforeEach(() => {
  4269. tempDir = createTempDir();
  4270. });
  4271. afterEach(() => {
  4272. if (cg) cg.close();
  4273. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4274. });
  4275. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  4276. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  4277. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  4278. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  4279. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  4280. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  4281. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  4282. cg = CodeGraph.initSync(tempDir);
  4283. await cg.indexAll();
  4284. cg.resolveReferences();
  4285. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  4286. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  4287. const deps = cg.getFileDependents(dfm!.filePath);
  4288. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  4289. });
  4290. });
  4291. describe('Liquid Shopify JSON template section resolution', () => {
  4292. let tempDir: string;
  4293. let cg: CodeGraph;
  4294. beforeEach(() => {
  4295. tempDir = createTempDir();
  4296. });
  4297. afterEach(() => {
  4298. if (cg) cg.close();
  4299. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4300. });
  4301. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  4302. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  4303. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  4304. // looked unused. The JSON is now indexed and its `type`s linked.
  4305. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  4306. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  4307. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  4308. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  4309. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  4310. // Nested template dir (templates/customers/login.json) must resolve too.
  4311. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  4312. cg = CodeGraph.initSync(tempDir);
  4313. await cg.indexAll();
  4314. cg.resolveReferences();
  4315. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  4316. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  4317. expect(product, 'main-product section').toBeDefined();
  4318. expect(login, 'main-login section').toBeDefined();
  4319. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  4320. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  4321. });
  4322. });
  4323. describe('Lua/Luau require resolution', () => {
  4324. let tempDir: string;
  4325. let cg: CodeGraph;
  4326. beforeEach(() => {
  4327. tempDir = createTempDir();
  4328. });
  4329. afterEach(() => {
  4330. if (cg) cg.close();
  4331. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4332. });
  4333. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  4334. // The require is the ONLY link (no method call), so coverage here proves the
  4335. // require resolver specifically, not method-call name-matching.
  4336. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  4337. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  4338. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  4339. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  4340. // Luau Roblox instance-path require (only the leaf survives extraction):
  4341. // require(script.Util.helper) → src/Util/helper.luau.
  4342. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  4343. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  4344. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  4345. cg = CodeGraph.initSync(tempDir);
  4346. await cg.indexAll();
  4347. cg.resolveReferences();
  4348. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  4349. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  4350. expect(config, 'config.lua file node').toBeDefined();
  4351. expect(helper, 'helper.luau file node').toBeDefined();
  4352. const cfgDeps = cg.getFileDependents(config!.filePath);
  4353. const helpDeps = cg.getFileDependents(helper!.filePath);
  4354. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  4355. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  4356. });
  4357. });
  4358. describe('Rust module-path call resolution', () => {
  4359. let tempDir: string;
  4360. let cg: CodeGraph;
  4361. beforeEach(() => {
  4362. tempDir = createTempDir();
  4363. });
  4364. afterEach(() => {
  4365. if (cg) cg.close();
  4366. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4367. });
  4368. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  4369. // The canonical Axum router-assembly pattern: a parent module calls each
  4370. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  4371. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  4372. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  4373. // resolved crate-relative only (looking for `src/users.rs`), so it found
  4374. // nothing and the handler modules looked dependent-less.
  4375. const http = path.join(tempDir, 'src/http');
  4376. fs.mkdirSync(http, { recursive: true });
  4377. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  4378. fs.writeFileSync(
  4379. path.join(http, 'mod.rs'),
  4380. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  4381. );
  4382. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  4383. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  4384. cg = CodeGraph.initSync(tempDir);
  4385. await cg.indexAll();
  4386. cg.resolveReferences();
  4387. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  4388. // proving the bare prefix resolved self-relative AND disambiguated the
  4389. // colliding `router` name to the correct file (not an arbitrary one).
  4390. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  4391. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  4392. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  4393. expect(usersRouter, 'users.rs router fn').toBeDefined();
  4394. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  4395. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4396. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4397. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  4398. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  4399. });
  4400. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  4401. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  4402. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  4403. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  4404. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  4405. // Rust path resolver and the leaf module looked dependent-less.
  4406. const routes = path.join(tempDir, 'src/routes');
  4407. const database = path.join(tempDir, 'src/database');
  4408. fs.mkdirSync(routes, { recursive: true });
  4409. fs.mkdirSync(database, { recursive: true });
  4410. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  4411. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  4412. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  4413. fs.writeFileSync(
  4414. path.join(routes, 'mod.rs'),
  4415. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  4416. );
  4417. cg = CodeGraph.initSync(tempDir);
  4418. await cg.indexAll();
  4419. cg.resolveReferences();
  4420. const find = cg
  4421. .getNodesByKind('function')
  4422. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  4423. expect(find, 'database/profiles.rs find fn').toBeDefined();
  4424. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4425. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  4426. });
  4427. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  4428. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  4429. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  4430. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  4431. // like they have no caller. The route-macro extractor reconstructs each path
  4432. // and emits a reference, which the Rust path resolver links to the handler.
  4433. const routes = path.join(tempDir, 'src/routes');
  4434. fs.mkdirSync(routes, { recursive: true });
  4435. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  4436. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  4437. ` rocket::build()\n` +
  4438. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  4439. ` .register("/", catchers![not_found]);\n}\n`);
  4440. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  4441. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  4442. cg = CodeGraph.initSync(tempDir);
  4443. await cg.indexAll();
  4444. cg.resolveReferences();
  4445. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  4446. expect(handlers.length, 'both handler fns indexed').toBe(2);
  4447. for (const h of handlers) {
  4448. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4449. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  4450. }
  4451. });
  4452. });
  4453. describe('SvelteKit load → page synthesizer', () => {
  4454. let tempDir: string;
  4455. let cg: CodeGraph;
  4456. beforeEach(() => {
  4457. tempDir = createTempDir();
  4458. });
  4459. afterEach(() => {
  4460. if (cg) cg.close();
  4461. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4462. });
  4463. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  4464. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  4465. // PATH — there is no static import — so editing a loader showed no impact on
  4466. // the page it feeds. The synthesizer links each page component to the `load`
  4467. // in its OWN directory (path-deterministic, so it never crosses routes).
  4468. const login = path.join(tempDir, 'src/routes/login');
  4469. const register = path.join(tempDir, 'src/routes/register');
  4470. fs.mkdirSync(login, { recursive: true });
  4471. fs.mkdirSync(register, { recursive: true });
  4472. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  4473. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  4474. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  4475. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  4476. cg = CodeGraph.initSync(tempDir);
  4477. await cg.indexAll();
  4478. cg.resolveReferences();
  4479. const loginLoad = cg
  4480. .getNodesByKind('function')
  4481. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  4482. expect(loginLoad, 'login load fn').toBeDefined();
  4483. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  4484. // editing login's load surfaces login's page (the framework-wired data flow)…
  4485. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  4486. // …but never register's page (same-directory only).
  4487. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  4488. });
  4489. });
  4490. describe('Nuxt nested auto-imported component resolution', () => {
  4491. let tempDir: string;
  4492. let cg: CodeGraph;
  4493. beforeEach(() => {
  4494. tempDir = createTempDir();
  4495. });
  4496. afterEach(() => {
  4497. if (cg) cg.close();
  4498. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4499. });
  4500. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  4501. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  4502. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  4503. // component node is named by basename (`Card`), so the PascalCase usage
  4504. // didn't resolve and the nested component looked unused.
  4505. const media = path.join(tempDir, 'components/media');
  4506. fs.mkdirSync(media, { recursive: true });
  4507. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  4508. fs.writeFileSync(
  4509. path.join(tempDir, 'components/Grid.vue'),
  4510. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  4511. );
  4512. cg = CodeGraph.initSync(tempDir);
  4513. await cg.indexAll();
  4514. cg.resolveReferences();
  4515. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  4516. expect(card, 'media/Card.vue component').toBeDefined();
  4517. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4518. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  4519. });
  4520. });
  4521. describe('Swift property-wrapper attribute type references', () => {
  4522. let tempDir: string;
  4523. let cg: CodeGraph;
  4524. beforeEach(() => {
  4525. tempDir = createTempDir();
  4526. });
  4527. afterEach(() => {
  4528. if (cg) cg.close();
  4529. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4530. });
  4531. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  4532. // A many-to-many pivot/join model is referenced ONLY through the relationship
  4533. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  4534. // query. The wrapper type was captured but the argument expression wasn't
  4535. // walked, so the pivot model looked like nothing depended on it.
  4536. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  4537. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  4538. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  4539. `import Fluent\nfinal class Acronym: Model {\n` +
  4540. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  4541. ` var categories: [Category]\n}\n`);
  4542. cg = CodeGraph.initSync(tempDir);
  4543. await cg.indexAll();
  4544. cg.resolveReferences();
  4545. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  4546. expect(pivot, 'pivot model class').toBeDefined();
  4547. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4548. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  4549. });
  4550. });
  4551. describe('Objective-C messages, class receivers, and #import', () => {
  4552. let tempDir: string;
  4553. let cg: CodeGraph;
  4554. beforeEach(() => {
  4555. tempDir = createTempDir();
  4556. });
  4557. afterEach(() => {
  4558. if (cg) cg.close();
  4559. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4560. });
  4561. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  4562. fs.writeFileSync(
  4563. path.join(tempDir, 'SDImageCache.h'),
  4564. `#import <Foundation/Foundation.h>
  4565. @interface SDImageCache : NSObject
  4566. + (instancetype)sharedCache;
  4567. + (void)storeImage:(NSString *)key;
  4568. @end
  4569. `
  4570. );
  4571. fs.writeFileSync(
  4572. path.join(tempDir, 'SDImageCache.m'),
  4573. `#import "SDImageCache.h"
  4574. @implementation SDImageCache
  4575. + (instancetype)sharedCache { return nil; }
  4576. + (void)storeImage:(NSString *)key { }
  4577. @end
  4578. `
  4579. );
  4580. fs.writeFileSync(
  4581. path.join(tempDir, 'SDManager.m'),
  4582. `#import "SDImageCache.h"
  4583. @interface SDManager : NSObject
  4584. @end
  4585. @implementation SDManager
  4586. - (void)run {
  4587. [SDImageCache sharedCache];
  4588. [SDImageCache storeImage:@"k"];
  4589. }
  4590. @end
  4591. `
  4592. );
  4593. cg = CodeGraph.initSync(tempDir);
  4594. await cg.indexAll();
  4595. cg.resolveReferences();
  4596. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  4597. // to the `storeImage:` method — named WITH its colon both at the call site
  4598. // and the definition (before the fix the call site dropped the colon).
  4599. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  4600. expect(storeImage, 'storeImage: method').toBeDefined();
  4601. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4602. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4603. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  4604. // SDImageCache class (whose @interface lives in the header).
  4605. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  4606. expect(cache, 'SDImageCache class').toBeDefined();
  4607. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4608. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4609. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  4610. // surfaces both importers.
  4611. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  4612. expect(header, 'SDImageCache.h indexed').toBeDefined();
  4613. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4614. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4615. });
  4616. });
  4617. describe('Full Indexing', () => {
  4618. let tempDir: string;
  4619. beforeEach(() => {
  4620. tempDir = createTempDir();
  4621. });
  4622. afterEach(() => {
  4623. cleanupTempDir(tempDir);
  4624. });
  4625. it('should index a TypeScript file', async () => {
  4626. // Create test file
  4627. const srcDir = path.join(tempDir, 'src');
  4628. fs.mkdirSync(srcDir);
  4629. fs.writeFileSync(
  4630. path.join(srcDir, 'utils.ts'),
  4631. `
  4632. export function add(a: number, b: number): number {
  4633. return a + b;
  4634. }
  4635. export function multiply(a: number, b: number): number {
  4636. return a * b;
  4637. }
  4638. `
  4639. );
  4640. // Initialize and index
  4641. const cg = CodeGraph.initSync(tempDir);
  4642. const result = await cg.indexAll();
  4643. expect(result.success).toBe(true);
  4644. expect(result.filesIndexed).toBe(1);
  4645. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  4646. // Check nodes were stored
  4647. const nodes = cg.getNodesInFile('src/utils.ts');
  4648. expect(nodes.length).toBeGreaterThanOrEqual(2);
  4649. const addFunc = nodes.find((n) => n.name === 'add');
  4650. expect(addFunc).toBeDefined();
  4651. expect(addFunc?.kind).toBe('function');
  4652. cg.close();
  4653. });
  4654. it('should index multiple files', async () => {
  4655. // Create test files
  4656. const srcDir = path.join(tempDir, 'src');
  4657. fs.mkdirSync(srcDir);
  4658. fs.writeFileSync(
  4659. path.join(srcDir, 'math.ts'),
  4660. `export function add(a: number, b: number) { return a + b; }`
  4661. );
  4662. fs.writeFileSync(
  4663. path.join(srcDir, 'string.ts'),
  4664. `export function capitalize(s: string) { return s.toUpperCase(); }`
  4665. );
  4666. // Initialize and index
  4667. const cg = CodeGraph.initSync(tempDir);
  4668. const result = await cg.indexAll();
  4669. expect(result.success).toBe(true);
  4670. expect(result.filesIndexed).toBe(2);
  4671. const files = cg.getFiles();
  4672. expect(files.length).toBe(2);
  4673. cg.close();
  4674. });
  4675. it('should track file hashes for incremental updates', async () => {
  4676. // Create initial file
  4677. const srcDir = path.join(tempDir, 'src');
  4678. fs.mkdirSync(srcDir);
  4679. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4680. // Initialize and index
  4681. const cg = CodeGraph.initSync(tempDir);
  4682. await cg.indexAll();
  4683. // Check file is tracked
  4684. const file = cg.getFile('src/main.ts');
  4685. expect(file).toBeDefined();
  4686. expect(file?.contentHash).toBeDefined();
  4687. // Modify file
  4688. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4689. // Check for changes
  4690. const changes = cg.getChangedFiles();
  4691. expect(changes.modified).toContain('src/main.ts');
  4692. cg.close();
  4693. });
  4694. it('should sync and detect changes', async () => {
  4695. // Create initial file
  4696. const srcDir = path.join(tempDir, 'src');
  4697. fs.mkdirSync(srcDir);
  4698. fs.writeFileSync(
  4699. path.join(srcDir, 'main.ts'),
  4700. `export function original() { return 1; }`
  4701. );
  4702. // Initialize and index
  4703. const cg = CodeGraph.initSync(tempDir);
  4704. await cg.indexAll();
  4705. const initialNodes = cg.getNodesInFile('src/main.ts');
  4706. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4707. // Modify file
  4708. fs.writeFileSync(
  4709. path.join(srcDir, 'main.ts'),
  4710. `export function updated() { return 2; }`
  4711. );
  4712. // Sync
  4713. const syncResult = await cg.sync();
  4714. expect(syncResult.filesModified).toBe(1);
  4715. // Check nodes were updated
  4716. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4717. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4718. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4719. cg.close();
  4720. });
  4721. it('should count file-level tracked YAML files as indexed', async () => {
  4722. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4723. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4724. const cg = CodeGraph.initSync(tempDir);
  4725. const result = await cg.indexAll();
  4726. expect(result.success).toBe(true);
  4727. expect(result.filesIndexed).toBe(2);
  4728. expect(result.filesSkipped).toBe(0);
  4729. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4730. cg.close();
  4731. });
  4732. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4733. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4734. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4735. const cg = CodeGraph.initSync(tempDir);
  4736. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4737. expect(result.success).toBe(true);
  4738. expect(result.filesIndexed).toBe(2);
  4739. expect(result.filesSkipped).toBe(0);
  4740. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4741. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4742. cg.close();
  4743. });
  4744. it('should count file-level tracked .properties files as indexed', async () => {
  4745. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4746. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4747. const cg = CodeGraph.initSync(tempDir);
  4748. const result = await cg.indexAll();
  4749. expect(result.success).toBe(true);
  4750. expect(result.filesIndexed).toBe(2);
  4751. expect(result.filesSkipped).toBe(0);
  4752. cg.close();
  4753. });
  4754. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4755. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4756. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4757. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4758. const cg = CodeGraph.initSync(tempDir);
  4759. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4760. expect(result.success).toBe(true);
  4761. expect(result.filesIndexed).toBe(3);
  4762. expect(result.filesSkipped).toBe(0);
  4763. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4764. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4765. cg.close();
  4766. });
  4767. });
  4768. describe('Path Normalization', () => {
  4769. it('should convert backslashes to forward slashes', () => {
  4770. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4771. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4772. });
  4773. it('should leave forward-slash paths unchanged', () => {
  4774. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4775. });
  4776. it('should handle empty string', () => {
  4777. expect(normalizePath('')).toBe('');
  4778. });
  4779. });
  4780. describe('Directory Exclusion', () => {
  4781. let tempDir: string;
  4782. beforeEach(() => {
  4783. tempDir = createTempDir();
  4784. });
  4785. afterEach(() => {
  4786. cleanupTempDir(tempDir);
  4787. });
  4788. it('should exclude directories listed in .gitignore', () => {
  4789. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4790. const srcDir = path.join(tempDir, 'src');
  4791. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4792. fs.mkdirSync(srcDir, { recursive: true });
  4793. fs.mkdirSync(nmDir, { recursive: true });
  4794. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4795. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4796. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4797. const files = scanDirectory(tempDir);
  4798. expect(files).toContain('src/index.ts');
  4799. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4800. });
  4801. it('should exclude nested node_modules via a root .gitignore', () => {
  4802. // A trailing-slash pattern with no leading slash matches at any depth.
  4803. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4804. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4805. fs.mkdirSync(srcDir, { recursive: true });
  4806. fs.mkdirSync(nmDir, { recursive: true });
  4807. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4808. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4809. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4810. const files = scanDirectory(tempDir);
  4811. expect(files).toContain('packages/app/src/index.ts');
  4812. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4813. });
  4814. it('should apply a nested .gitignore only to its own subtree', () => {
  4815. const appSrc = path.join(tempDir, 'app', 'src');
  4816. fs.mkdirSync(appSrc, { recursive: true });
  4817. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4818. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4819. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4820. // A sibling with the same name outside app/ must NOT be ignored.
  4821. const otherDir = path.join(tempDir, 'other', 'src');
  4822. fs.mkdirSync(otherDir, { recursive: true });
  4823. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4824. const files = scanDirectory(tempDir);
  4825. expect(files).toContain('app/src/keep.ts');
  4826. expect(files).not.toContain('app/src/skip.ts');
  4827. expect(files).toContain('other/src/skip.ts');
  4828. });
  4829. it('should always skip .git directories', () => {
  4830. const srcDir = path.join(tempDir, 'src');
  4831. const gitDir = path.join(tempDir, '.git', 'objects');
  4832. fs.mkdirSync(srcDir, { recursive: true });
  4833. fs.mkdirSync(gitDir, { recursive: true });
  4834. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4835. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  4836. const files = scanDirectory(tempDir);
  4837. expect(files).toContain('src/index.ts');
  4838. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  4839. });
  4840. it('should return forward-slash paths on all platforms', () => {
  4841. const srcDir = path.join(tempDir, 'src', 'components');
  4842. fs.mkdirSync(srcDir, { recursive: true });
  4843. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  4844. const files = scanDirectory(tempDir);
  4845. expect(files.length).toBe(1);
  4846. expect(files[0]).toBe('src/components/Button.tsx');
  4847. expect(files[0]).not.toContain('\\');
  4848. });
  4849. });
  4850. describe('Git Submodules', () => {
  4851. let tempDir: string;
  4852. beforeEach(() => {
  4853. tempDir = createTempDir();
  4854. });
  4855. afterEach(() => {
  4856. cleanupTempDir(tempDir);
  4857. });
  4858. it('should index files inside git submodules (issue #147)', async () => {
  4859. const { execFileSync } = await import('child_process');
  4860. const git = (cwd: string, ...args: string[]) =>
  4861. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4862. // Build a separate "library" repo to use as a submodule source.
  4863. const libDir = path.join(tempDir, '_lib');
  4864. fs.mkdirSync(libDir, { recursive: true });
  4865. git(libDir, 'init', '-q');
  4866. git(libDir, 'config', 'user.email', 'test@test.com');
  4867. git(libDir, 'config', 'user.name', 'Test');
  4868. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  4869. git(libDir, 'add', '-A');
  4870. git(libDir, 'commit', '-q', '-m', 'lib init');
  4871. // Build the main repo and add the lib repo as a submodule.
  4872. const mainDir = path.join(tempDir, 'main');
  4873. fs.mkdirSync(mainDir, { recursive: true });
  4874. git(mainDir, 'init', '-q');
  4875. git(mainDir, 'config', 'user.email', 'test@test.com');
  4876. git(mainDir, 'config', 'user.name', 'Test');
  4877. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  4878. git(mainDir, 'add', '-A');
  4879. git(mainDir, 'commit', '-q', '-m', 'app init');
  4880. // protocol.file.allow=always is required to add a local-path submodule on
  4881. // recent git versions (CVE-2022-39253 mitigation).
  4882. execFileSync(
  4883. 'git',
  4884. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  4885. { cwd: mainDir, stdio: 'pipe' }
  4886. );
  4887. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  4888. const files = scanDirectory(mainDir);
  4889. expect(files).toContain('app.ts');
  4890. expect(files).toContain('libs/lib/lib.ts');
  4891. });
  4892. });
  4893. describe('Nested gitlink repos (#1031, #1033)', () => {
  4894. let tempDir: string;
  4895. // Helper: make a self-contained git repo at `dir` with one committed TS file.
  4896. const makeRepo = async (dir: string, base: string) => {
  4897. const { execFileSync } = await import('child_process');
  4898. const git = (...args: string[]) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
  4899. fs.mkdirSync(dir, { recursive: true });
  4900. git('init', '-q');
  4901. git('config', 'user.email', 'test@test.com');
  4902. git('config', 'user.name', 'Test');
  4903. fs.writeFileSync(path.join(dir, `${base}.ts`), `export const ${base} = 1;`);
  4904. git('add', '-A');
  4905. git('commit', '-q', '-m', `${base} init`);
  4906. };
  4907. beforeEach(() => {
  4908. tempDir = createTempDir();
  4909. });
  4910. afterEach(() => {
  4911. cleanupTempDir(tempDir);
  4912. });
  4913. // The #1031 case: a nested repo `git add`ed inside the super-repo becomes a
  4914. // gitlink (mode 160000) with NO `.gitmodules`. It is tracked (so it never shows
  4915. // in the untracked `-o` listing) yet not an active submodule (so
  4916. // `--recurse-submodules` won't expand it) — it used to fall through both passes
  4917. // and only the super-repo's own files got indexed.
  4918. it('indexes a bare gitlink (git add\'ed embedded repo, no .gitmodules), recursively', async () => {
  4919. const { execFileSync } = await import('child_process');
  4920. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4921. const root = path.join(tempDir, 'root');
  4922. await makeRepo(root, 'app');
  4923. // An embedded clone, itself holding a further nested clone (untracked inside it).
  4924. await makeRepo(path.join(root, 'embedded'), 'inner');
  4925. await makeRepo(path.join(root, 'embedded', 'deep'), 'deep');
  4926. // `git add embedded` records it as a 160000 gitlink (no fetch, no .gitmodules).
  4927. git(root, 'add', 'embedded');
  4928. git(root, 'commit', '-q', '-m', 'add embedded as gitlink');
  4929. expect(fs.existsSync(path.join(root, '.gitmodules'))).toBe(false);
  4930. const files = scanDirectory(root);
  4931. expect(files).toContain('app.ts');
  4932. expect(files).toContain('embedded/inner.ts'); // the gitlink's own source
  4933. expect(files).toContain('embedded/deep/deep.ts'); // recursion continues into its nested repo
  4934. });
  4935. // The -c → -s switch must not regress active submodules (#147): a repo can hold
  4936. // BOTH an active submodule (expanded by --recurse-submodules) and a bare gitlink
  4937. // (handled by the new pass), and the mixed 160000/100644 modes must parse right.
  4938. it('indexes a gitlink alongside an active submodule', async () => {
  4939. const { execFileSync } = await import('child_process');
  4940. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4941. const lib = path.join(tempDir, '_lib');
  4942. await makeRepo(lib, 'lib');
  4943. const root = path.join(tempDir, 'root');
  4944. await makeRepo(root, 'app');
  4945. // A proper, active submodule.
  4946. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: root, stdio: 'pipe' });
  4947. git(root, 'commit', '-q', '-m', 'add submodule');
  4948. // A bare gitlink in the same repo (under a non-ignored dir name).
  4949. await makeRepo(path.join(root, 'external', 'tool'), 'tool');
  4950. git(root, 'add', 'external/tool');
  4951. git(root, 'commit', '-q', '-m', 'add gitlink');
  4952. const files = scanDirectory(root);
  4953. expect(files).toContain('app.ts');
  4954. expect(files).toContain('libs/lib/lib.ts'); // active submodule still expands (#147)
  4955. expect(files).toContain('external/tool/tool.ts'); // bare gitlink now indexed
  4956. });
  4957. // A gitlink under a built-in default-ignored directory (vendor/, node_modules/,
  4958. // …) stays excluded — a committed dependency doesn't become project code just
  4959. // because it's a nested repo. Mirrors how the untracked-embedded path treats
  4960. // the same dirs (#407), so the two passes agree.
  4961. it('does not index a gitlink under a default-ignored directory (e.g. vendor/)', async () => {
  4962. const { execFileSync } = await import('child_process');
  4963. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  4964. const root = path.join(tempDir, 'root');
  4965. await makeRepo(root, 'app');
  4966. await makeRepo(path.join(root, 'vendor', 'pkg'), 'dep');
  4967. git(root, 'add', 'vendor/pkg');
  4968. git(root, 'commit', '-q', '-m', 'add vendored gitlink');
  4969. const files = scanDirectory(root);
  4970. expect(files).toContain('app.ts');
  4971. expect(files).not.toContain('vendor/pkg/dep.ts');
  4972. });
  4973. // A gitlink with NO working tree on disk (the common "cloned without
  4974. // --recurse-submodules" state) has nothing to index — we must leave it alone,
  4975. // not fabricate entries, and must not break the rest of the scan.
  4976. it('leaves an uninitialized submodule (no checkout on disk) alone', async () => {
  4977. const { execFileSync } = await import('child_process');
  4978. const lib = path.join(tempDir, '_lib');
  4979. await makeRepo(lib, 'lib');
  4980. const sup = path.join(tempDir, 'super');
  4981. await makeRepo(sup, 'app');
  4982. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: sup, stdio: 'pipe' });
  4983. execFileSync('git', ['commit', '-q', '-m', 'add submodule'], { cwd: sup, stdio: 'pipe' });
  4984. // Clone the super-repo WITHOUT --recurse-submodules → libs/lib is an empty
  4985. // gitlink dir (mode 160000, no `.git` inside, no files).
  4986. const clone = path.join(tempDir, 'clone');
  4987. execFileSync('git', ['clone', '-q', sup, clone], { stdio: 'pipe' });
  4988. expect(fs.readdirSync(path.join(clone, 'libs', 'lib'))).toHaveLength(0);
  4989. const files = scanDirectory(clone);
  4990. expect(files).toContain('app.ts');
  4991. expect(files).not.toContain('libs/lib/lib.ts'); // not on disk → correctly absent
  4992. });
  4993. // #1065: a gitlink under a path the super-repo's OWN `.gitignore` covers is the
  4994. // tracked-gitlink twin of the untracked-ignored embedded repo (#514, #970). The
  4995. // gitlink-discovery pass must honor that `.gitignore` the same way — otherwise a
  4996. // gitignored reference/benchmark corpus full of `git add`ed clones gets pulled
  4997. // into the index (the 138k-file blow-up the reporter hit). Respect it by default;
  4998. // re-include only via `codegraph.json` `includeIgnored`.
  4999. it('does not index a gitlink under a gitignored directory by default (#1065)', async () => {
  5000. const { execFileSync } = await import('child_process');
  5001. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5002. const root = path.join(tempDir, 'root');
  5003. await makeRepo(root, 'app');
  5004. // An embedded clone under a path the super-repo gitignores (a benchmark corpus).
  5005. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  5006. git(root, 'add', 'benchmark/repos/ref'); // tracked as a 160000 gitlink
  5007. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  5008. git(root, 'add', '.gitignore');
  5009. git(root, 'commit', '-q', '-m', 'add gitignored gitlink + ignore rule');
  5010. const files = scanDirectory(root);
  5011. expect(files).toContain('app.ts');
  5012. expect(files).not.toContain('benchmark/repos/ref/ref.ts'); // gitignored → excluded
  5013. // The watcher path agrees: the ignored root is never discovered, and the dir is
  5014. // pruned (the reporter's exact clue — `ignores('benchmark/repos/')` was false).
  5015. expect(discoverEmbeddedRepoRoots(root)).toEqual([]);
  5016. expect(buildScopeIgnore(root).ignores('benchmark/repos/')).toBe(true);
  5017. expect(buildScopeIgnore(root).ignores('benchmark/repos/ref/ref.ts')).toBe(true);
  5018. });
  5019. it('re-includes a gitignored gitlink when codegraph.json includeIgnored opts in (#1065)', async () => {
  5020. const { execFileSync } = await import('child_process');
  5021. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5022. const root = path.join(tempDir, 'root');
  5023. await makeRepo(root, 'app');
  5024. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  5025. git(root, 'add', 'benchmark/repos/ref');
  5026. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  5027. fs.writeFileSync(path.join(root, 'codegraph.json'), JSON.stringify({ includeIgnored: ['benchmark/repos/'] }));
  5028. git(root, 'add', '.gitignore', 'codegraph.json');
  5029. git(root, 'commit', '-q', '-m', 'opt the gitignored gitlink back in');
  5030. const files = scanDirectory(root);
  5031. expect(files).toContain('app.ts');
  5032. expect(files).toContain('benchmark/repos/ref/ref.ts'); // opted in → indexed
  5033. expect(discoverEmbeddedRepoRoots(root)).toContain('benchmark/repos/ref/');
  5034. });
  5035. });
  5036. describe('Nested non-submodule git repos', () => {
  5037. let tempDir: string;
  5038. beforeEach(() => {
  5039. tempDir = createTempDir();
  5040. });
  5041. afterEach(() => {
  5042. cleanupTempDir(tempDir);
  5043. });
  5044. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  5045. const { execFileSync } = await import('child_process');
  5046. const git = (cwd: string, ...args: string[]) =>
  5047. execFileSync('git', args, { cwd, stdio: 'pipe' });
  5048. // Top-level workspace is itself a git repo, holding no source directly —
  5049. // the CMake "super-repo" layout from the issue.
  5050. const root = path.join(tempDir, 'root');
  5051. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  5052. git(root, 'init', '-q');
  5053. git(root, 'config', 'user.email', 'test@test.com');
  5054. git(root, 'config', 'user.name', 'Test');
  5055. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  5056. // Two independent clones living inside the workspace (NOT submodules):
  5057. // one with committed source, one with only untracked source.
  5058. const sub1 = path.join(root, 'sub_repo1', 'src');
  5059. fs.mkdirSync(sub1, { recursive: true });
  5060. git(path.join(root, 'sub_repo1'), 'init', '-q');
  5061. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  5062. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  5063. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  5064. git(path.join(root, 'sub_repo1'), 'add', '-A');
  5065. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  5066. const sub2 = path.join(root, 'sub_repo2', 'src');
  5067. fs.mkdirSync(sub2, { recursive: true });
  5068. git(path.join(root, 'sub_repo2'), 'init', '-q');
  5069. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  5070. const files = scanDirectory(root);
  5071. // Both committed and untracked source from the nested repos must be found.
  5072. expect(files).toContain('sub_repo1/src/one.ts');
  5073. expect(files).toContain('sub_repo2/src/two.ts');
  5074. });
  5075. it('should respect each embedded repo\'s own .gitignore', async () => {
  5076. const { execFileSync } = await import('child_process');
  5077. const git = (cwd: string, ...args: string[]) =>
  5078. execFileSync('git', args, { cwd, stdio: 'pipe' });
  5079. const root = path.join(tempDir, 'root');
  5080. fs.mkdirSync(root, { recursive: true });
  5081. git(root, 'init', '-q');
  5082. const sub = path.join(root, 'sub_repo', 'src');
  5083. fs.mkdirSync(sub, { recursive: true });
  5084. git(path.join(root, 'sub_repo'), 'init', '-q');
  5085. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  5086. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  5087. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  5088. const files = scanDirectory(root);
  5089. expect(files).toContain('sub_repo/src/real.ts');
  5090. expect(files).not.toContain('sub_repo/src/generated.ts');
  5091. });
  5092. // A .gitignore the `ignore` library can't compile to a regex must not abort
  5093. // the whole scan — the bad pattern is dropped, valid ones still apply (#682).
  5094. it('does not crash on a .gitignore with an uncompilable pattern (#682)', () => {
  5095. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  5096. fs.mkdirSync(path.join(tempDir, 'build'), { recursive: true });
  5097. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  5098. fs.writeFileSync(path.join(tempDir, 'build', 'out.ts'), 'export const y = 2;');
  5099. // `\\[` makes the matcher build an unterminated character class — the throw
  5100. // is lazy (at match time), which is what escaped and killed sync.
  5101. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'build/\n\\\\[\n');
  5102. let files: string[] = [];
  5103. expect(() => {
  5104. files = scanDirectory(tempDir);
  5105. }).not.toThrow();
  5106. expect(files).toContain('src/real.ts');
  5107. // The still-valid `build/` rule is honored; only the bad line was dropped.
  5108. expect(files.some((f) => f.startsWith('build/'))).toBe(false);
  5109. });
  5110. // A .gitignore that isn't valid UTF-8 — e.g. encrypted in place by corporate
  5111. // DLP / endpoint software (UTF-16 header + ciphertext) — is skipped whole,
  5112. // not fed to the matcher as garbage patterns (#682).
  5113. it('does not crash on a non-UTF-8 (DLP-encrypted) .gitignore (#682)', () => {
  5114. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  5115. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  5116. const header = Buffer.concat([
  5117. Buffer.from([0x00, 0x00]),
  5118. Buffer.from('[notice][user]', 'utf16le'),
  5119. ]);
  5120. const junk = Buffer.from([0x5b, 0x99, 0xc3, 0x28, 0x5c, 0x5b, 0xff, 0xfd]);
  5121. fs.writeFileSync(path.join(tempDir, '.gitignore'), Buffer.concat([header, junk]));
  5122. let files: string[] = [];
  5123. expect(() => {
  5124. files = scanDirectory(tempDir);
  5125. }).not.toThrow();
  5126. expect(files).toContain('src/real.ts');
  5127. });
  5128. it('buildDefaultIgnore survives a bad .gitignore and still applies valid rules (#682)', () => {
  5129. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'dist/\n\\\\[\n');
  5130. const ig = buildDefaultIgnore(tempDir);
  5131. expect(() => ig.ignores('src/app.ts')).not.toThrow();
  5132. expect(ig.ignores('dist/')).toBe(true); // valid rule survives
  5133. expect(ig.ignores('src/app.ts')).toBe(false);
  5134. });
  5135. });
  5136. // =============================================================================
  5137. // Scala
  5138. // =============================================================================
  5139. describe('Scala Extraction', () => {
  5140. describe('Language detection', () => {
  5141. it('should detect Scala files', () => {
  5142. expect(detectLanguage('Main.scala')).toBe('scala');
  5143. expect(detectLanguage('script.sc')).toBe('scala');
  5144. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  5145. });
  5146. it('should report Scala as supported', () => {
  5147. expect(isLanguageSupported('scala')).toBe(true);
  5148. expect(getSupportedLanguages()).toContain('scala');
  5149. });
  5150. });
  5151. describe('Class extraction', () => {
  5152. it('should extract class definitions', () => {
  5153. const code = `
  5154. class UserService(private val repo: UserRepository) {
  5155. def findUser(id: String): Option[String] = Some(id)
  5156. }
  5157. `;
  5158. const result = extractFromSource('UserService.scala', code);
  5159. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  5160. expect(cls).toBeDefined();
  5161. expect(cls?.language).toBe('scala');
  5162. });
  5163. it('should extract object definitions as class kind', () => {
  5164. const code = `
  5165. object DatabaseConfig {
  5166. val url = "jdbc:postgresql://localhost/mydb"
  5167. }
  5168. `;
  5169. const result = extractFromSource('Config.scala', code);
  5170. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  5171. expect(obj).toBeDefined();
  5172. });
  5173. it('should extract trait definitions as trait kind', () => {
  5174. const code = `
  5175. trait Repository[A] {
  5176. def findById(id: String): Option[A]
  5177. def save(entity: A): Unit
  5178. }
  5179. `;
  5180. const result = extractFromSource('Repository.scala', code);
  5181. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  5182. expect(trait_).toBeDefined();
  5183. });
  5184. });
  5185. describe('Method and function extraction', () => {
  5186. it('should extract method definitions inside a class', () => {
  5187. const code = `
  5188. class Calculator {
  5189. def add(a: Int, b: Int): Int = a + b
  5190. def divide(a: Double, b: Double): Double = a / b
  5191. }
  5192. `;
  5193. const result = extractFromSource('Calculator.scala', code);
  5194. const methods = result.nodes.filter((n) => n.kind === 'method');
  5195. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  5196. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  5197. });
  5198. it('should extract method signatures', () => {
  5199. const code = `
  5200. class Greeter {
  5201. def greet(name: String): String = s"Hello, \${name}!"
  5202. }
  5203. `;
  5204. const result = extractFromSource('Greeter.scala', code);
  5205. const method = result.nodes.find((n) => n.name === 'greet');
  5206. expect(method?.signature).toContain('name: String');
  5207. expect(method?.signature).toContain('String');
  5208. });
  5209. it('should extract top-level function definitions as functions', () => {
  5210. const code = `
  5211. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  5212. def greet(name: String): String = s"Hello, \${name}!"
  5213. `;
  5214. const result = extractFromSource('utils.scala', code);
  5215. const fns = result.nodes.filter((n) => n.kind === 'function');
  5216. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  5217. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  5218. });
  5219. });
  5220. describe('Val and var extraction', () => {
  5221. it('should extract val inside a class as field', () => {
  5222. const code = `
  5223. class Config {
  5224. val timeout: Int = 30
  5225. val host: String = "localhost"
  5226. }
  5227. `;
  5228. const result = extractFromSource('Config.scala', code);
  5229. const fields = result.nodes.filter((n) => n.kind === 'field');
  5230. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  5231. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  5232. });
  5233. it('should extract var inside a class as field', () => {
  5234. const code = `
  5235. class Counter {
  5236. var count: Int = 0
  5237. }
  5238. `;
  5239. const result = extractFromSource('Counter.scala', code);
  5240. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  5241. expect(field).toBeDefined();
  5242. });
  5243. it('should extract top-level val as constant', () => {
  5244. const code = `
  5245. val MaxConnections: Int = 100
  5246. val DefaultTimeout = 30
  5247. `;
  5248. const result = extractFromSource('constants.scala', code);
  5249. const consts = result.nodes.filter((n) => n.kind === 'constant');
  5250. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  5251. });
  5252. it('should extract top-level var as variable', () => {
  5253. const code = `
  5254. var retries: Int = 3
  5255. `;
  5256. const result = extractFromSource('state.scala', code);
  5257. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  5258. expect(v).toBeDefined();
  5259. });
  5260. it('should include type in val/var signature', () => {
  5261. const code = `
  5262. class Service {
  5263. val timeout: Int = 30
  5264. }
  5265. `;
  5266. const result = extractFromSource('Service.scala', code);
  5267. const field = result.nodes.find((n) => n.name === 'timeout');
  5268. expect(field?.signature).toContain('timeout');
  5269. expect(field?.signature).toContain('Int');
  5270. });
  5271. });
  5272. describe('Enum extraction', () => {
  5273. it('should extract enum definitions', () => {
  5274. const code = `
  5275. enum Color:
  5276. case Red
  5277. case Green
  5278. case Blue
  5279. `;
  5280. const result = extractFromSource('Color.scala', code);
  5281. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  5282. expect(enumNode).toBeDefined();
  5283. });
  5284. it('should extract enum cases as enum_member', () => {
  5285. const code = `
  5286. enum Direction:
  5287. case North
  5288. case South
  5289. case East
  5290. case West
  5291. `;
  5292. const result = extractFromSource('Direction.scala', code);
  5293. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  5294. expect(members.find((m) => m.name === 'North')).toBeDefined();
  5295. expect(members.find((m) => m.name === 'South')).toBeDefined();
  5296. expect(members.length).toBeGreaterThanOrEqual(4);
  5297. });
  5298. });
  5299. describe('Type alias extraction', () => {
  5300. it('should extract type aliases', () => {
  5301. const code = `
  5302. type UserId = String
  5303. type UserMap = Map[String, String]
  5304. `;
  5305. const result = extractFromSource('types.scala', code);
  5306. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5307. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  5308. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  5309. });
  5310. });
  5311. describe('Import extraction', () => {
  5312. it('should extract import declarations', () => {
  5313. const code = `
  5314. import scala.collection.mutable.ListBuffer
  5315. import scala.concurrent.Future
  5316. `;
  5317. const result = extractFromSource('imports.scala', code);
  5318. const imports = result.nodes.filter((n) => n.kind === 'import');
  5319. expect(imports.length).toBeGreaterThanOrEqual(2);
  5320. });
  5321. });
  5322. describe('Visibility modifiers', () => {
  5323. it('should extract private visibility', () => {
  5324. const code = `
  5325. class Service {
  5326. private val secret: String = "abc"
  5327. private def helper(): Unit = {}
  5328. }
  5329. `;
  5330. const result = extractFromSource('Service.scala', code);
  5331. const secretField = result.nodes.find((n) => n.name === 'secret');
  5332. expect(secretField?.visibility).toBe('private');
  5333. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  5334. expect(helperMethod?.visibility).toBe('private');
  5335. });
  5336. it('should extract protected visibility', () => {
  5337. const code = `
  5338. class Base {
  5339. protected def helperMethod(): Unit = {}
  5340. }
  5341. `;
  5342. const result = extractFromSource('Base.scala', code);
  5343. const method = result.nodes.find((n) => n.name === 'helperMethod');
  5344. expect(method?.visibility).toBe('protected');
  5345. });
  5346. it('should default to public visibility', () => {
  5347. const code = `
  5348. class Greeter {
  5349. def hello(): Unit = {}
  5350. }
  5351. `;
  5352. const result = extractFromSource('Greeter.scala', code);
  5353. const method = result.nodes.find((n) => n.name === 'hello');
  5354. expect(method?.visibility).toBe('public');
  5355. });
  5356. });
  5357. describe('Inheritance', () => {
  5358. it('should extract extends relationships', () => {
  5359. const code = `
  5360. class AdminUser extends User {
  5361. def adminAction(): Unit = {}
  5362. }
  5363. `;
  5364. const result = extractFromSource('AdminUser.scala', code);
  5365. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5366. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  5367. });
  5368. });
  5369. describe('Call extraction', () => {
  5370. it('should extract function call expressions', () => {
  5371. const code = `
  5372. def processData(): Unit = {
  5373. val result = computeResult()
  5374. println(result)
  5375. }
  5376. `;
  5377. const result = extractFromSource('processor.scala', code);
  5378. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  5379. expect(calls.length).toBeGreaterThan(0);
  5380. });
  5381. });
  5382. });
  5383. describe('Vue Extraction', () => {
  5384. it('should detect Vue files', () => {
  5385. expect(detectLanguage('App.vue')).toBe('vue');
  5386. expect(detectLanguage('components/Button.vue')).toBe('vue');
  5387. expect(isLanguageSupported('vue')).toBe(true);
  5388. });
  5389. it('should extract component node from a Vue SFC', () => {
  5390. const code = `<template>
  5391. <div>{{ message }}</div>
  5392. </template>
  5393. <script>
  5394. export default {
  5395. data() {
  5396. return { message: 'Hello' };
  5397. }
  5398. }
  5399. </script>
  5400. `;
  5401. const result = extractFromSource('HelloWorld.vue', code);
  5402. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5403. expect(componentNode).toBeDefined();
  5404. expect(componentNode?.name).toBe('HelloWorld');
  5405. expect(componentNode?.language).toBe('vue');
  5406. expect(componentNode?.isExported).toBe(true);
  5407. });
  5408. it('should extract functions from <script> block', () => {
  5409. const code = `<template>
  5410. <button @click="handleClick">Click</button>
  5411. </template>
  5412. <script>
  5413. function handleClick() {
  5414. console.log('clicked');
  5415. }
  5416. const count = 0;
  5417. </script>
  5418. `;
  5419. const result = extractFromSource('Button.vue', code);
  5420. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5421. expect(componentNode).toBeDefined();
  5422. expect(componentNode?.name).toBe('Button');
  5423. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  5424. expect(funcNode).toBeDefined();
  5425. expect(funcNode?.language).toBe('vue');
  5426. });
  5427. it('should extract from <script setup lang="ts"> block', () => {
  5428. const code = `<template>
  5429. <div>{{ count }}</div>
  5430. </template>
  5431. <script setup lang="ts">
  5432. import { ref } from 'vue';
  5433. const count = ref(0);
  5434. function increment(): void {
  5435. count.value++;
  5436. }
  5437. </script>
  5438. `;
  5439. const result = extractFromSource('Counter.vue', code);
  5440. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5441. expect(componentNode).toBeDefined();
  5442. expect(componentNode?.name).toBe('Counter');
  5443. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  5444. expect(funcNode).toBeDefined();
  5445. expect(funcNode?.language).toBe('vue');
  5446. // All nodes should be marked as vue language
  5447. for (const node of result.nodes) {
  5448. expect(node.language).toBe('vue');
  5449. }
  5450. });
  5451. it('should extract calls from top-level <script setup> initializers', () => {
  5452. const code = `<template>
  5453. <div>{{ token }}</div>
  5454. </template>
  5455. <script setup lang="ts">
  5456. import { getTokenMp } from './api/upload';
  5457. const token = getTokenMp();
  5458. </script>
  5459. `;
  5460. const result = extractFromSource('Issue425Setup.vue', code);
  5461. const call = result.unresolvedReferences.find(
  5462. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5463. );
  5464. expect(call).toBeDefined();
  5465. });
  5466. it('should extract calls from Vue Options API object methods', () => {
  5467. const code = `<template>
  5468. <button @click="save">Save</button>
  5469. </template>
  5470. <script>
  5471. import { getTokenMp } from './api/upload';
  5472. export default {
  5473. methods: {
  5474. save() {
  5475. return getTokenMp();
  5476. }
  5477. },
  5478. setup() {
  5479. return getTokenMp();
  5480. }
  5481. }
  5482. </script>
  5483. `;
  5484. const result = extractFromSource('Issue425Options.vue', code);
  5485. const calls = result.unresolvedReferences.filter(
  5486. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5487. );
  5488. expect(calls).toHaveLength(2);
  5489. });
  5490. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  5491. const code = `<template>
  5492. <div class="wrap">
  5493. <UserCard :user="u" />
  5494. <my-button>Click</my-button>
  5495. <Transition><span>x</span></Transition>
  5496. </div>
  5497. </template>
  5498. <script setup lang="ts">
  5499. import UserCard from './UserCard.vue';
  5500. import MyButton from './MyButton.vue';
  5501. </script>
  5502. `;
  5503. const result = extractFromSource('Host.vue', code);
  5504. const refs = result.unresolvedReferences
  5505. .filter((r) => r.referenceKind === 'references')
  5506. .map((r) => r.referenceName);
  5507. expect(refs).toContain('UserCard'); // PascalCase tag
  5508. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  5509. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  5510. expect(refs).not.toContain('Div'); // native HTML element skipped
  5511. expect(refs).not.toContain('Span');
  5512. });
  5513. it('should extract from both <script> and <script setup> blocks', () => {
  5514. const code = `<template>
  5515. <div>{{ msg }}</div>
  5516. </template>
  5517. <script>
  5518. export default {
  5519. name: 'DualScript'
  5520. }
  5521. </script>
  5522. <script setup>
  5523. const msg = 'hello';
  5524. function greet() {
  5525. return msg;
  5526. }
  5527. </script>
  5528. `;
  5529. const result = extractFromSource('DualScript.vue', code);
  5530. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5531. expect(componentNode).toBeDefined();
  5532. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  5533. expect(greetFunc).toBeDefined();
  5534. });
  5535. it('should create component node for template-only Vue file', () => {
  5536. const code = `<template>
  5537. <div>Static content</div>
  5538. </template>
  5539. `;
  5540. const result = extractFromSource('Static.vue', code);
  5541. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5542. expect(componentNode).toBeDefined();
  5543. expect(componentNode?.name).toBe('Static');
  5544. expect(componentNode?.language).toBe('vue');
  5545. // Only the component node should exist (no script nodes)
  5546. expect(result.nodes.length).toBe(1);
  5547. });
  5548. it('should create containment edges from component to script nodes', () => {
  5549. const code = `<template>
  5550. <div>{{ value }}</div>
  5551. </template>
  5552. <script setup lang="ts">
  5553. const value = 42;
  5554. </script>
  5555. `;
  5556. const result = extractFromSource('Contained.vue', code);
  5557. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5558. expect(componentNode).toBeDefined();
  5559. // Should have containment edges from component to child nodes
  5560. const containEdges = result.edges.filter(
  5561. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5562. );
  5563. expect(containEdges.length).toBeGreaterThan(0);
  5564. });
  5565. });
  5566. describe('Astro Extraction', () => {
  5567. it('should detect Astro files', () => {
  5568. expect(detectLanguage('src/pages/index.astro')).toBe('astro');
  5569. expect(detectLanguage('Layout.astro')).toBe('astro');
  5570. expect(isLanguageSupported('astro')).toBe(true);
  5571. });
  5572. it('should extract component node from an .astro file', () => {
  5573. const code = `---
  5574. const title = 'Hello';
  5575. ---
  5576. <h1>{title}</h1>
  5577. `;
  5578. const result = extractFromSource('Card.astro', code);
  5579. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5580. expect(componentNode).toBeDefined();
  5581. expect(componentNode?.name).toBe('Card');
  5582. expect(componentNode?.language).toBe('astro');
  5583. expect(componentNode?.isExported).toBe(true);
  5584. });
  5585. it('should extract frontmatter symbols with correct line numbers (#768)', () => {
  5586. const code = `---
  5587. import { formatDate } from '../utils/format';
  5588. function getIconNode(name: string): string {
  5589. return name;
  5590. }
  5591. const { title } = Astro.props;
  5592. ---
  5593. <span>{title}</span>
  5594. `;
  5595. const result = extractFromSource('navs.astro', code);
  5596. // The #768 repro: a function defined in frontmatter must be found
  5597. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getIconNode');
  5598. expect(fn).toBeDefined();
  5599. expect(fn?.language).toBe('astro');
  5600. expect(fn?.startLine).toBe(4);
  5601. const imp = result.nodes.find((n) => n.kind === 'import');
  5602. expect(imp).toBeDefined();
  5603. expect(imp?.startLine).toBe(2);
  5604. });
  5605. it('should extract exported getStaticPaths from frontmatter', () => {
  5606. const code = `---
  5607. export async function getStaticPaths() {
  5608. return [];
  5609. }
  5610. const { slug } = Astro.params;
  5611. ---
  5612. <p>{slug}</p>
  5613. `;
  5614. const result = extractFromSource('[slug].astro', code);
  5615. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getStaticPaths');
  5616. expect(fn).toBeDefined();
  5617. expect(fn?.isExported).toBe(true);
  5618. });
  5619. it('should extract calls from template expressions', () => {
  5620. const code = `---
  5621. import { formatDate } from '../utils/format';
  5622. const date = new Date();
  5623. ---
  5624. <time>{formatDate(date)}</time>
  5625. `;
  5626. const result = extractFromSource('Stamp.astro', code);
  5627. const call = result.unresolvedReferences.find(
  5628. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'formatDate' && ref.line === 5
  5629. );
  5630. expect(call).toBeDefined();
  5631. });
  5632. it('should extract calls from a multiline expression opening line', () => {
  5633. const code = `---
  5634. const posts = [];
  5635. ---
  5636. <ul>
  5637. {posts.map((post) => (
  5638. <li>{render(post)}</li>
  5639. ))}
  5640. </ul>
  5641. `;
  5642. const result = extractFromSource('List.astro', code);
  5643. const mapCall = result.unresolvedReferences.find(
  5644. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'posts.map'
  5645. );
  5646. expect(mapCall).toBeDefined();
  5647. const innerCall = result.unresolvedReferences.find(
  5648. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'render'
  5649. );
  5650. expect(innerCall).toBeDefined();
  5651. });
  5652. it('should extract PascalCase component usages from the template', () => {
  5653. const code = `---
  5654. import Layout from '../layouts/Layout.astro';
  5655. import PostCard from '../components/PostCard.astro';
  5656. ---
  5657. <Layout title="Home">
  5658. <PostCard />
  5659. <Fragment slot="head" />
  5660. <div class="plain-html" />
  5661. </Layout>
  5662. `;
  5663. const result = extractFromSource('index.astro', code);
  5664. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  5665. const names = refs.map((r) => r.referenceName);
  5666. expect(names).toContain('Layout');
  5667. expect(names).toContain('PostCard');
  5668. // Astro built-ins and lowercase HTML are not component references
  5669. expect(names).not.toContain('Fragment');
  5670. expect(names).not.toContain('div');
  5671. });
  5672. it('should not extract template patterns from frontmatter, script, or style content', () => {
  5673. const code = `---
  5674. // <FakeComponent /> inside frontmatter comment
  5675. const x = { y: maybeCall(1) };
  5676. ---
  5677. <div>real</div>
  5678. <script>
  5679. const z = { w: scriptCall(2) };
  5680. </script>
  5681. <style>
  5682. .a { color: red; }
  5683. </style>
  5684. `;
  5685. const result = extractFromSource('Guard.astro', code);
  5686. const templateRefs = result.unresolvedReferences.filter(
  5687. (r) => r.referenceKind === 'references' && r.referenceName === 'FakeComponent'
  5688. );
  5689. expect(templateRefs).toHaveLength(0);
  5690. // maybeCall/scriptCall come from the delegated TS extraction (once),
  5691. // not double-counted by the template scanner
  5692. const maybeCalls = result.unresolvedReferences.filter(
  5693. (r) => r.referenceName === 'maybeCall' && r.referenceKind === 'calls'
  5694. );
  5695. expect(maybeCalls.length).toBeLessThanOrEqual(1);
  5696. });
  5697. it('should extract <script> block symbols with correct line numbers', () => {
  5698. const code = `---
  5699. const a = 1;
  5700. ---
  5701. <div>hi</div>
  5702. <script>
  5703. function trackView(page: string) {
  5704. console.log(page);
  5705. }
  5706. </script>
  5707. `;
  5708. const result = extractFromSource('Tracker.astro', code);
  5709. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'trackView');
  5710. expect(fn).toBeDefined();
  5711. expect(fn?.startLine).toBe(6);
  5712. expect(fn?.language).toBe('astro');
  5713. });
  5714. it('should create component node for a frontmatter-less template-only file', () => {
  5715. const code = `<div>Static content</div>
  5716. `;
  5717. const result = extractFromSource('Static.astro', code);
  5718. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5719. expect(componentNode).toBeDefined();
  5720. expect(componentNode?.name).toBe('Static');
  5721. expect(componentNode?.language).toBe('astro');
  5722. });
  5723. it('should treat an unclosed frontmatter fence as no frontmatter', () => {
  5724. const code = `---
  5725. const broken = true;
  5726. <div>never closed</div>
  5727. `;
  5728. const result = extractFromSource('Broken.astro', code);
  5729. // No TS delegation happened (the fence never closes), but the component
  5730. // node still exists and nothing throws.
  5731. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5732. expect(componentNode).toBeDefined();
  5733. expect(result.nodes.find((n) => n.name === 'broken')).toBeUndefined();
  5734. });
  5735. it('should create containment edges from component to frontmatter nodes', () => {
  5736. const code = `---
  5737. const value = 42;
  5738. ---
  5739. <div>{value}</div>
  5740. `;
  5741. const result = extractFromSource('Contained.astro', code);
  5742. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5743. expect(componentNode).toBeDefined();
  5744. const containEdges = result.edges.filter(
  5745. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5746. );
  5747. expect(containEdges.length).toBeGreaterThan(0);
  5748. });
  5749. });
  5750. describe('Instantiates + Decorates edge extraction', () => {
  5751. it('emits an instantiates ref for `new Foo()`', () => {
  5752. const code = `
  5753. class Foo {}
  5754. function bootstrap() { return new Foo(); }
  5755. `;
  5756. const result = extractFromSource('app.ts', code);
  5757. const ref = result.unresolvedReferences.find(
  5758. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  5759. );
  5760. expect(ref).toBeDefined();
  5761. });
  5762. it('strips type-argument suffix from generic constructors', () => {
  5763. const code = `
  5764. class Container<T> { constructor(_: T) {} }
  5765. function go() { return new Container<string>('x'); }
  5766. `;
  5767. const result = extractFromSource('app.ts', code);
  5768. const ref = result.unresolvedReferences.find(
  5769. (r) => r.referenceKind === 'instantiates'
  5770. );
  5771. expect(ref).toBeDefined();
  5772. // Container<string> must be normalised to "Container" — otherwise
  5773. // resolution can never match the class node.
  5774. expect(ref!.referenceName).toBe('Container');
  5775. });
  5776. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  5777. const code = `
  5778. const ns = { Foo: class {} };
  5779. function go() { return new ns.Foo(); }
  5780. `;
  5781. const result = extractFromSource('app.ts', code);
  5782. const ref = result.unresolvedReferences.find(
  5783. (r) => r.referenceKind === 'instantiates'
  5784. );
  5785. // We can't always resolve which Foo, but the name should be the
  5786. // simple identifier so name-matching has a chance.
  5787. expect(ref?.referenceName).toBe('Foo');
  5788. });
  5789. it('emits a decorates ref for `@Foo class X {}`', () => {
  5790. const code = `
  5791. function Foo(_arg: string) { return (cls: any) => cls; }
  5792. @Foo('x')
  5793. class X {}
  5794. `;
  5795. const result = extractFromSource('app.ts', code);
  5796. const decorClass = result.unresolvedReferences.find(
  5797. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  5798. );
  5799. expect(decorClass).toBeDefined();
  5800. });
  5801. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  5802. // Regression: the sibling-walk must stop at the first non-
  5803. // decorator separator. `@A class Foo {} @B class Bar {}` must
  5804. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  5805. // `decorates(Bar, A)`.
  5806. const code = `
  5807. function A(cls: any) { return cls; }
  5808. function B(cls: any) { return cls; }
  5809. @A
  5810. class Foo {}
  5811. @B
  5812. class Bar {}
  5813. `;
  5814. const result = extractFromSource('app.ts', code);
  5815. const decoratesEdges = result.unresolvedReferences.filter(
  5816. (r) => r.referenceKind === 'decorates'
  5817. );
  5818. // Exactly one decorates ref per decorated class, no cross-attribution.
  5819. const fromBar = decoratesEdges.filter((r) =>
  5820. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  5821. );
  5822. expect(fromBar.length).toBe(1);
  5823. expect(fromBar[0]!.referenceName).toBe('B');
  5824. });
  5825. it('emits a decorates ref for `@Foo method() {}`', () => {
  5826. const code = `
  5827. function Get(p: string) { return (t: any, k: string) => t; }
  5828. class Svc {
  5829. @Get('/x') method() { return 1; }
  5830. }
  5831. `;
  5832. const result = extractFromSource('app.ts', code);
  5833. const decorMethod = result.unresolvedReferences.find(
  5834. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  5835. );
  5836. expect(decorMethod).toBeDefined();
  5837. // The decorated symbol must be `method`, not the constructor or class.
  5838. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  5839. expect(decoratedNode?.name).toBe('method');
  5840. });
  5841. });
  5842. // =============================================================================
  5843. // Lua
  5844. // =============================================================================
  5845. describe('Lua Extraction', () => {
  5846. describe('Language detection', () => {
  5847. it('should detect Lua files', () => {
  5848. expect(detectLanguage('init.lua')).toBe('lua');
  5849. expect(detectLanguage('src/util.lua')).toBe('lua');
  5850. });
  5851. it('should report Lua as supported', () => {
  5852. expect(isLanguageSupported('lua')).toBe(true);
  5853. expect(getSupportedLanguages()).toContain('lua');
  5854. });
  5855. });
  5856. describe('Function extraction', () => {
  5857. it('should extract global and local functions', () => {
  5858. const code = `
  5859. function configure(opts) return opts end
  5860. local function helper(x) return x * 2 end
  5861. `;
  5862. const result = extractFromSource('init.lua', code);
  5863. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5864. expect(funcs).toContain('configure');
  5865. expect(funcs).toContain('helper');
  5866. const configure = result.nodes.find((n) => n.name === 'configure');
  5867. expect(configure?.language).toBe('lua');
  5868. expect(configure?.signature).toBe('(opts)');
  5869. });
  5870. it('should split table/method functions into a receiver and method name', () => {
  5871. const code = `
  5872. function M.connect(host, port) return host end
  5873. function M:send(data) return self end
  5874. `;
  5875. const result = extractFromSource('init.lua', code);
  5876. const methods = result.nodes.filter((n) => n.kind === 'method');
  5877. const connect = methods.find((m) => m.name === 'connect');
  5878. expect(connect?.qualifiedName).toBe('M::connect');
  5879. const send = methods.find((m) => m.name === 'send');
  5880. expect(send?.qualifiedName).toBe('M::send');
  5881. });
  5882. });
  5883. describe('Variable extraction', () => {
  5884. it('should extract local variable declarations', () => {
  5885. const code = `
  5886. local M = {}
  5887. local count = 0
  5888. `;
  5889. const result = extractFromSource('mod.lua', code);
  5890. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5891. expect(vars).toContain('M');
  5892. expect(vars).toContain('count');
  5893. });
  5894. });
  5895. describe('Import extraction (require)', () => {
  5896. it('should extract require() in local declarations and bare calls', () => {
  5897. const code = `
  5898. local socket = require("socket")
  5899. local http = require "resty.http"
  5900. require("side.effect")
  5901. `;
  5902. const result = extractFromSource('net.lua', code);
  5903. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5904. expect(imports).toContain('socket');
  5905. expect(imports).toContain('resty.http');
  5906. expect(imports).toContain('side.effect');
  5907. const ref = result.unresolvedReferences.find(
  5908. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  5909. );
  5910. expect(ref).toBeDefined();
  5911. });
  5912. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  5913. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  5914. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  5915. // by extracting several sources in sequence and asserting the LAST still works.
  5916. it('should keep extracting require across many sequential parses', () => {
  5917. let last;
  5918. for (let i = 0; i < 8; i++) {
  5919. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  5920. }
  5921. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5922. expect(imports).toContain('module.7');
  5923. });
  5924. });
  5925. describe('Call extraction', () => {
  5926. it('should record intra-file calls as resolvable references', () => {
  5927. const code = `
  5928. local function helper(x) return x end
  5929. local function run(y) return helper(y) end
  5930. `;
  5931. const result = extractFromSource('calls.lua', code);
  5932. const call = result.unresolvedReferences.find(
  5933. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  5934. );
  5935. expect(call).toBeDefined();
  5936. });
  5937. });
  5938. });
  5939. // =============================================================================
  5940. // Luau (typed superset of Lua — https://luau.org)
  5941. // =============================================================================
  5942. describe('Luau Extraction', () => {
  5943. describe('Language detection', () => {
  5944. it('should detect Luau files', () => {
  5945. expect(detectLanguage('init.luau')).toBe('luau');
  5946. expect(detectLanguage('src/Client.luau')).toBe('luau');
  5947. });
  5948. it('should report Luau as supported', () => {
  5949. expect(isLanguageSupported('luau')).toBe(true);
  5950. expect(getSupportedLanguages()).toContain('luau');
  5951. });
  5952. });
  5953. describe('Type aliases', () => {
  5954. it('should extract `type` and `export type` definitions', () => {
  5955. const code = `
  5956. export type Vector = { x: number, y: number }
  5957. type Handler = (msg: string) -> boolean
  5958. `;
  5959. const result = extractFromSource('types.luau', code);
  5960. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5961. const vector = aliases.find((a) => a.name === 'Vector');
  5962. expect(vector).toBeDefined();
  5963. expect(vector?.isExported).toBe(true);
  5964. const handler = aliases.find((a) => a.name === 'Handler');
  5965. expect(handler).toBeDefined();
  5966. expect(handler?.isExported).toBe(false);
  5967. });
  5968. });
  5969. describe('Typed functions and methods', () => {
  5970. it('should capture typed signatures and split methods by receiver', () => {
  5971. const code = `
  5972. function configure(opts: { debug: boolean }): boolean
  5973. return opts.debug
  5974. end
  5975. function Client:fetch(path: string): Response
  5976. return path
  5977. end
  5978. `;
  5979. const result = extractFromSource('client.luau', code);
  5980. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  5981. expect(configure?.language).toBe('luau');
  5982. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  5983. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  5984. expect(fetch?.qualifiedName).toBe('Client::fetch');
  5985. });
  5986. });
  5987. describe('Imports and variables', () => {
  5988. it('should extract string and Roblox instance-path require imports', () => {
  5989. const code = `
  5990. local http = require("http")
  5991. local Signal = require(script.Parent.Signal)
  5992. local count = 0
  5993. `;
  5994. const result = extractFromSource('mod.luau', code);
  5995. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  5996. expect(imports).toContain('http'); // string require
  5997. expect(imports).toContain('Signal'); // Roblox instance-path require
  5998. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  5999. expect(vars).toContain('count');
  6000. });
  6001. });
  6002. });
  6003. // =============================================================================
  6004. // Objective-C
  6005. // =============================================================================
  6006. describe('Objective-C Extraction', () => {
  6007. const sample = `
  6008. #import <Foundation/Foundation.h>
  6009. #import "MyClass.h"
  6010. @interface MyClass : NSObject <NSCopying>
  6011. @property (nonatomic, copy) NSString *name;
  6012. - (void)greet;
  6013. - (void)doThing:(id)x with:(id)y;
  6014. + (instancetype)shared;
  6015. @end
  6016. @implementation MyClass
  6017. - (void)greet {
  6018. NSLog(@"Hello");
  6019. [self doWork];
  6020. }
  6021. - (void)doThing:(id)x with:(id)y {
  6022. [self notify:x];
  6023. }
  6024. + (instancetype)shared {
  6025. return [[MyClass alloc] init];
  6026. }
  6027. @end
  6028. void helperFunction(int count) {
  6029. MyClass *obj = [MyClass shared];
  6030. [obj greet];
  6031. }
  6032. `;
  6033. it('should extract classes, methods, functions, and imports', () => {
  6034. const result = extractFromSource('App.m', sample);
  6035. const classes = result.nodes.filter((n) => n.kind === 'class');
  6036. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  6037. const methods = result.nodes.filter((n) => n.kind === 'method');
  6038. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  6039. const shared = methods.find((m) => m.name === 'shared');
  6040. expect(shared?.isStatic).toBe(true);
  6041. const properties = result.nodes.filter((n) => n.kind === 'property');
  6042. expect(properties.some((p) => p.name === 'name')).toBe(true);
  6043. const functions = result.nodes.filter((n) => n.kind === 'function');
  6044. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  6045. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6046. expect(imports).toContain('Foundation/Foundation.h');
  6047. expect(imports).toContain('MyClass.h');
  6048. });
  6049. it('should record inheritance and protocol conformance', () => {
  6050. const result = extractFromSource('App.m', sample);
  6051. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  6052. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  6053. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  6054. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  6055. });
  6056. it('should record message sends and C calls', () => {
  6057. const result = extractFromSource('App.m', sample);
  6058. const calls = result.unresolvedReferences
  6059. .filter((r) => r.referenceKind === 'calls')
  6060. .map((r) => r.referenceName);
  6061. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  6062. });
  6063. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  6064. // Regression for the gap discovered post-#165: message_expression's
  6065. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  6066. // so calls never resolved to multi-part method definitions like
  6067. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  6068. // must match the method-definition name with full keywords + trailing colons.
  6069. const code = `
  6070. @implementation Caller
  6071. - (void)demo {
  6072. NSMutableDictionary *d = [NSMutableDictionary new];
  6073. [d setObject:@"v" forKey:@"k"];
  6074. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  6075. [self touchesBegan:nil withEvent:nil];
  6076. }
  6077. @end
  6078. `;
  6079. const result = extractFromSource('Caller.m', code);
  6080. const calls = result.unresolvedReferences
  6081. .filter((r) => r.referenceKind === 'calls')
  6082. .map((r) => r.referenceName);
  6083. expect(calls).toEqual(
  6084. expect.arrayContaining([
  6085. 'd.setObject:forKey:',
  6086. 'd.setObject:forKey:withRetry:',
  6087. 'touchesBegan:withEvent:',
  6088. ])
  6089. );
  6090. });
  6091. it('should not classify pure C headers with @end in comments as objc', () => {
  6092. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  6093. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  6094. });
  6095. it('should extract protocol declarations', () => {
  6096. const code = `
  6097. @protocol DataSource <NSObject>
  6098. - (NSInteger)numberOfItems;
  6099. @end
  6100. `;
  6101. const result = extractFromSource('DataSource.h', code);
  6102. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  6103. expect(protocol).toBeDefined();
  6104. });
  6105. it('should report Objective-C as supported', () => {
  6106. expect(isLanguageSupported('objc')).toBe(true);
  6107. expect(getSupportedLanguages()).toContain('objc');
  6108. });
  6109. });
  6110. describe('Regression: issue-specific extraction fixes', () => {
  6111. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  6112. const code = `
  6113. define(['dep'], function (dep) {
  6114. function innerHelper(x) { return x + 1; }
  6115. function compute(y) { return innerHelper(y); }
  6116. return { compute: compute };
  6117. });
  6118. `;
  6119. const result = extractFromSource('amd-module.js', code);
  6120. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6121. expect(fns).toContain('innerHelper');
  6122. expect(fns).toContain('compute');
  6123. });
  6124. it('attaches Go methods on generic receivers to their type (#583)', () => {
  6125. const code = `
  6126. package main
  6127. type Stack[T any] struct { items []T }
  6128. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  6129. func (s Stack[T]) Len() int { return len(s.items) }
  6130. `;
  6131. const result = extractFromSource('stack.go', code);
  6132. const methods = result.nodes.filter((n) => n.kind === 'method');
  6133. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  6134. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  6135. });
  6136. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  6137. expect(isSourceFile('mod.mts')).toBe(true);
  6138. expect(isSourceFile('mod.cts')).toBe(true);
  6139. expect(isSourceFile('service.xsjs')).toBe(true);
  6140. expect(isSourceFile('lib.xsjslib')).toBe(true);
  6141. expect(detectLanguage('mod.mts')).toBe('typescript');
  6142. expect(detectLanguage('service.xsjs')).toBe('javascript');
  6143. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  6144. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  6145. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  6146. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  6147. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  6148. });
  6149. });
  6150. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  6151. // An import IS a dependency, but extraction only emits references for calls,
  6152. // instantiations, type annotations, and inheritance — so a symbol imported and
  6153. // then merely re-exported, placed in a registry array, passed as an argument,
  6154. // or used in JSX produced no cross-file edge, leaving the providing file with a
  6155. // false "0 dependents". These tests pin the import/re-export binding linking.
  6156. it('emits an imports reference per named, aliased, and default import binding', () => {
  6157. const code = `
  6158. import { widget, helper as h } from './foo';
  6159. import Thing from './thing';
  6160. import * as NS from './ns';
  6161. export const registry = [widget];
  6162. `;
  6163. const result = extractFromSource('bar.ts', code);
  6164. const names = result.unresolvedReferences
  6165. .filter((r) => r.referenceKind === 'imports')
  6166. .map((r) => r.referenceName);
  6167. expect(names).toContain('widget'); // named import → local name
  6168. expect(names).toContain('h'); // aliased import → local alias
  6169. expect(names).toContain('Thing'); // default import
  6170. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  6171. });
  6172. it('emits an imports reference per re-exported binding', () => {
  6173. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  6174. const names = result.unresolvedReferences
  6175. .filter((r) => r.referenceKind === 'imports')
  6176. .map((r) => r.referenceName);
  6177. // Re-export links the SOURCE-side name, not the local alias.
  6178. expect(names).toContain('alpha');
  6179. expect(names).toContain('beta');
  6180. });
  6181. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  6182. const dir = createTempDir();
  6183. try {
  6184. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6185. fs.writeFileSync(
  6186. path.join(dir, 'src', 'foo.ts'),
  6187. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  6188. );
  6189. // bar uses widget ONLY in an array and re-exports helper — neither is
  6190. // called/typed, so before import-linking bar had no edge to foo at all.
  6191. fs.writeFileSync(
  6192. path.join(dir, 'src', 'bar.ts'),
  6193. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  6194. );
  6195. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6196. await cg.indexAll();
  6197. cg.resolveReferences();
  6198. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6199. cg.destroy();
  6200. } finally {
  6201. cleanupTempDir(dir);
  6202. }
  6203. });
  6204. it('a namespace import touched only via a value-member read still links the module file', async () => {
  6205. const dir = createTempDir();
  6206. try {
  6207. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6208. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  6209. // `foo` is imported as a namespace and used ONLY via a value-member read
  6210. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  6211. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  6212. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  6213. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6214. await cg.indexAll();
  6215. cg.resolveReferences();
  6216. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6217. cg.destroy();
  6218. } finally {
  6219. cleanupTempDir(dir);
  6220. }
  6221. });
  6222. });
  6223. describe('Python import dependency linking (blast-radius recall)', () => {
  6224. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  6225. // name brought in with `from module import X` and then merely stored, used as
  6226. // a decorator/argument, or re-exported through an `__init__.py` produced no
  6227. // cross-file edge — the providing module showed a false "0 dependents".
  6228. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  6229. const code = [
  6230. 'from foo import helper, widget',
  6231. 'from foo import Thing as T',
  6232. 'from . import sibling',
  6233. 'from bar import *',
  6234. ].join('\n');
  6235. const names = extractFromSource('mod.py', code)
  6236. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  6237. .map((r) => r.referenceName);
  6238. expect(names).toContain('helper');
  6239. expect(names).toContain('widget'); // value import
  6240. expect(names).toContain('T'); // aliased import → local name
  6241. expect(names).toContain('sibling'); // `from . import <name>`
  6242. expect(names).not.toContain('*'); // wildcard import has no names
  6243. });
  6244. it('a Python value imported but never called still makes the importer a dependent', async () => {
  6245. const dir = createTempDir();
  6246. try {
  6247. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6248. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  6249. // bar imports widget+helper but only stores widget in a list — nothing is
  6250. // called, so before import-linking bar had no edge to foo.
  6251. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  6252. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6253. await cg.indexAll();
  6254. cg.resolveReferences();
  6255. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  6256. cg.destroy();
  6257. } finally {
  6258. cleanupTempDir(dir);
  6259. }
  6260. });
  6261. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  6262. const dir = createTempDir();
  6263. try {
  6264. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6265. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6266. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  6267. // certs is an imported MODULE (a file), and certs.where() is a qualified
  6268. // call through it — the receiver isn't a symbol, so plain name-matching
  6269. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  6270. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  6271. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6272. await cg.indexAll();
  6273. cg.resolveReferences();
  6274. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6275. cg.destroy();
  6276. } finally {
  6277. cleanupTempDir(dir);
  6278. }
  6279. });
  6280. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  6281. const dir = createTempDir();
  6282. try {
  6283. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6284. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6285. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  6286. // member resolution can't find it — the module-import backstop must still
  6287. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  6288. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  6289. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  6290. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6291. await cg.indexAll();
  6292. cg.resolveReferences();
  6293. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6294. cg.destroy();
  6295. } finally {
  6296. cleanupTempDir(dir);
  6297. }
  6298. });
  6299. });
  6300. describe('Go cross-package composite literals (blast-radius recall)', () => {
  6301. // Go function calls and type references across packages already resolved, but
  6302. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  6303. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  6304. // (gin's render/binding implementations) showed 0 dependents.
  6305. it('links a cross-package struct composite literal to the defining package', async () => {
  6306. const dir = createTempDir();
  6307. try {
  6308. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6309. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6310. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  6311. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  6312. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6313. await cg.indexAll();
  6314. cg.resolveReferences();
  6315. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  6316. cg.destroy();
  6317. } finally {
  6318. cleanupTempDir(dir);
  6319. }
  6320. });
  6321. it('links a composite literal in a package-level var registry', async () => {
  6322. const dir = createTempDir();
  6323. try {
  6324. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6325. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6326. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  6327. // The implementation is registered only in a top-level `var registry = {...}`
  6328. // map literal — the body walker doesn't cover top-level declarations, so this
  6329. // exercises the var-initializer walking added for Go.
  6330. 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`);
  6331. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6332. await cg.indexAll();
  6333. cg.resolveReferences();
  6334. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  6335. cg.destroy();
  6336. } finally {
  6337. cleanupTempDir(dir);
  6338. }
  6339. });
  6340. it('attributes a call inside a top-level closure (cobra RunE) to the var, not the file (#693)', async () => {
  6341. const dir = createTempDir();
  6342. try {
  6343. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6344. // Wire is called ONLY from the anonymous RunE closure inside a top-level
  6345. // `var rootCmd = &Cmd{...}` — previously the call leaked to the file node,
  6346. // so `callers(Wire)` surfaced a file (or read as "no caller"). It must now
  6347. // attribute to the enclosing var.
  6348. fs.writeFileSync(path.join(dir, 'factory.go'), `package main\n\nfunc Wire() error { return nil }\n`);
  6349. fs.writeFileSync(
  6350. path.join(dir, 'root.go'),
  6351. `package main\n\ntype Cmd struct{ RunE func() error }\n\nvar rootCmd = &Cmd{\n\tRunE: func() error { return Wire() },\n}\n`
  6352. );
  6353. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6354. await cg.indexAll();
  6355. cg.resolveReferences();
  6356. const wire = cg.getNodesByName('Wire').find((n) => n.kind === 'function');
  6357. expect(wire).toBeDefined();
  6358. const callers = cg.getCallers(wire!.id).map((c) => c.node);
  6359. expect(callers.some((n) => n.kind === 'variable' && n.name === 'rootCmd')).toBe(true);
  6360. expect(callers.some((n) => n.kind === 'file')).toBe(false);
  6361. cg.destroy();
  6362. } finally {
  6363. cleanupTempDir(dir);
  6364. }
  6365. });
  6366. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  6367. const dir = createTempDir();
  6368. try {
  6369. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6370. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  6371. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  6372. // `(*Wrapped)` — without normalization it dropped on the floor.
  6373. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  6374. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6375. await cg.indexAll();
  6376. cg.resolveReferences();
  6377. expect(cg.getFileDependents('types.go')).toContain('use.go');
  6378. cg.destroy();
  6379. } finally {
  6380. cleanupTempDir(dir);
  6381. }
  6382. });
  6383. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  6384. const dir = createTempDir();
  6385. try {
  6386. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6387. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  6388. 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`);
  6389. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  6390. // reached ONLY through the interface (API.Marshal). Without implicit
  6391. // interface satisfaction + dispatch, json.go shows 0 dependents.
  6392. 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`);
  6393. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6394. await cg.indexAll();
  6395. cg.resolveReferences();
  6396. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  6397. cg.destroy();
  6398. } finally {
  6399. cleanupTempDir(dir);
  6400. }
  6401. });
  6402. });
  6403. describe('C# records (blast-radius recall)', () => {
  6404. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  6405. // but `record` / `record struct` declarations weren't extracted as types — so
  6406. // every reference, generic-type-argument, and `new` of a record dropped on the
  6407. // floor and the defining file showed 0 dependents. (#237)
  6408. it('extracts a record as a graph node (record class + record struct)', () => {
  6409. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  6410. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6411. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6412. });
  6413. it('resolves references / instantiations of a record across files', async () => {
  6414. const dir = createTempDir();
  6415. try {
  6416. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  6417. // Box is used as a generic type argument and instantiated — both require
  6418. // Box to be a node to resolve.
  6419. fs.writeFileSync(
  6420. path.join(dir, 'use.cs'),
  6421. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  6422. );
  6423. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  6424. await cg.indexAll();
  6425. cg.resolveReferences();
  6426. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  6427. cg.destroy();
  6428. } finally {
  6429. cleanupTempDir(dir);
  6430. }
  6431. });
  6432. });
  6433. describe('Rust cross-module recall', () => {
  6434. function rustProject(files: Record<string, string>): string {
  6435. const dir = createTempDir();
  6436. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  6437. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6438. for (const [rel, content] of Object.entries(files)) {
  6439. const full = path.join(dir, 'src', rel);
  6440. fs.mkdirSync(path.dirname(full), { recursive: true });
  6441. fs.writeFileSync(full, content);
  6442. }
  6443. return dir;
  6444. }
  6445. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  6446. const dir = rustProject({
  6447. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6448. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  6449. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  6450. });
  6451. try {
  6452. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6453. await cg.indexAll();
  6454. cg.resolveReferences();
  6455. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6456. cg.destroy();
  6457. } finally { cleanupTempDir(dir); }
  6458. });
  6459. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  6460. const dir = rustProject({
  6461. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6462. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  6463. // Mine implements Render structurally; reached via &dyn Render dispatch.
  6464. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  6465. });
  6466. try {
  6467. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6468. await cg.indexAll();
  6469. cg.resolveReferences();
  6470. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  6471. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6472. cg.destroy();
  6473. } finally { cleanupTempDir(dir); }
  6474. });
  6475. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  6476. const dir = rustProject({
  6477. 'lib.rs': 'pub mod api;\n',
  6478. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  6479. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  6480. });
  6481. try {
  6482. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6483. await cg.indexAll();
  6484. cg.resolveReferences();
  6485. // The re-export hub depends on the module it re-exports from.
  6486. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  6487. cg.destroy();
  6488. } finally { cleanupTempDir(dir); }
  6489. });
  6490. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  6491. const dir = rustProject({
  6492. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  6493. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  6494. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  6495. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  6496. // send this re-export to fast.rs specifically, not name-match either.
  6497. 'hub.rs': 'pub use crate::fast::read;\n',
  6498. });
  6499. try {
  6500. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6501. await cg.indexAll();
  6502. cg.resolveReferences();
  6503. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  6504. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  6505. cg.destroy();
  6506. } finally { cleanupTempDir(dir); }
  6507. });
  6508. });
  6509. describe('Java annotations (blast-radius recall)', () => {
  6510. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  6511. const dir = createTempDir();
  6512. try {
  6513. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  6514. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  6515. // live inside a `modifiers` node on the class/field/method) must extract.
  6516. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  6517. fs.writeFileSync(
  6518. path.join(dir, 'p', 'User.java'),
  6519. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  6520. );
  6521. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  6522. await cg.indexAll();
  6523. cg.resolveReferences();
  6524. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  6525. cg.destroy();
  6526. } finally { cleanupTempDir(dir); }
  6527. });
  6528. });
  6529. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  6530. it('links a @propertyWrapper usage to the wrapper type', async () => {
  6531. const dir = createTempDir();
  6532. try {
  6533. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  6534. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  6535. // `@Argument` is a Swift attribute on a stored property — it lives in the
  6536. // property's `modifiers` and Swift doesn't extract instance properties as
  6537. // their own nodes, so without the fix the wrapper type has no users.
  6538. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  6539. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  6540. await cg.indexAll();
  6541. cg.resolveReferences();
  6542. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  6543. cg.destroy();
  6544. } finally { cleanupTempDir(dir); }
  6545. });
  6546. });
  6547. describe('R Extraction', () => {
  6548. describe('Language detection', () => {
  6549. it('should detect R files (both extension cases)', () => {
  6550. expect(detectLanguage('analysis.R')).toBe('r');
  6551. expect(detectLanguage('scripts/clean.r')).toBe('r');
  6552. });
  6553. it('should report R as supported', () => {
  6554. expect(isLanguageSupported('r')).toBe(true);
  6555. expect(getSupportedLanguages()).toContain('r');
  6556. });
  6557. });
  6558. describe('Function extraction', () => {
  6559. it('extracts every assignment form, lambdas, and nested functions', () => {
  6560. const code = `
  6561. clean_data <- function(df, threshold = 0.5) {
  6562. helper <- function(d) scale(d)
  6563. helper(df)
  6564. }
  6565. normalize = function(v) (v - mean(v)) / sd(v)
  6566. double_it <- \\(x) x * 2
  6567. `;
  6568. const result = extractFromSource('analysis.R', code);
  6569. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6570. expect(funcs).toContain('clean_data');
  6571. expect(funcs).toContain('normalize');
  6572. expect(funcs).toContain('double_it');
  6573. expect(funcs).toContain('helper'); // nested, inside clean_data's scope
  6574. const cleanData = result.nodes.find((n) => n.name === 'clean_data');
  6575. expect(cleanData?.language).toBe('r');
  6576. expect(cleanData?.signature).toBe('(df, threshold = 0.5)');
  6577. });
  6578. it('attributes body calls to the enclosing function', () => {
  6579. const code = `
  6580. prep <- function(d) scale(d)
  6581. fit_model <- function(data) {
  6582. lm(y ~ x, data = prep(data))
  6583. }
  6584. `;
  6585. const result = extractFromSource('models.R', code);
  6586. const prepCall = result.unresolvedReferences.find(
  6587. (r) => r.referenceName === 'prep' && r.referenceKind === 'calls'
  6588. );
  6589. expect(prepCall).toBeDefined();
  6590. const fitModel = result.nodes.find((n) => n.name === 'fit_model');
  6591. expect(prepCall?.fromNodeId).toBe(fitModel?.id);
  6592. });
  6593. });
  6594. describe('Imports', () => {
  6595. it('extracts library/require/source as imports, not calls', () => {
  6596. const code = `
  6597. library(dplyr)
  6598. require(stats)
  6599. requireNamespace("jsonlite")
  6600. source("helpers.R")
  6601. `;
  6602. const result = extractFromSource('main.R', code);
  6603. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6604. expect(imports).toContain('dplyr');
  6605. expect(imports).toContain('stats');
  6606. expect(imports).toContain('jsonlite');
  6607. expect(imports).toContain('helpers.R');
  6608. // Claimed by the hook — no call references to the import machinery.
  6609. const libCalls = result.unresolvedReferences.filter(
  6610. (r) => r.referenceKind === 'calls' && (r.referenceName === 'library' || r.referenceName === 'source')
  6611. );
  6612. expect(libCalls).toHaveLength(0);
  6613. });
  6614. });
  6615. describe('Variables and constants', () => {
  6616. it('extracts top-level assignments; ALL_CAPS as constants; right-assign too', () => {
  6617. const code = `
  6618. ALPHA <- 0.05
  6619. max_iter = 100
  6620. compute_stats(df) -> stats_result
  6621. inner <- function() {
  6622. local_var <- 1
  6623. }
  6624. `;
  6625. const result = extractFromSource('config.R', code);
  6626. const constant = result.nodes.find((n) => n.name === 'ALPHA');
  6627. expect(constant?.kind).toBe('constant');
  6628. const variable = result.nodes.find((n) => n.name === 'max_iter');
  6629. expect(variable?.kind).toBe('variable');
  6630. const rightAssigned = result.nodes.find((n) => n.name === 'stats_result');
  6631. expect(rightAssigned?.kind).toBe('variable');
  6632. // Locals inside functions are deliberately NOT extracted.
  6633. expect(result.nodes.find((n) => n.name === 'local_var')).toBeUndefined();
  6634. });
  6635. });
  6636. describe('Classes', () => {
  6637. it('extracts S4/R5/R6 class calls as classes with their list methods', () => {
  6638. const code = `
  6639. setClass("Patient", representation(id = "character"))
  6640. Account <- setRefClass("Account",
  6641. fields = list(balance = "numeric"),
  6642. methods = list(deposit = function(x) { balance <<- balance + x })
  6643. )
  6644. Stack <- R6Class("Stack",
  6645. public = list(push = function(v) invisible(v))
  6646. )
  6647. setGeneric("describe", function(obj) standardGeneric("describe"))
  6648. setMethod("describe", "Patient", function(obj) paste(obj@id))
  6649. `;
  6650. const result = extractFromSource('classes.R', code);
  6651. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  6652. expect(classes).toContain('Patient');
  6653. expect(classes).toContain('Account');
  6654. expect(classes).toContain('Stack');
  6655. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  6656. expect(methods).toContain('deposit');
  6657. expect(methods).toContain('push');
  6658. // setGeneric/setMethod produce functions named by their string argument.
  6659. const describes = result.nodes.filter((n) => n.name === 'describe' && n.kind === 'function');
  6660. expect(describes.length).toBeGreaterThanOrEqual(2);
  6661. // The class-assignment idiom must not ALSO produce a variable node.
  6662. expect(result.nodes.find((n) => n.name === 'Account' && n.kind === 'variable')).toBeUndefined();
  6663. });
  6664. it('extracts ggproto classes with direct-arg methods and the parent as extends', () => {
  6665. // ggplot2's OO system — every Geom/Stat/Scale in the ecosystem uses it.
  6666. const code = `
  6667. GeomPoint <- ggproto("GeomPoint", Geom,
  6668. required_aes = c("x", "y"),
  6669. draw_panel = function(data, panel_params, coord) {
  6670. coords <- coord$transform(data, panel_params)
  6671. grid::pointsGrob(coords$x, coords$y)
  6672. },
  6673. draw_key = draw_key_point
  6674. )
  6675. `;
  6676. const result = extractFromSource('geom-point.R', code);
  6677. const cls = result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'class');
  6678. expect(cls).toBeDefined();
  6679. const method = result.nodes.find((n) => n.name === 'draw_panel' && n.kind === 'method');
  6680. expect(method).toBeDefined();
  6681. const ext = result.unresolvedReferences.find(
  6682. (r) => r.referenceKind === 'extends' && r.referenceName === 'Geom'
  6683. );
  6684. expect(ext?.fromNodeId).toBe(cls?.id);
  6685. // No twin variable for the assignment.
  6686. expect(result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'variable')).toBeUndefined();
  6687. });
  6688. });
  6689. });