tree-sitter.ts 326 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187
  1. /**
  2. * Tree-sitter Parser Wrapper
  3. *
  4. * Handles parsing source code and extracting structural information.
  5. */
  6. import { Node as SyntaxNode, Tree } from 'web-tree-sitter';
  7. import * as path from 'path';
  8. import {
  9. Language,
  10. Node,
  11. Edge,
  12. NodeKind,
  13. ExtractionResult,
  14. ExtractionError,
  15. UnresolvedReference,
  16. } from '../types';
  17. import { getParser, detectLanguage, isLanguageSupported, isFileLevelOnlyLanguage } from './grammars';
  18. import { generateNodeId, getNodeText, getChildByField, getPrecedingDocstring } from './tree-sitter-helpers';
  19. import { FN_REF_SPECS, captureFnRefCandidates, type FnRefSpec, type FnRefCandidate } from './function-ref';
  20. import { isGeneratedFile } from './generated-detection';
  21. import type { LanguageExtractor, ExtractorContext } from './tree-sitter-types';
  22. import { EXTRACTORS } from './languages';
  23. import { stripCppTemplateArgs } from './languages/c-cpp';
  24. import { rustImplTypeName } from './languages/rust';
  25. import { LiquidExtractor } from './liquid-extractor';
  26. import { RazorExtractor } from './razor-extractor';
  27. import { SvelteExtractor } from './svelte-extractor';
  28. import { AstroExtractor } from './astro-extractor';
  29. import { DfmExtractor } from './dfm-extractor';
  30. import { VueExtractor } from './vue-extractor';
  31. import { MyBatisExtractor } from './mybatis-extractor';
  32. import { CfmlExtractor } from './cfml-extractor';
  33. import { tryKernelExtract, takeDeferredPreParse } from './kernel';
  34. import {
  35. getAllFrameworkResolvers,
  36. getApplicableFrameworks,
  37. } from '../resolution/frameworks';
  38. // Re-export for backward compatibility
  39. export { generateNodeId } from './tree-sitter-helpers';
  40. /**
  41. * RTK Query generated-hook naming convention: `use` + PascalCase endpoint (with
  42. * an optional `Lazy` variant prefix) + `Query`/`Mutation`. Matches the hook
  43. * bindings to extract from an `export const {...} = api` destructuring. Kept in
  44. * sync with the same convention in `callback-synthesizer.ts` (the synth side).
  45. */
  46. const RTK_HOOK_NAME_RE = /^use[A-Z][A-Za-z0-9]*(?:Query|Mutation)$/;
  47. /** React HOC callees whose result is itself a component — a PascalCase const
  48. * initialized with one of these is a component, not a constant (#841). */
  49. const REACT_COMPONENT_HOCS = new Set(['forwardRef', 'memo', 'React.forwardRef', 'React.memo']);
  50. /**
  51. * Method node types that spell a SIGNATURE — a declaration with no body (#1638).
  52. *
  53. * They are a method of whatever type declares them and nothing on their own, so
  54. * they must not take `extractMethod`'s "no class-like parent, so treat it as a
  55. * free function" fallback. The other `methodTypes` can: a `method_definition`
  56. * outside a class really is a function. This one appears outside a class only
  57. * inside a type literal (`type Handle = { stop(): void }`), whose members
  58. * `extractTypeAlias` already extracts and attaches to the alias (#359) — take
  59. * the fallback and the file gains a phantom top-level `function stop` beside
  60. * the real `Handle::stop`.
  61. */
  62. const SIGNATURE_METHOD_NODE_TYPES = new Set(['method_signature']);
  63. /** Vue store collections whose object-literal members are the symbols an agent
  64. * looks for. Extracted as function nodes so `actions`/`mutations`/`getters` are
  65. * findable + readable (the foundation under any later dispatch-bridge synth). */
  66. const VUE_STORE_COLLECTION_NAMES = new Set(['actions', 'mutations', 'getters']);
  67. /** Store-definition callees whose config object carries those collections. */
  68. const VUE_STORE_FACTORY_CALLEES = new Set(['defineStore', 'createStore']);
  69. /** Distinct signals that a file is a Vuex/Pinia store (≥2 ⇒ treat a bare
  70. * `const actions = {…}` as a store collection — see looksLikeVueStoreFile). */
  71. const VUE_STORE_FILE_SIGNAL = /\bdefineStore\b|\bcreateStore\b|\bVuex\b|\bmutations\b|\bactions\b|\bgetters\b|\bnamespaced\b/g;
  72. /**
  73. * Erlang calls that take their real callee as (Module, Function, Args)
  74. * ARGUMENTS — the spawn/apply family. Keys are the callee as the call site
  75. * spells it: bare for auto-imported BIFs, `module:function` for remote calls.
  76. * Used by the erlang branch of extractCall to lift a static MFA pair into a
  77. * call edge (the spawned/applied function is otherwise invisible to the graph).
  78. */
  79. /** Compiler-predefined Erlang macros — no `-define` exists to link a use to. */
  80. const ERLANG_PREDEFINED_MACROS = new Set([
  81. 'MODULE', 'MODULE_STRING', 'FILE', 'LINE', 'MACHINE',
  82. 'FUNCTION_NAME', 'FUNCTION_ARITY', 'OTP_RELEASE',
  83. 'FEATURE_AVAILABLE', 'FEATURE_ENABLED',
  84. ]);
  85. const ERLANG_MFA_CALLS = new Set([
  86. 'spawn', 'spawn_link', 'spawn_monitor', 'spawn_opt', 'apply',
  87. 'erlang:spawn', 'erlang:spawn_link', 'erlang:spawn_monitor', 'erlang:spawn_opt', 'erlang:apply',
  88. 'proc_lib:spawn', 'proc_lib:spawn_link', 'proc_lib:spawn_opt', 'proc_lib:start', 'proc_lib:start_link',
  89. 'timer:apply_after', 'timer:apply_interval',
  90. 'rpc:call', 'rpc:cast', 'rpc:async_call',
  91. 'erpc:call', 'erpc:cast',
  92. ]);
  93. /**
  94. * Extract the name from a node based on language
  95. */
  96. function extractName(node: SyntaxNode, source: string, extractor: LanguageExtractor): string {
  97. const name = extractNameRaw(node, source, extractor);
  98. // Universal fallback: recover a real identifier from a name still mangled by a
  99. // macro the pre-parse didn't blank (C/C++ only — see recoverMangledName). A
  100. // no-op on well-formed names, so a clean name is never altered.
  101. return extractor.recoverMangledName ? extractor.recoverMangledName(name) : name;
  102. }
  103. function extractNameRaw(node: SyntaxNode, source: string, extractor: LanguageExtractor): string {
  104. const hookName = extractor.resolveName?.(node, source);
  105. if (hookName) return hookName;
  106. // Try field name first
  107. const nameNode = getChildByField(node, extractor.nameField);
  108. if (nameNode) {
  109. // Unwrap pointer_declarator / reference_declarator for C/C++ pointer and
  110. // reference return types (`int* f()`, `int& f()`, `int&& f()`). Without
  111. // unwrapping the reference wrapper an inline reference-returning method is
  112. // named "& f() const" instead of "f" — common in Unreal Engine gameplay
  113. // headers (`const FGameplayTagContainer& GetActiveTags() const`). Out-of-line
  114. // defs (`T& C::f()`) already resolve via the qualified-name hook. A
  115. // pointer_declarator exposes its inner through a `declarator` field; a
  116. // reference_declarator has none, so it's reached via namedChild(0).
  117. let resolved = nameNode;
  118. while (resolved.type === 'pointer_declarator' || resolved.type === 'reference_declarator') {
  119. const inner = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
  120. if (!inner) break;
  121. resolved = inner;
  122. }
  123. // C++ user-defined conversion operator: the declarator is an `operator_cast`
  124. // whose first child is the target type and second is the `() const` tail. Name
  125. // it `operator <type>` (the conventional spelling) rather than the whole
  126. // `operator EALSMovementState() const` declarator, so it matches symbolic
  127. // overloads (`operator+`) and is findable by the type name.
  128. if (resolved.type === 'operator_cast') {
  129. const typeNode = resolved.namedChild(0);
  130. return typeNode ? `operator ${getNodeText(typeNode, source).trim()}` : getNodeText(resolved, source);
  131. }
  132. // Handle complex declarators (C/C++)
  133. if (resolved.type === 'function_declarator' || resolved.type === 'declarator') {
  134. const innerName = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
  135. return innerName ? getNodeText(innerName, source) : getNodeText(resolved, source);
  136. }
  137. // Lua: `function t.f()` / `function t:m()` — the name node is a dot/method
  138. // index expression; the simple name is the trailing field/method (the table
  139. // receiver is captured separately via getReceiverType).
  140. if (resolved.type === 'dot_index_expression') {
  141. const field = getChildByField(resolved, 'field');
  142. if (field) return getNodeText(field, source);
  143. }
  144. if (resolved.type === 'method_index_expression') {
  145. const method = getChildByField(resolved, 'method');
  146. if (method) return getNodeText(method, source);
  147. }
  148. return getNodeText(resolved, source);
  149. }
  150. // For Dart method_signature, look inside inner signature types
  151. if (node.type === 'method_signature') {
  152. for (let i = 0; i < node.namedChildCount; i++) {
  153. const child = node.namedChild(i);
  154. if (child && (
  155. child.type === 'function_signature' ||
  156. child.type === 'getter_signature' ||
  157. child.type === 'setter_signature' ||
  158. child.type === 'constructor_signature' ||
  159. child.type === 'factory_constructor_signature'
  160. )) {
  161. // Find identifier inside the inner signature
  162. for (let j = 0; j < child.namedChildCount; j++) {
  163. const inner = child.namedChild(j);
  164. if (inner?.type === 'identifier') {
  165. return getNodeText(inner, source);
  166. }
  167. }
  168. }
  169. }
  170. }
  171. // Arrow/function expressions get their name from the parent variable_declarator,
  172. // not from identifiers in their body. Without this, single-expression arrow
  173. // functions like `const fn = () => someIdentifier` get named "someIdentifier"
  174. // instead of "fn", because the fallback below finds the body identifier.
  175. if (node.type === 'arrow_function' || node.type === 'function_expression' || node.type === 'generator_function') {
  176. return '<anonymous>';
  177. }
  178. // Fall back to first identifier child
  179. for (let i = 0; i < node.namedChildCount; i++) {
  180. const child = node.namedChild(i);
  181. if (
  182. child &&
  183. (child.type === 'identifier' ||
  184. child.type === 'type_identifier' ||
  185. child.type === 'simple_identifier' ||
  186. child.type === 'constant')
  187. ) {
  188. return getNodeText(child, source);
  189. }
  190. }
  191. return '<anonymous>';
  192. }
  193. /**
  194. * Resolve a Scala type node to its base type NAME for name-matching — unwrapping
  195. * `generic_type` (`Monoid[Int]` → `Monoid`), taking the last segment of a
  196. * qualified `stable_type_identifier` (`cats.Functor` → `Functor`), and falling
  197. * back to a descendant `type_identifier`. Returns null for non-type nodes.
  198. * Shared by Scala inheritance and type-reference extraction.
  199. */
  200. function scalaBaseTypeName(node: SyntaxNode | null, source: string): string | null {
  201. if (!node) return null;
  202. switch (node.type) {
  203. case 'type_identifier':
  204. case 'identifier':
  205. return getNodeText(node, source);
  206. case 'generic_type':
  207. // `<base> type_arguments` — the base type is the first named child.
  208. return scalaBaseTypeName(node.namedChild(0), source);
  209. case 'stable_type_identifier':
  210. case 'stable_identifier': {
  211. // Qualified `a.b.C` — match on the simple (last) segment.
  212. const ids = node.namedChildren.filter(
  213. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'identifier'
  214. );
  215. const last = ids[ids.length - 1];
  216. return last ? getNodeText(last, source) : null;
  217. }
  218. default: {
  219. const id = node.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  220. return id ? getNodeText(id, source) : null;
  221. }
  222. }
  223. }
  224. /**
  225. * Resolve the declared identifier inside a C declarator. A `declaration`'s
  226. * `declarator` field nests the name through `init_declarator` (with value),
  227. * `pointer_declarator`/`array_declarator`/`parenthesized_declarator`
  228. * wrappers (each via their own `declarator` field) down to an `identifier`.
  229. * A `function_declarator` means the declaration is a function prototype (or a
  230. * function-pointer var) — return null so it isn't extracted as a variable.
  231. */
  232. function cDeclaratorIdentifier(node: SyntaxNode | null): SyntaxNode | null {
  233. let cur: SyntaxNode | null = node;
  234. let guard = 0;
  235. while (cur && guard++ < 12) {
  236. switch (cur.type) {
  237. case 'identifier':
  238. return cur;
  239. case 'function_declarator':
  240. return null;
  241. case 'init_declarator':
  242. case 'pointer_declarator':
  243. case 'array_declarator':
  244. case 'parenthesized_declarator':
  245. cur = getChildByField(cur, 'declarator');
  246. break;
  247. default:
  248. return null;
  249. }
  250. }
  251. return null;
  252. }
  253. /** First `simple_identifier` in `node`'s subtree (breadth-ish, first-found).
  254. * Swift's property name nests as `property_declaration → <name> pattern →
  255. * bound_identifier → simple_identifier`; this resolves it (and the bound name of
  256. * a Kotlin/Swift property declarator for the shadow prune). For a tuple pattern
  257. * (`let (a, b)`) it returns the first — acceptable, those are rare for consts. */
  258. function firstSimpleIdentifier(node: SyntaxNode | null): SyntaxNode | null {
  259. const stack: SyntaxNode[] = node ? [node] : [];
  260. let guard = 0;
  261. while (stack.length > 0 && guard++ < 40) {
  262. const n = stack.shift()!;
  263. if (n.type === 'simple_identifier') return n;
  264. for (let i = 0; i < n.namedChildCount; i++) {
  265. const c = n.namedChild(i);
  266. if (c) stack.push(c);
  267. }
  268. }
  269. return null;
  270. }
  271. /** Swift property facts: the bound name, whether it's a `let`, and whether it's
  272. * a *computed* property (a getter block, no stored value — never a constant). */
  273. function swiftPropertyInfo(
  274. node: SyntaxNode,
  275. source: string,
  276. ): { nameNode: SyntaxNode | null; isLet: boolean; isComputed: boolean } {
  277. const pattern =
  278. getChildByField(node, 'name') ??
  279. node.namedChildren.find((c) => c.type === 'value_binding_pattern' || c.type === 'pattern') ??
  280. null;
  281. const binding = node.namedChildren.find((c) => c.type === 'value_binding_pattern');
  282. const isLet = binding != null && getNodeText(binding, source).trimStart().startsWith('let');
  283. const isComputed = node.namedChildren.some(
  284. (c) => c.type === 'computed_property' || c.type === 'protocol_property_requirements',
  285. );
  286. return { nameNode: firstSimpleIdentifier(pattern), isLet, isComputed };
  287. }
  288. /** True when `node` is (transitively) inside a C function body — i.e. a local,
  289. * not a file/namespace-scope declaration. Walks the parent chain to the root. */
  290. function hasFunctionAncestor(node: SyntaxNode): boolean {
  291. let p = node.parent;
  292. while (p) {
  293. if (p.type === 'function_definition') return true;
  294. p = p.parent;
  295. }
  296. return false;
  297. }
  298. /**
  299. * PHP type-position wrapper node kinds (a type-hint is `named_type`,
  300. * `?Foo` is `optional_type`, `A|B` is `union_type`, `A&B` is
  301. * `intersection_type`). Used to find the type subtree inside a parameter /
  302. * property / return position before walking it for class references.
  303. */
  304. const PHP_TYPE_NODES: ReadonlySet<string> = new Set([
  305. 'named_type', 'optional_type', 'nullable_type',
  306. 'union_type', 'intersection_type', 'disjunctive_normal_form_type',
  307. 'primitive_type',
  308. ]);
  309. /**
  310. * Member-access node kinds whose receiver, when it's a capitalized
  311. * type/enum/class name, is a real dependency — `Enum.value`, `Type.CONST`,
  312. * `Foo::BAR`. These VALUE reads (as opposed to `Type.method()` calls, already
  313. * handled) produced no edge, so a type used only via a static member or enum
  314. * value looked like nothing depended on it. See {@link extractStaticMemberRef}.
  315. */
  316. const MEMBER_ACCESS_TYPES: ReadonlySet<string> = new Set([
  317. 'field_access', // java (`Foo.BAR`)
  318. 'member_access_expression', // c# (`Foo.Bar`)
  319. 'navigation_expression', // kotlin / swift (`Foo.bar`)
  320. 'field_expression', // scala (`Foo.bar`)
  321. 'class_constant_access_expression', // php (`Foo::CONST`, `Foo::class`)
  322. 'scoped_property_access_expression', // php (`Foo::$bar`)
  323. 'qualified_identifier', // c++ (`Foo::bar`)
  324. ]);
  325. /**
  326. * Languages whose types are Capitalized by convention, so a capitalized
  327. * member-access receiver is reliably a type (not a local/variable). The
  328. * static-member/value-read pass is gated to these — the ones where it was the
  329. * confirmed residual frontier (enum-value / static-field reads). TS/JS/Python
  330. * are deliberately excluded, and a measured A/B confirms the call: extending the
  331. * pass to them adds ZERO coverage — in import-based languages you must `import` a
  332. * type before any `Type.MEMBER` read, so the import edge already covers it (the
  333. * static read is pure duplication) — while adding real graph noise (+1813 edges /
  334. * +2448 `references` on excalidraw, the retrieval-perf benchmark, all pointing at
  335. * already-covered types). Don't re-add `member_expression`/`attribute` here.
  336. */
  337. const STATIC_MEMBER_LANGS: ReadonlySet<string> = new Set([
  338. 'java', 'csharp', 'kotlin', 'swift', 'scala', 'dart', 'php', 'cpp',
  339. ]);
  340. /**
  341. * Tree-sitter node kinds that represent constructor invocations
  342. * (`new Foo()` and friends). Used by extractInstantiation to emit
  343. * an `instantiates` reference targeting the class name.
  344. */
  345. const INSTANTIATION_KINDS: ReadonlySet<string> = new Set([
  346. 'new_expression', // typescript / javascript / tsx / jsx
  347. 'object_creation_expression', // java / c#
  348. 'instance_creation_expression', // some grammars
  349. 'composite_literal', // go — `Widget{...}` / `pkga.Widget{...}`
  350. 'struct_expression', // rust — `Widget { n: 1 }` / `m::Widget { .. }`
  351. 'instance_expression', // scala — `new Monoid[Int] { ... }`
  352. ]);
  353. /**
  354. * TreeSitterExtractor - Main extraction class
  355. */
  356. /**
  357. * tree-sitter node types (across grammars) for literal expressions in method-
  358. * call RECEIVER position. A literal's methods are the language's builtins —
  359. * `", ".join`, `"x".toUpperCase()`, `5.times`, `[].concat` — never project
  360. * symbols, so a member call on one must not emit a `calls` ref that bare-name
  361. * matching could bind to an unrelated same-named project function (#1230).
  362. */
  363. const LITERAL_RECEIVER_TYPES = new Set([
  364. // strings
  365. 'string', 'string_literal', 'interpreted_string_literal', 'raw_string_literal',
  366. 'template_string', 'concatenated_string', 'formatted_string', 'f_string',
  367. 'line_string_literal', 'string_content', 'heredoc_body',
  368. // numbers
  369. 'number', 'number_literal', 'integer', 'integer_literal', 'float',
  370. 'float_literal', 'int_literal', 'decimal_integer_literal', 'real_literal',
  371. // chars / runes / regex / booleans / null-likes
  372. 'char_literal', 'character_literal', 'rune_literal', 'regex', 'regex_literal',
  373. 'true', 'false', 'boolean_literal', 'bool_literal', 'none', 'null', 'nil',
  374. 'null_literal', 'undefined',
  375. // collection literals
  376. 'list', 'list_literal', 'array', 'array_literal', 'array_creation_expression',
  377. 'dictionary', 'dict_literal', 'object', 'tuple', 'set',
  378. ]);
  379. /**
  380. * Languages whose member calls go through the TS/JS grammars.
  381. */
  382. const TS_JS_CHAIN_LANGUAGES = new Set(['typescript', 'tsx', 'javascript', 'jsx']);
  383. /** Receiver node types (TS/JS grammars) that continue a member chain downward. */
  384. const TS_JS_CHAIN_RECEIVER_TYPES = new Set(['member_expression', 'subscript_expression']);
  385. /**
  386. * Identifier-rooted member chains have no inferred property type (#1566),
  387. * including host API chains (#1707). Keep the existing `window.MyNamespace`
  388. * escape for project globals; call-result and `this` receivers have their own
  389. * paths and are outside this guard.
  390. */
  391. function isUnresolvedTsJsChain(node: SyntaxNode, source: string): boolean {
  392. let cur: SyntaxNode | null = node;
  393. while (cur && TS_JS_CHAIN_RECEIVER_TYPES.has(cur.type)) {
  394. cur = getChildByField(cur, 'object');
  395. }
  396. return !!cur && cur.type === 'identifier' && getNodeText(cur, source) !== 'window';
  397. }
  398. /**
  399. * React hooks that bind a NAME to a handler function (`const onPress =
  400. * useCallback(() => {…}, [])`). The arrow inside is extracted as a function
  401. * node named by the declarator — see `reactHookBoundName`.
  402. */
  403. const REACT_HANDLER_HOOKS = /^(?:React\.)?use(?:Callback|EffectEvent|Event)$/;
  404. export class TreeSitterExtractor {
  405. private filePath: string;
  406. private language: Language;
  407. private source: string;
  408. private tree: Tree | null = null;
  409. private nodes: Node[] = [];
  410. private edges: Edge[] = [];
  411. private unresolvedReferences: UnresolvedReference[] = [];
  412. // Value-reference edges (default ON; set CODEGRAPH_VALUE_REFS=0 to disable; see flushValueRefs).
  413. // Same-file reads of file-scope const/var symbols → `references` edges so impact analysis catches
  414. // value consumers ("change this constant/table, affect its readers").
  415. private static readonly VALUE_REF_LANGS = new Set<string>(['typescript', 'javascript', 'tsx', 'arkts', 'go', 'python', 'rust', 'ruby', 'c', 'java', 'csharp', 'php', 'scala', 'kotlin', 'swift', 'dart', 'pascal']);
  416. private static readonly MAX_VALUE_REF_NODES = 20_000;
  417. private readonly valueRefsEnabled = process.env.CODEGRAPH_VALUE_REFS !== '0';
  418. private fileScopeValues = new Map<string, string>();
  419. private fileScopeValueCounts = new Map<string, number>(); // file-scope nodes per name (conditional-def detection)
  420. private valueRefScopes: Array<{ id: string; node: SyntaxNode; name: string }> = [];
  421. private errors: ExtractionError[] = [];
  422. private extractor: LanguageExtractor | null = null;
  423. private nodeStack: string[] = []; // Stack of parent node IDs
  424. // C/C++ enclosing `namespace ns { … }` names, prepended to every contained
  425. // symbol's qualifiedName (see visitNode). Prefix-only by design — no
  426. // namespace NODE is created: `namespace cutlass {` opens in thousands of
  427. // files, and a node per block would flood search with same-named symbols
  428. // (the #1093 crowd-out failure mode). Always empty outside C/C++.
  429. private namespacePrefix: string[] = [];
  430. // C++ local function-pointer bindings, per enclosing symbol:
  431. // `auto kernel = &flash_fwd_kernel<…>;` recorded as callerId → kernel →
  432. // {flash_fwd_kernel}, so a later `kernel<<<grid, block>>>(params)` (or plain
  433. // `kernel(args)`) in the same body emits calls refs to the real target(s)
  434. // instead of an unresolvable local name. Branch reassignments accumulate —
  435. // each assigned target is a genuine possible callee. Same-body locality is
  436. // the precision guard (the #932 table-dispatch philosophy scoped to locals).
  437. private cppLocalFnPtrs = new Map<string, Map<string, Set<string>>>();
  438. private methodIndex: Map<string, string> | null = null; // lookup key → node ID for Pascal defProc lookup
  439. // Function-as-value capture (#756): per-language spec + candidates collected
  440. // during the walk, gated & flushed into unresolvedReferences at end-of-file
  441. // (see flushFnRefCandidates).
  442. private fnRefSpec: FnRefSpec | undefined;
  443. private fnRefCandidates: Array<FnRefCandidate & { fromNodeId: string }> = [];
  444. // Memoized "is this a Vue store file" verdict (per-extractor = per-file).
  445. private vueStoreFile: boolean | null = null;
  446. // Source already went through the extractor's preParse at the kernel route
  447. // point (this instance is the wasm fallback for a kernel-deferred file) —
  448. // don't blank it a second time.
  449. private sourceIsPreParsed = false;
  450. constructor(
  451. filePath: string,
  452. source: string,
  453. language?: Language,
  454. options?: { sourceIsPreParsed?: boolean }
  455. ) {
  456. this.filePath = filePath;
  457. this.source = source;
  458. this.language = language || detectLanguage(filePath, source);
  459. this.extractor = EXTRACTORS[this.language] || null;
  460. this.fnRefSpec = FN_REF_SPECS[this.language];
  461. this.sourceIsPreParsed = options?.sourceIsPreParsed === true;
  462. }
  463. /**
  464. * Parse and extract from the source code
  465. */
  466. extract(): ExtractionResult {
  467. const startTime = Date.now();
  468. if (!isLanguageSupported(this.language)) {
  469. return {
  470. nodes: [],
  471. edges: [],
  472. unresolvedReferences: [],
  473. errors: [
  474. {
  475. message: `Unsupported language: ${this.language}`,
  476. filePath: this.filePath,
  477. severity: 'error',
  478. code: 'unsupported_language',
  479. },
  480. ],
  481. durationMs: Date.now() - startTime,
  482. };
  483. }
  484. const parser = getParser(this.language);
  485. if (!parser) {
  486. return {
  487. nodes: [],
  488. edges: [],
  489. unresolvedReferences: [],
  490. errors: [
  491. {
  492. message: `Failed to get parser for language: ${this.language}`,
  493. filePath: this.filePath,
  494. severity: 'error',
  495. code: 'parser_error',
  496. },
  497. ],
  498. durationMs: Date.now() - startTime,
  499. };
  500. }
  501. try {
  502. // Optional pre-parse source transform (offset-preserving) to work around
  503. // grammar gaps — e.g. C# blanks conditional-compilation directive lines
  504. // the grammar mis-parses inside enum bodies (#237). We reassign
  505. // this.source so downstream getNodeText reads the same bytes the parser
  506. // saw (identical outside the blanked directive lines). Skipped when the
  507. // kernel route point already applied it (sourceIsPreParsed).
  508. if (this.extractor?.preParse && !this.sourceIsPreParsed) {
  509. this.source = this.extractor.preParse(this.source, this.filePath);
  510. }
  511. this.tree = parser.parse(this.source) ?? null;
  512. if (!this.tree) {
  513. throw new Error('Parser returned null tree');
  514. }
  515. // Create file node representing the source file
  516. const fileNode: Node = {
  517. id: `file:${this.filePath}`,
  518. kind: 'file',
  519. name: path.basename(this.filePath),
  520. qualifiedName: this.filePath,
  521. filePath: this.filePath,
  522. language: this.language,
  523. startLine: 1,
  524. endLine: this.source.split('\n').length,
  525. startColumn: 0,
  526. endColumn: 0,
  527. isExported: false,
  528. updatedAt: Date.now(),
  529. };
  530. this.nodes.push(fileNode);
  531. // Push file node onto stack so top-level declarations get contains edges
  532. this.nodeStack.push(fileNode.id);
  533. // File-level package declaration (Kotlin/Java). Creates an implicit
  534. // `namespace` node wrapping every top-level declaration so their
  535. // qualifiedName carries the FQN — required for cross-file import
  536. // resolution on JVM languages where filename ≠ class name.
  537. const packageNodeId = this.extractFilePackage(this.tree.rootNode);
  538. if (packageNodeId) this.nodeStack.push(packageNodeId);
  539. this.visitNode(this.tree.rootNode);
  540. // Gate + flush function-as-value candidates (#756) while the file's
  541. // nodes and import refs are complete and the file node is still pushed.
  542. this.flushFnRefCandidates();
  543. this.flushValueRefs();
  544. if (packageNodeId) this.nodeStack.pop();
  545. this.nodeStack.pop();
  546. // hasError is routine for several grammars; warn only when no symbols survived.
  547. const symbolCount = this.nodes.filter((n) => n.kind !== 'file').length;
  548. if (this.tree?.rootNode.hasError && symbolCount === 0) {
  549. this.errors.push({
  550. message:
  551. `${this.filePath}: parse produced no symbols (tree has errors) — ` +
  552. `the file is indexed but contributes nothing to the graph`,
  553. severity: 'warning',
  554. code: 'parse_error',
  555. });
  556. }
  557. } catch (error) {
  558. const msg = error instanceof Error ? error.message : String(error);
  559. // WASM memory errors leave the module in a corrupted state — all subsequent
  560. // parses would also fail. Re-throw so the worker can detect and crash,
  561. // forcing a clean restart with a fresh heap.
  562. if (msg.includes('memory access out of bounds') || msg.includes('out of memory')) {
  563. throw error;
  564. }
  565. this.errors.push({
  566. message: `Parse error: ${msg}`,
  567. filePath: this.filePath,
  568. severity: 'error',
  569. code: 'parse_error',
  570. });
  571. } finally {
  572. // Free tree-sitter WASM memory immediately — trees hold native heap memory
  573. // invisible to V8's GC that accumulates across thousands of files.
  574. if (this.tree) {
  575. this.tree.delete();
  576. this.tree = null;
  577. }
  578. // Release source string to reduce GC pressure
  579. this.source = '';
  580. }
  581. return {
  582. nodes: this.nodes,
  583. edges: this.edges,
  584. unresolvedReferences: this.unresolvedReferences,
  585. errors: this.errors,
  586. durationMs: Date.now() - startTime,
  587. };
  588. }
  589. /**
  590. * Function-as-value capture (#756): if this node is one of the language's
  591. * value-position containers (call arguments, assignment RHS, struct/object
  592. * initializer, array/table literal), collect candidate function names from
  593. * it. Candidates are gated & flushed at end-of-file (flushFnRefCandidates).
  594. */
  595. private maybeCaptureFnRefs(node: SyntaxNode, nodeType: string): void {
  596. const spec = this.fnRefSpec;
  597. if (!spec) return;
  598. const rule = spec.dispatch.get(nodeType);
  599. if (!rule || this.nodeStack.length === 0) return;
  600. const fromNodeId = this.nodeStack[this.nodeStack.length - 1];
  601. if (!fromNodeId) return;
  602. for (const cand of captureFnRefCandidates(node, rule, spec, this.source)) {
  603. this.fnRefCandidates.push({ ...cand, fromNodeId });
  604. }
  605. }
  606. /**
  607. * Candidates-only scan of a subtree the main walkers won't traverse
  608. * (top-level variable initializers). No extraction side effects. Halts at
  609. * nested function definitions: their bodies are walked — and their
  610. * candidates attributed — by extractFunction's own body walk.
  611. */
  612. private scanFnRefSubtree(node: SyntaxNode, depth: number): void {
  613. if (!this.fnRefSpec || depth > 12) return;
  614. const nodeType = node.type;
  615. if (depth > 0 && (
  616. this.extractor?.functionTypes.includes(nodeType) ||
  617. ((this.language === 'lua' || this.language === 'luau') && nodeType === 'function_definition') ||
  618. nodeType === 'arrow_function' ||
  619. nodeType === 'function_expression' ||
  620. nodeType === 'lambda_literal' ||
  621. nodeType === 'lambda_expression'
  622. )) {
  623. return;
  624. }
  625. this.maybeCaptureFnRefs(node, nodeType);
  626. for (let i = 0; i < node.namedChildCount; i++) {
  627. const child = node.namedChild(i);
  628. if (child) this.scanFnRefSubtree(child, depth + 1);
  629. }
  630. }
  631. /**
  632. * Gate captured function-as-value candidates and push survivors as
  633. * `function_ref` unresolved references.
  634. *
  635. * The gate bounds volume and protects precision: a candidate survives only
  636. * if its name matches a function/method DEFINED IN THIS FILE or a name this
  637. * file imports/references. Everything else (locals, params, fields passed
  638. * as arguments) is dropped before it ever reaches the database. Resolution
  639. * then matches survivors against function/method nodes only
  640. * (matchFunctionRef) and emits `references` edges — which callers/impact
  641. * already traverse.
  642. *
  643. * Known v1 limit, deliberate: a C/C++ callback registered in a DIFFERENT
  644. * translation unit than its definition (extern, no symbol imports to match)
  645. * is not captured. Same-file registration — the dominant C pattern (static
  646. * callback + same-file ops struct) — is.
  647. */
  648. private flushFnRefCandidates(): void {
  649. if (this.fnRefCandidates.length === 0) return;
  650. const candidates = this.fnRefCandidates;
  651. this.fnRefCandidates = [];
  652. // Generated/minified files (vendored jquery.min.js and friends): their
  653. // function-as-value edges are noise — single-letter minified symbols
  654. // resolve everywhere. Same policy as the callback synthesizer.
  655. if (isGeneratedFile(this.filePath)) return;
  656. const definedHere = new Set<string>();
  657. for (const n of this.nodes) {
  658. if (n.kind === 'function' || n.kind === 'method') definedHere.add(n.name);
  659. // Python only (#1478): class-as-value is a first-class idiom (DRF
  660. // get_serializer_class, Meta.model, registry dicts), so same-file CLASS
  661. // names pass the gate too. Other languages keep the function/method
  662. // gate — TS/JS recover class references through type annotations, and
  663. // resolution's kind filter would drop their class candidates anyway.
  664. else if (this.language === 'python' && n.kind === 'class') definedHere.add(n.name);
  665. }
  666. // Import-binding names only (all binding emitters push kind 'imports').
  667. // Deliberately NOT 'references': those carry type-annotation and
  668. // interface-member names, which let local variables that share a type
  669. // member's name slip through the gate (excalidraw A/B finding). A dotted
  670. // import (JVM `import com.example.OtherClass`) also contributes its LAST
  671. // segment — the simple name Java/Kotlin code uses in `OtherClass::method`
  672. // references.
  673. const SIMPLE_NAME = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
  674. // JVM imports are dotted (`com.example.OtherClass`); PHP `use` imports
  675. // are backslashed (`App\Services\Mailer`). Both contribute their last
  676. // segment — the simple name code uses to reference them.
  677. const QUALIFIED_IMPORT = /^[A-Za-z_$][A-Za-z0-9_$.\\]*[.\\]([A-Za-z_$][A-Za-z0-9_$]*)$/;
  678. const importedNames = new Set<string>();
  679. for (const r of this.unresolvedReferences) {
  680. if (r.referenceKind !== 'imports') continue;
  681. if (SIMPLE_NAME.test(r.referenceName)) {
  682. importedNames.add(r.referenceName);
  683. } else {
  684. const qualified = r.referenceName.match(QUALIFIED_IMPORT);
  685. if (qualified) importedNames.add(qualified[1]!);
  686. }
  687. }
  688. const ungated = this.fnRefSpec?.ungatedModes;
  689. const addressOfOnly = this.fnRefSpec?.addressOfOnly === true;
  690. const seen = new Set<string>();
  691. for (const c of candidates) {
  692. const atFileScope = c.fromNodeId.startsWith('file:');
  693. // C++ (addressOfOnly): a BARE identifier qualifies only inside a
  694. // file-scope initializer table. Everywhere else — args, assignments,
  695. // local braced-init lists like `{begin, size}` — only explicit `&`
  696. // forms count (fmt A/B finding: generic names `begin`/`out`/`size`
  697. // collide with locals and members).
  698. if (
  699. addressOfOnly &&
  700. !c.explicitRef &&
  701. !(atFileScope && (c.mode === 'value' || c.mode === 'list'))
  702. ) {
  703. continue;
  704. }
  705. // Gate policy by candidate shape:
  706. // - `this.<member>`: ALWAYS flush — the member may be inherited from a
  707. // class in another file (definedHere can't see it), volume is
  708. // naturally bounded by real `this.X` expressions, and resolution is
  709. // strictly class-scoped (own members or the validated supertype
  710. // pass), so nothing fuzzy can leak.
  711. // - `Scope::member` (C++ member-pointers, Java/Kotlin type-qualified
  712. // method refs, PHP `'Cls::m'`): ALWAYS flush — the explicit-ref
  713. // syntax is self-selecting, the referenced type often needs NO
  714. // import (Java/Kotlin same-package, Kotlin companions), and
  715. // resolution is scope-suffix-anchored + unique-or-drop, so a
  716. // same-named member on another class can't match.
  717. // - C-family file-scope initializers skip the gate entirely
  718. // (constant-expression context — see FnRefSpec.ungatedModes).
  719. // - everything else: name ∈ same-file functions/methods ∪ imports.
  720. if (!c.name.startsWith('this.') && !c.name.includes('::')) {
  721. const skipGate =
  722. (ungated?.has(c.mode) === true && atFileScope) ||
  723. c.skipGate === true; // PHP HOF-position string callables (see FnRefCandidate.skipGate)
  724. if (!skipGate && !definedHere.has(c.name) && !importedNames.has(c.name)) {
  725. continue;
  726. }
  727. }
  728. const key = `${c.fromNodeId}|${c.name}`;
  729. if (seen.has(key)) continue;
  730. seen.add(key);
  731. this.unresolvedReferences.push({
  732. fromNodeId: c.fromNodeId,
  733. referenceName: c.name,
  734. referenceKind: 'function_ref',
  735. line: c.line,
  736. column: c.column,
  737. });
  738. }
  739. }
  740. /**
  741. * Record value-reference bookkeeping as nodes are created: file-scope const/var symbols with
  742. * distinctive names become reference targets; function/method/const/var symbols become reader
  743. * scopes whose bodies flushValueRefs scans.
  744. */
  745. private captureValueRefScope(kind: NodeKind, name: string, id: string, node: SyntaxNode): void {
  746. // Pascal targets `constant` only: its extractor emits function PARAMETERS
  747. // (`Dest: TBufferWriter`) and class fields (`declField`) as `variable` at the
  748. // enclosing scope, which would otherwise become noisy targets (a param name
  749. // shared across many procs collapses to one file-wide target). Genuine
  750. // Pascal shared values are `const` (`constant`), so restrict to that. (Unit
  751. // `var` globals are the rare cost; the parameter/field noise dominates.)
  752. const targetKindOk =
  753. this.language === 'pascal' ? kind === 'constant' : kind === 'constant' || kind === 'variable';
  754. if (targetKindOk && name.length >= 3 && /[A-Z_]/.test(name)) {
  755. const parentId = this.nodeStack[this.nodeStack.length - 1];
  756. // file-scope OR class/module/struct/enum-scope constants are targets.
  757. // Class/module scope matters for languages (Ruby) that keep nearly all
  758. // constants inside a class or module; struct/enum scope matters for Swift,
  759. // which namespaces shared constants in `struct`/`enum` (`enum Constants {
  760. // static let X }`). Readers are same-file methods of that type.
  761. if (
  762. parentId &&
  763. (parentId.startsWith('file:') || parentId.startsWith('class:') ||
  764. parentId.startsWith('module:') || parentId.startsWith('struct:') ||
  765. parentId.startsWith('enum:'))
  766. ) {
  767. this.fileScopeValues.set(name, id);
  768. // How many target nodes carry this name. A conditional def
  769. // (`try: X = a; except: X = b`) makes >1 — distinct from a local shadow,
  770. // which adds a binding the prune must catch (see flushValueRefs).
  771. this.fileScopeValueCounts.set(name, (this.fileScopeValueCounts.get(name) ?? 0) + 1);
  772. }
  773. }
  774. if (kind === 'function' || kind === 'method' || kind === 'constant' || kind === 'variable') {
  775. this.valueRefScopes.push({ id, node, name });
  776. }
  777. }
  778. /**
  779. * Emit same-file `references` edges from a symbol to the file-scope const/var it reads (TS/JS).
  780. * The engine doesn't edge const→consumer, so impact analysis misses "change this table, affect
  781. * its readers" (the ReScript-PR false positive). Same-file only (resolution is unambiguous),
  782. * distinctive target names only (dodges the local-shadowing precision trap documented on
  783. * function_ref), deduped per (reader, target). Default on (CODEGRAPH_VALUE_REFS=0 disables) +
  784. * additive. Shadowed targets are pruned — see below.
  785. */
  786. private flushValueRefs(): void {
  787. const scopes = this.valueRefScopes;
  788. const targets = this.fileScopeValues;
  789. const fileScopeCounts = this.fileScopeValueCounts;
  790. this.valueRefScopes = [];
  791. this.fileScopeValues = new Map();
  792. this.fileScopeValueCounts = new Map();
  793. if (!this.valueRefsEnabled || !TreeSitterExtractor.VALUE_REF_LANGS.has(this.language)) return;
  794. if (targets.size === 0 || scopes.length === 0 || isGeneratedFile(this.filePath)) return;
  795. // Prune SHADOWED targets. A target re-bound in an INNER scope (a
  796. // bundled/Emscripten `const Module` re-declared as a nested `var Module`; a
  797. // Go package `const Timeout` shadowed by a local `Timeout := …`; a Python
  798. // module `CONFIG` shadowed by a local `CONFIG = …`) resolves to the inner
  799. // binding for nested readers, so a file-scope edge is a false positive.
  800. // Inner re-bindings aren't graph nodes, so detect them at the syntax level:
  801. // count every declarator of the name across the tree and compare against how
  802. // many FILE-SCOPE nodes carry it. A real shadow makes (declarators >
  803. // file-scope nodes) — the excess is the local binding. A conditional
  804. // module-level def (`try: X = a; except: X = b`) makes them EQUAL (both
  805. // declarators are file-scope nodes), so it's correctly kept. Complements the
  806. // path-based isGeneratedFile() check, which can't catch content-minified
  807. // bundles.
  808. //
  809. // Declarator node types are per-grammar; a file only contains its own
  810. // language's nodes, so matching all of them in one switch is safe.
  811. if (this.tree) {
  812. const declCounts = new Map<string, number>();
  813. const bump = (nameNode: SyntaxNode | null) => {
  814. // `simple_identifier` is Kotlin's name node (a property declarator's name).
  815. if (nameNode && (nameNode.type === 'identifier' || nameNode.type === 'simple_identifier')) {
  816. const nm = getNodeText(nameNode, this.source);
  817. if (targets.has(nm)) declCounts.set(nm, (declCounts.get(nm) ?? 0) + 1);
  818. }
  819. };
  820. const dstack: SyntaxNode[] = [this.tree.rootNode];
  821. let dvisited = 0;
  822. while (dstack.length > 0 && dvisited < TreeSitterExtractor.MAX_VALUE_REF_NODES) {
  823. const n = dstack.pop()!;
  824. dvisited++;
  825. switch (n.type) {
  826. case 'variable_declarator': // TS/JS/tsx
  827. case 'const_spec': // Go `const X = …`
  828. case 'var_spec': // Go `var X = …`
  829. bump(n.namedChild(0));
  830. break;
  831. case 'const_item': // Rust `const X: T = …`
  832. case 'static_item': // Rust `static X: T = …`
  833. bump(getChildByField(n, 'name'));
  834. break;
  835. case 'let_declaration': // Rust `let x = …` (locals — the shadow source)
  836. case 'short_var_declaration': // Go `x, Y := …`
  837. case 'assignment': { // Python `X = …` / `X: T = …` / `A, B = …`
  838. const left = getChildByField(n, 'left') ?? getChildByField(n, 'pattern') ?? n.namedChild(0);
  839. if (left?.type === 'identifier') bump(left);
  840. else if (left) for (const c of left.namedChildren) bump(c);
  841. break;
  842. }
  843. case 'init_declarator': // C `T X = …` (file-scope const AND the local that shadows it)
  844. bump(cDeclaratorIdentifier(n));
  845. break;
  846. case 'val_definition': // Scala `val X = …` (object/top-level const AND a method-local that shadows it)
  847. case 'var_definition': { // Scala `var X = …`
  848. const pat = getChildByField(n, 'pattern');
  849. if (pat?.type === 'identifier') bump(pat);
  850. break;
  851. }
  852. case 'static_final_declaration': // Dart top-level/`static` `const`/`final` (the target itself)
  853. case 'initialized_identifier': // Dart instance field / `var`
  854. case 'initialized_variable_definition': { // Dart a method-local `const`/`final`/`var` that shadows a const
  855. const id = n.namedChildren.find((c) => c.type === 'identifier');
  856. if (id) bump(id);
  857. break;
  858. }
  859. case 'declConst': // Pascal unit/class `const` (the target itself) AND a function-local `const` that shadows it
  860. case 'declVar': { // Pascal a function-local `var` that shadows a const
  861. bump(getChildByField(n, 'name'));
  862. break;
  863. }
  864. case 'property_declaration': { // Kotlin / Swift `val`/`let X = …` (object/static const AND a method-local that shadows it)
  865. // Kotlin: variable_declaration → simple_identifier; Swift: a `pattern`
  866. // (`<name>` field) → simple_identifier. Resolve either shape.
  867. const vd = n.namedChildren.find((c) => c.type === 'variable_declaration');
  868. const id = vd
  869. ? vd.namedChildren.find((c) => c.type === 'simple_identifier')
  870. : firstSimpleIdentifier(
  871. getChildByField(n, 'name') ??
  872. n.namedChildren.find((c) => c.type === 'value_binding_pattern' || c.type === 'pattern') ??
  873. null,
  874. );
  875. if (id) bump(id);
  876. break;
  877. }
  878. }
  879. for (let i = 0; i < n.namedChildCount; i++) {
  880. const c = n.namedChild(i);
  881. if (c) dstack.push(c);
  882. }
  883. }
  884. for (const [nm, c] of declCounts) if (c > (fileScopeCounts.get(nm) ?? 1)) targets.delete(nm);
  885. if (targets.size === 0) return;
  886. }
  887. for (const scope of scopes) {
  888. const seen = new Set<string>();
  889. const stack: SyntaxNode[] = [scope.node];
  890. // Dart and Pascal attach a function/method BODY as a *next sibling* of the
  891. // signature node that is stored as the reader scope (Dart `method_signature`
  892. // ← `function_body`; Pascal `declProc` ← `block`, both under a `defProc`),
  893. // not as a child — so the scope subtree is just the signature and the reads
  894. // live in the sibling. Pull it in. (A body as a next sibling of the scope
  895. // node is unique to Dart/Pascal among the value-ref languages — every other
  896. // grammar nests the body inside the function node — so this is inert
  897. // elsewhere.)
  898. const sib = scope.node.nextNamedSibling;
  899. if (sib && (sib.type === 'function_body' || sib.type === 'block')) stack.push(sib);
  900. let visited = 0;
  901. while (stack.length > 0 && visited < TreeSitterExtractor.MAX_VALUE_REF_NODES) {
  902. const n = stack.pop()!;
  903. visited++;
  904. // `constant` covers Ruby, where both a constant's definition and its
  905. // references are `constant`-typed nodes, not `identifier`. `name` covers
  906. // PHP, where a constant reference — bare `MAX_ITEMS` or the const half of
  907. // `self::MAX_ITEMS` / `Foo::MAX_ITEMS` — is a `name` node (a `$var` local
  908. // is a `variable_name`, a different namespace, so it can never shadow a
  909. // bare constant — no prune wiring needed). `simple_identifier` covers
  910. // Kotlin, whose every name reference (a const read included) is that
  911. // node type. Safe across languages: a file only holds its own grammar's
  912. // nodes; `name` is PHP-only and `simple_identifier` is Kotlin-only here.
  913. if (
  914. n.type === 'identifier' || n.type === 'constant' ||
  915. n.type === 'name' || n.type === 'simple_identifier'
  916. ) {
  917. const refName = getNodeText(n, this.source);
  918. const targetId = targets.get(refName);
  919. // Skip self and same-name targets: a symbol referencing a file-scope
  920. // sibling of its own name (the two halves of a conditional `try: X=…;
  921. // except: X=…`) is never a meaningful value read.
  922. if (targetId && targetId !== scope.id && refName !== scope.name && !seen.has(targetId)) {
  923. seen.add(targetId);
  924. this.edges.push({
  925. source: scope.id,
  926. target: targetId,
  927. kind: 'references',
  928. metadata: { valueRef: true },
  929. });
  930. }
  931. }
  932. for (let i = 0; i < n.namedChildCount; i++) {
  933. const c = n.namedChild(i);
  934. if (c) stack.push(c);
  935. }
  936. }
  937. }
  938. }
  939. /**
  940. * Visit a node and extract information
  941. */
  942. private visitNode(node: SyntaxNode): void {
  943. if (!this.extractor) return;
  944. const nodeType = node.type;
  945. let skipChildren = false;
  946. // Language-specific custom visitor hook
  947. if (this.extractor.visitNode) {
  948. const ctx = this.makeExtractorContext();
  949. const handled = this.extractor.visitNode(node, ctx);
  950. if (handled) {
  951. // The hook consumed this subtree, so the walkers below never descend
  952. // into it — scan it for function-as-value candidates (#756). Scala's
  953. // hook handles val/var definitions (`val table = Seq(targetCb)`), for
  954. // example. The scan is capture-only and halts at nested functions.
  955. this.scanFnRefSubtree(node, 0);
  956. return;
  957. }
  958. }
  959. // Pascal-specific AST handling
  960. if (this.language === 'pascal') {
  961. skipChildren = this.visitPascalNode(node);
  962. if (skipChildren) return;
  963. }
  964. // C++ namespace blocks: carry the namespace name as a qualifiedName prefix
  965. // while walking the body, so `namespace flash { void compute_attn(); }`
  966. // indexes compute_attn with qualifiedName `flash::compute_attn` and a
  967. // namespace-qualified call (`flash::compute_attn(...)`) resolves by exact
  968. // qualified match instead of never resolving — C++ namespaces previously
  969. // left no trace in qualifiedNames at all, so every `ns::fn()` call site
  970. // was a permanently dead edge (surfaced by #387 flow validation on
  971. // flash-attention/cutlass, whose kernel dispatch is namespace-qualified).
  972. // C++17 nested forms (`namespace a::b {`) prefix as written. An anonymous
  973. // namespace falls through to the generic walk — its contents stay bare,
  974. // matching how call sites spell them.
  975. if (this.language === 'cpp' && nodeType === 'namespace_definition') {
  976. const nameNode = getChildByField(node, 'name');
  977. const nsName = nameNode ? getNodeText(nameNode, this.source) : '';
  978. if (nsName) {
  979. this.namespacePrefix.push(nsName);
  980. for (let i = 0; i < node.namedChildCount; i++) {
  981. const child = node.namedChild(i);
  982. if (child) this.visitNode(child);
  983. }
  984. this.namespacePrefix.pop();
  985. return;
  986. }
  987. }
  988. // Function-as-value capture (#756) — independent of the dispatch ladder
  989. // below (the captured container types have no other handler there), so it
  990. // can never shadow or be shadowed by an extraction branch.
  991. this.maybeCaptureFnRefs(node, nodeType);
  992. // Check for function declarations
  993. // For Python/Ruby, function_definition inside a class should be treated as method
  994. if (this.extractor.functionTypes.includes(nodeType)) {
  995. if (this.isInsideClassLikeNode() && this.extractor.methodTypes.includes(nodeType)) {
  996. // Inside a class - treat as method
  997. this.extractMethod(node);
  998. skipChildren = true; // extractMethod visits children via visitFunctionBody
  999. } else {
  1000. this.extractFunction(node);
  1001. skipChildren = true; // extractFunction visits children via visitFunctionBody
  1002. }
  1003. }
  1004. // Check for class declarations
  1005. else if (this.extractor.classTypes.includes(nodeType)) {
  1006. // Some languages reuse class_declaration for structs/enums (e.g. Swift)
  1007. const classification = this.extractor.classifyClassNode?.(node) ?? 'class';
  1008. if (classification === 'struct') {
  1009. this.extractStruct(node);
  1010. } else if (classification === 'enum') {
  1011. this.extractEnum(node);
  1012. } else if (classification === 'interface') {
  1013. this.extractInterface(node);
  1014. } else if (classification === 'trait') {
  1015. this.extractClass(node, 'trait');
  1016. } else {
  1017. this.extractClass(node);
  1018. }
  1019. skipChildren = true; // extractClass visits body children
  1020. }
  1021. // Extra class node types (e.g. Dart mixin_declaration, extension_declaration)
  1022. else if (this.extractor.extraClassNodeTypes?.includes(nodeType)) {
  1023. this.extractClass(node);
  1024. skipChildren = true;
  1025. }
  1026. // Check for method declarations (only if not already handled by functionTypes).
  1027. // A bodiless SIGNATURE only counts as one where a type declares it — see
  1028. // SIGNATURE_METHOD_NODE_TYPES for what falling through would otherwise mint.
  1029. else if (
  1030. this.extractor.methodTypes.includes(nodeType)
  1031. && (!SIGNATURE_METHOD_NODE_TYPES.has(nodeType) || this.isInsideClassLikeNode())
  1032. ) {
  1033. // TS/JS class fields parse as a methodTypes node; only function-valued
  1034. // fields are methods — a plain field (`public fonts: Fonts;`) is a
  1035. // property (#808). C++ lists `field_declaration` so pure-virtual methods
  1036. // mint nodes (#1727); non-callable ones return 'skip' and fall through to
  1037. // the children walk. classifyMethodNode is absent for other languages.
  1038. const methodClass = this.extractor.classifyMethodNode?.(node) ?? 'method';
  1039. if (methodClass === 'skip') {
  1040. // Not a method — leave skipChildren false so data-member initializers
  1041. // still contribute call/instantiation edges under the enclosing class.
  1042. } else if (methodClass === 'property') {
  1043. const propNode = this.extractProperty(node);
  1044. // Walk the initializer so its calls/instantiations attribute to the
  1045. // property (`history = createHistory()` → history calls
  1046. // createHistory). The old field-as-method path never walked these
  1047. // (resolveBody only resolves function bodies), so this is additive.
  1048. const valueNode = getChildByField(node, 'value');
  1049. if (propNode && valueNode) {
  1050. this.nodeStack.push(propNode.id);
  1051. this.visitFunctionBody(valueNode, '');
  1052. this.nodeStack.pop();
  1053. }
  1054. // A field initializer can also register callbacks
  1055. // (`static handlers = { click: onClick }`) — scan it for
  1056. // function-as-value candidates (capture-only, halts at functions).
  1057. this.scanFnRefSubtree(node, 0);
  1058. skipChildren = true;
  1059. } else {
  1060. this.extractMethod(node);
  1061. skipChildren = true; // extractMethod visits children via visitFunctionBody
  1062. }
  1063. }
  1064. // Check for interface/protocol/trait declarations
  1065. else if (this.extractor.interfaceTypes.includes(nodeType)) {
  1066. this.extractInterface(node);
  1067. skipChildren = true; // extractInterface visits body children
  1068. }
  1069. // Check for struct declarations
  1070. else if (this.extractor.structTypes.includes(nodeType)) {
  1071. this.extractStruct(node);
  1072. skipChildren = true; // extractStruct visits body children
  1073. }
  1074. // Check for union declarations
  1075. else if (this.extractor.unionTypes?.includes(nodeType)) {
  1076. this.extractUnion(node);
  1077. skipChildren = true; // extractUnion visits body children
  1078. }
  1079. // Check for enum declarations
  1080. else if (this.extractor.enumTypes.includes(nodeType)) {
  1081. this.extractEnum(node);
  1082. skipChildren = true; // extractEnum visits body children
  1083. }
  1084. // Check for type alias declarations (e.g. `type X = ...` in TypeScript)
  1085. // For Go, type_spec wraps struct/interface definitions — resolveTypeAliasKind
  1086. // detects these and extractTypeAlias creates the correct node kind.
  1087. else if (this.extractor.typeAliasTypes.includes(nodeType)) {
  1088. skipChildren = this.extractTypeAlias(node);
  1089. }
  1090. // Check for class properties (e.g. C# property_declaration)
  1091. else if (this.extractor.propertyTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
  1092. this.extractProperty(node);
  1093. // Property initializers aren't walked — scan for function-as-value
  1094. // candidates (#756): Scala `val table = Seq(targetCb)` in an object,
  1095. // Kotlin `val cb = ::handler` class properties.
  1096. this.scanFnRefSubtree(node, 0);
  1097. skipChildren = true;
  1098. }
  1099. // Check for class fields (e.g. Java field_declaration, C# field_declaration)
  1100. else if (this.extractor.fieldTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
  1101. this.extractField(node);
  1102. // Field initializers aren't walked — scan for function-as-value
  1103. // candidates (#756): Java `List<IntConsumer> table = List.of(Main::cb)`,
  1104. // C# `List<Action<int>> table = new() { TargetCb }`.
  1105. this.scanFnRefSubtree(node, 0);
  1106. skipChildren = true;
  1107. }
  1108. // Check for variable declarations (const, let, var, etc.)
  1109. // Only extract top-level variables (not inside functions/methods) — plus
  1110. // class/module-scope CONSTANTS, which Ruby (and other const-in-class
  1111. // languages) keep almost exclusively inside a class/module. A Ruby `CONST =
  1112. // …` has a `constant`-typed LHS; other languages don't put one here, so this
  1113. // is effectively Ruby-only and doesn't disturb their class-internal locals.
  1114. else if (
  1115. this.extractor.variableTypes.includes(nodeType) &&
  1116. (!this.isInsideClassLikeNode() || this.isClassScopeConstantAssignment(node))
  1117. ) {
  1118. this.extractVariable(node);
  1119. // extractVariable doesn't walk every initializer shape (object literals
  1120. // are deliberately skipped; Python/Ruby don't walk at all), so scan the
  1121. // declaration subtree for function-as-value candidates — `const routes =
  1122. // { home: renderHome }`, `handlers = {"recv": target_cb}`. The scan halts
  1123. // at nested function definitions (their bodies are walked — and
  1124. // attributed — separately) and flush-time dedup absorbs any overlap with
  1125. // initializers extractVariable DOES walk.
  1126. this.scanFnRefSubtree(node, 0);
  1127. skipChildren = true; // extractVariable handles children
  1128. }
  1129. // Swift properties inside a type. A stored instance property becomes a `field`
  1130. // node; a `static let`/`static var` member becomes `constant`/`variable`
  1131. // (Swift's `static`-namespacing idiom — value-reference edges can then target
  1132. // it); a COMPUTED property (getter block, no stored value) becomes a `property`
  1133. // node whose getter is walked below so its calls attribute to it. A property's
  1134. // PROPERTY WRAPPER (`@Argument`/`@Published`/`@State`/custom) and declared type
  1135. // are dependencies attributed to the enclosing type. (Other languages extract
  1136. // properties via property/field types.)
  1137. else if (
  1138. this.language === 'swift' &&
  1139. (nodeType === 'property_declaration' || nodeType === 'protocol_property_declaration') &&
  1140. this.isInsideClassLikeNode()
  1141. ) {
  1142. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  1143. const { nameNode, isLet, isComputed } = swiftPropertyInfo(node, this.source);
  1144. let computedPropId: string | undefined;
  1145. if (nameNode) {
  1146. if (isComputed) {
  1147. // Computed property — accessed like a property but its getter holds real
  1148. // logic. Index as `property` so search/explore find it (#1020: computed
  1149. // props such as a heavily-read `var isCloudProxy: Bool` returned "No
  1150. // results found"); pushed below so the getter's calls attribute to it
  1151. // rather than flattening onto the owning type (SwiftUI `var body: some
  1152. // View { … }` — the whole subview tree — is the canonical case).
  1153. const prop = this.createNode('property', getNodeText(nameNode, this.source), node, {
  1154. visibility: this.extractor.getVisibility?.(node),
  1155. isStatic: this.extractor.isStatic?.(node) ?? false,
  1156. });
  1157. computedPropId = prop?.id;
  1158. } else {
  1159. // A `static let`/`static var` member is a SHARED constant of the type
  1160. // (esp. in `enum`/`struct`); an instance stored property stays a `field`
  1161. // (per-instance — Swift instance properties otherwise aren't own nodes).
  1162. const isStatic = this.extractor.isStatic?.(node) ?? false;
  1163. this.createNode(isStatic ? (isLet ? 'constant' : 'variable') : 'field',
  1164. getNodeText(nameNode, this.source), node, {
  1165. visibility: this.extractor.getVisibility?.(node),
  1166. isStatic,
  1167. });
  1168. }
  1169. }
  1170. if (ownerId) {
  1171. this.extractDecoratorsFor(node, ownerId);
  1172. this.extractVariableTypeAnnotation(node, ownerId);
  1173. // Fluent / SwiftUI property-wrapper attributes often reference a model or
  1174. // type by metatype in their ARGUMENTS — `@Siblings(through: Pivot.self,
  1175. // …)`, `@Group(…)`. extractDecoratorsFor captures the wrapper type
  1176. // (`Siblings`); this pulls the TYPE out of the argument expressions
  1177. // (`Pivot.self` → a dependency on Pivot), so a model reached ONLY through
  1178. // a relationship (a many-to-many pivot/join model) isn't left orphaned.
  1179. // extractStaticMemberRef self-filters to `Type.member` navigation, so the
  1180. // `\.$keypath` arguments and the wrapper `user_type` are skipped.
  1181. const modifiers = node.namedChildren.find((c: SyntaxNode) => c.type === 'modifiers');
  1182. if (modifiers) {
  1183. const walkAttrArgs = (n: SyntaxNode): void => {
  1184. this.extractStaticMemberRef(n);
  1185. for (let i = 0; i < n.namedChildCount; i++) {
  1186. const c = n.namedChild(i);
  1187. if (c) walkAttrArgs(c);
  1188. }
  1189. };
  1190. walkAttrArgs(modifiers);
  1191. }
  1192. }
  1193. // A computed property's getter holds real logic — walk it with the property
  1194. // node pushed so its calls/instantiations attribute to the property (a
  1195. // SwiftUI `body`'s subview tree becomes the property's callees). skipChildren
  1196. // then stops the generic walker from re-walking the getter (and the
  1197. // modifiers/type annotation already handled above).
  1198. if (computedPropId) {
  1199. const getter = node.namedChildren.find(
  1200. (c: SyntaxNode) =>
  1201. c.type === 'computed_property' || c.type === 'protocol_property_requirements',
  1202. );
  1203. if (getter) {
  1204. this.nodeStack.push(computedPropId);
  1205. this.visitFunctionBody(getter, '');
  1206. this.nodeStack.pop();
  1207. }
  1208. skipChildren = true;
  1209. }
  1210. }
  1211. // `export_statement` itself is not extracted — the walker descends
  1212. // into children, where the inner declaration (lexical_declaration,
  1213. // function_declaration, class_declaration, etc.) is dispatched to
  1214. // its own extractor. `isExported` walks the parent chain, so the
  1215. // exported flag is preserved automatically.
  1216. //
  1217. // Calling extractExportedVariables here AND descending caused every
  1218. // `export const X = ...` to produce two nodes for the same symbol —
  1219. // one kind:'variable' from extractExportedVariables and one
  1220. // kind:'constant' from extractVariable. The dedicated dispatch is
  1221. // the correct one (it picks kind from isConst, captures the
  1222. // initializer signature, and walks type annotations); the
  1223. // export-statement helper was redundant.
  1224. // Check for imports
  1225. else if (this.extractor.importTypes.includes(nodeType)) {
  1226. this.extractImport(node);
  1227. }
  1228. // Re-export from another module — `export { X } from './y'` (TS/JS). A
  1229. // re-export is a dependency on the source module just like an import, but
  1230. // the export_statement is otherwise only descended into (no declaration to
  1231. // extract), so a barrel that ONLY re-exports produced zero edges and showed
  1232. // 0 dependents. Link each re-exported name to its definition. Children are
  1233. // still visited (a non-re-export `export const X = …` has no `source` and
  1234. // falls through to its normal declaration extraction).
  1235. else if (
  1236. nodeType === 'export_statement' &&
  1237. (this.language === 'typescript' || this.language === 'tsx' ||
  1238. this.language === 'javascript' || this.language === 'jsx' ||
  1239. this.language === 'arkts') &&
  1240. getChildByField(node, 'source')
  1241. ) {
  1242. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1243. if (parentId) this.emitReExportRefs(node, parentId);
  1244. }
  1245. // Vuex MODULE default export — `export default { namespaced, actions: {…},
  1246. // mutations: {…} }` (the canonical Vuex module shape). Object-literal methods
  1247. // aren't otherwise extracted, so scan the config's actions/mutations/getters
  1248. // collections and extract their methods as nodes. Store-file gated (the
  1249. // ≥2-signal heuristic) so a plain default-exported object is untouched; skip
  1250. // the subtree afterward (the collection methods are now handled).
  1251. else if (
  1252. nodeType === 'export_statement' &&
  1253. (this.language === 'typescript' || this.language === 'tsx' ||
  1254. this.language === 'javascript' || this.language === 'jsx') &&
  1255. this.looksLikeVueStoreFile()
  1256. ) {
  1257. const exported = getChildByField(node, 'value');
  1258. if (exported && (exported.type === 'object' || exported.type === 'object_expression')) {
  1259. this.extractStoreCollectionMethods(exported);
  1260. skipChildren = true;
  1261. }
  1262. }
  1263. // Check for function calls
  1264. else if (this.extractor.callTypes.includes(nodeType)) {
  1265. this.extractCall(node);
  1266. }
  1267. // `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  1268. // produce an `instantiates` reference. Children still walked so
  1269. // nested calls inside the constructor args (`new Foo(bar())`) get
  1270. // their own `calls` refs.
  1271. else if (INSTANTIATION_KINDS.has(nodeType) || this.isVbnetConstructorShapedArrayCreation(node)) {
  1272. this.extractInstantiation(node);
  1273. // Java/C# `new T(...) { ... }` — anonymous class with body. Without
  1274. // extracting it as a class node + its methods, the interface→impl
  1275. // synthesizer (Phase 5.5) can't bridge T's abstract methods to the
  1276. // anonymous overrides, and an agent investigating a call through T
  1277. // (`strategy.iterator(...)` where strategy is a Strategy lambda body)
  1278. // has to Read the file to find the actual implementation.
  1279. const anonBody = this.findAnonymousClassBody(node);
  1280. if (anonBody) {
  1281. this.extractAnonymousClass(node, anonBody);
  1282. skipChildren = true;
  1283. }
  1284. }
  1285. // (Decorator handling lives inside the symbol-creating extractors
  1286. // — extractClass / extractFunction / extractProperty — because the
  1287. // decorator node sits BEFORE the symbol in the AST and the walker
  1288. // would otherwise see the wrong nodeStack head.)
  1289. // Rust: `impl Trait for Type { ... }` — creates implements edge from Type to Trait
  1290. else if (nodeType === 'impl_item') {
  1291. this.extractRustImplItem(node);
  1292. }
  1293. // NOTE: `property_signature` / `method_signature` used to be handled here,
  1294. // hanging their type annotations off the ENCLOSING INTERFACE — the only
  1295. // anchor available while the members themselves went unextracted. Since
  1296. // #1638 they are in the TS extractor's `methodTypes` / `propertyTypes`, so
  1297. // the branches above claim them first (under the same `isInsideClassLikeNode`
  1298. // guard this branch had, so nothing it used to reach is now missed) and this
  1299. // one was dead. The `references` edges survive — `extractMethod` and
  1300. // `extractProperty` each call `extractTypeAnnotations` — but now hang off
  1301. // the member, which is the more precise anchor: `Api::fetch → PageId` says
  1302. // which member wants the type, where `Api → PageId` only said the file did.
  1303. // Visit children (unless the extract method already visited them)
  1304. if (!skipChildren) {
  1305. for (let i = 0; i < node.namedChildCount; i++) {
  1306. const child = node.namedChild(i);
  1307. if (child) {
  1308. this.visitNode(child);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. /**
  1314. * Create a Node object
  1315. */
  1316. private createNode(
  1317. kind: NodeKind,
  1318. name: string,
  1319. node: SyntaxNode,
  1320. extra?: Partial<Node>
  1321. ): Node | null {
  1322. // Skip nodes with empty/missing names — they are not meaningful symbols
  1323. // and would cause FK violations when edges reference them (see issue #42)
  1324. if (!name) {
  1325. return null;
  1326. }
  1327. const id = generateNodeId(this.filePath, kind, name, node.startPosition.row + 1);
  1328. // Some grammars (e.g. Dart) model a function/method body as a *sibling* of
  1329. // the signature node, so the declaration node's own range is just the
  1330. // signature line. Extend endLine to the resolved body when it sits beyond
  1331. // the node so the node spans its body — required for any body-level analysis
  1332. // (callees, the callback synthesizer's body scan, context slices). Guarded to
  1333. // only ever extend: for child-body grammars the body is within range (no-op).
  1334. let endLine = node.endPosition.row + 1;
  1335. if (kind === 'function' || kind === 'method') {
  1336. const body = this.extractor?.resolveBody?.(node, this.extractor.bodyField);
  1337. if (body && body.endPosition.row + 1 > endLine) {
  1338. endLine = body.endPosition.row + 1;
  1339. }
  1340. }
  1341. const newNode: Node = {
  1342. id,
  1343. kind,
  1344. name,
  1345. qualifiedName: this.buildQualifiedName(name),
  1346. filePath: this.filePath,
  1347. language: this.language,
  1348. startLine: node.startPosition.row + 1,
  1349. endLine,
  1350. startColumn: node.startPosition.column,
  1351. endColumn: node.endPosition.column,
  1352. updatedAt: Date.now(),
  1353. ...extra,
  1354. };
  1355. // Persist extra symbol-level modifiers (e.g. Kotlin `expect`/`actual`) onto
  1356. // the node's decorators list so the resolver can pair multiplatform
  1357. // declarations with their implementations. Merged, not overwritten, so a
  1358. // language that also captures real annotations keeps both.
  1359. const mods = this.extractor?.extractModifiers?.(node);
  1360. if (mods && mods.length > 0) {
  1361. newNode.decorators = [...(newNode.decorators ?? []), ...mods];
  1362. }
  1363. this.nodes.push(newNode);
  1364. // Add containment edge from parent
  1365. if (this.nodeStack.length > 0) {
  1366. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1367. if (parentId) {
  1368. this.edges.push({
  1369. source: parentId,
  1370. target: id,
  1371. kind: 'contains',
  1372. });
  1373. }
  1374. }
  1375. if (this.valueRefsEnabled) this.captureValueRefScope(kind, name, id, node);
  1376. return newNode;
  1377. }
  1378. /**
  1379. * Find first named child whose type is in the given list.
  1380. * Used to locate inner type nodes (e.g. enum_specifier inside a typedef).
  1381. */
  1382. private findChildByTypes(node: SyntaxNode, types: string[]): SyntaxNode | null {
  1383. for (let i = 0; i < node.namedChildCount; i++) {
  1384. const child = node.namedChild(i);
  1385. if (child && types.includes(child.type)) return child;
  1386. }
  1387. return null;
  1388. }
  1389. /**
  1390. * Find a `packageTypes` child under the root, create a `namespace` node
  1391. * for it, and return its id so the caller can scope top-level
  1392. * declarations underneath. Returns null when no package header is
  1393. * present (script files, .kts without a package).
  1394. */
  1395. private extractFilePackage(rootNode: SyntaxNode): string | null {
  1396. const types = this.extractor?.packageTypes;
  1397. if (!types || types.length === 0 || !this.extractor?.extractPackage) return null;
  1398. let pkgNode: SyntaxNode | null = null;
  1399. for (let i = 0; i < rootNode.namedChildCount; i++) {
  1400. const child = rootNode.namedChild(i);
  1401. if (child && types.includes(child.type)) {
  1402. pkgNode = child;
  1403. break;
  1404. }
  1405. }
  1406. if (!pkgNode) return null;
  1407. const pkgName = this.extractor.extractPackage(pkgNode, this.source);
  1408. if (!pkgName) return null;
  1409. const ns = this.createNode('namespace', pkgName, pkgNode);
  1410. return ns?.id ?? null;
  1411. }
  1412. /**
  1413. * Qualified name for a method defined out-of-line via a receiver qualifier
  1414. * (`Type::method() {}`). The declarator spells the receiver RELATIVE to the
  1415. * enclosing namespace, so the active C++ namespace prefix must be composed
  1416. * in — `namespace sim { Output ManifestStartup::Apply() {} }` previously
  1417. * indexed as `ManifestStartup::Apply` while the class node carried
  1418. * `sim::ManifestStartup`, so qualified call sites
  1419. * (`sim::ManifestStartup::Apply(...)`) never resolved (#1291).
  1420. *
  1421. * The source may also re-spell part or all of the namespace path
  1422. * (`namespace sim { void sim::M::f() {} }` is legal), so the receiver is
  1423. * anchored at the first prefix segment it names: everything before that
  1424. * anchor is taken from the prefix, the receiver supplies the rest. A
  1425. * receiver naming no prefix segment gets the whole prefix prepended.
  1426. * `namespacePrefix` is only ever non-empty for C++, so every other
  1427. * receiver language (Go, Rust, Kotlin, Lua) passes through unchanged.
  1428. */
  1429. private composeReceiverQualifiedName(receiverType: string, name: string): string {
  1430. const base = `${receiverType}::${name}`;
  1431. if (this.namespacePrefix.length === 0) return base;
  1432. const receiverHead = receiverType.split('::')[0];
  1433. const anchor = this.namespacePrefix.indexOf(receiverHead!);
  1434. const prefix = anchor === -1 ? this.namespacePrefix : this.namespacePrefix.slice(0, anchor);
  1435. return prefix.length > 0 ? `${prefix.join('::')}::${base}` : base;
  1436. }
  1437. /**
  1438. * Build qualified name from node stack
  1439. */
  1440. private buildQualifiedName(name: string): string {
  1441. // Build a qualified name from the semantic hierarchy only (no file path).
  1442. // The file path is stored separately in filePath and pollutes FTS if included here.
  1443. // C/C++ enclosing namespaces prefix first (empty for every other language).
  1444. const parts: string[] = [...this.namespacePrefix];
  1445. for (const nodeId of this.nodeStack) {
  1446. const node = this.nodes.find((n) => n.id === nodeId);
  1447. if (node && node.kind !== 'file') {
  1448. parts.push(node.name);
  1449. }
  1450. }
  1451. parts.push(name);
  1452. return parts.join('::');
  1453. }
  1454. /**
  1455. * Build an ExtractorContext for passing to language-specific visitNode hooks.
  1456. */
  1457. private makeExtractorContext(): ExtractorContext {
  1458. // eslint-disable-next-line @typescript-eslint/no-this-alias
  1459. const self = this;
  1460. return {
  1461. createNode: (kind, name, node, extra) => self.createNode(kind, name, node, extra),
  1462. visitNode: (node) => self.visitNode(node),
  1463. visitFunctionBody: (body, functionId) => self.visitFunctionBody(body, functionId),
  1464. addUnresolvedReference: (ref) => self.unresolvedReferences.push(ref),
  1465. pushScope: (nodeId) => self.nodeStack.push(nodeId),
  1466. popScope: () => self.nodeStack.pop(),
  1467. get filePath() { return self.filePath; },
  1468. get source() { return self.source; },
  1469. get nodeStack() { return self.nodeStack; },
  1470. get nodes() { return self.nodes; },
  1471. };
  1472. }
  1473. /**
  1474. * Check if the current node stack indicates we are inside a class-like node
  1475. * (class, struct, union, interface, trait). File nodes do not count as class-like.
  1476. */
  1477. private isInsideClassLikeNode(): boolean {
  1478. if (this.nodeStack.length === 0) return false;
  1479. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1480. if (!parentId) return false;
  1481. const parentNode = this.nodes.find((n) => n.id === parentId);
  1482. if (!parentNode) return false;
  1483. return (
  1484. parentNode.kind === 'class' ||
  1485. parentNode.kind === 'struct' ||
  1486. parentNode.kind === 'union' ||
  1487. parentNode.kind === 'interface' ||
  1488. parentNode.kind === 'trait' ||
  1489. parentNode.kind === 'enum' ||
  1490. parentNode.kind === 'module'
  1491. );
  1492. }
  1493. /**
  1494. * Ruby `CONST = …` assignment whose LHS is a `constant` node — a class/module
  1495. * (or top-level) constant worth extracting as a symbol even inside a class.
  1496. * Other languages don't give an assignment a `constant`-typed LHS, so this
  1497. * gate is effectively Ruby-only.
  1498. */
  1499. private isClassScopeConstantAssignment(node: SyntaxNode): boolean {
  1500. if (node.type !== 'assignment') return false;
  1501. const left = getChildByField(node, 'left') ?? node.namedChild(0);
  1502. return left?.type === 'constant';
  1503. }
  1504. /**
  1505. * Extract a function
  1506. */
  1507. private extractFunction(node: SyntaxNode, nameOverride?: string): void {
  1508. if (!this.extractor) return;
  1509. // If the language provides getReceiverType and this function has a receiver
  1510. // (e.g., Rust function_item inside an impl block), extract as method instead
  1511. if (this.extractor.getReceiverType?.(node, this.source)) {
  1512. this.extractMethod(node);
  1513. return;
  1514. }
  1515. // nameOverride is supplied only for explicitly-named anonymous functions the
  1516. // caller resolved itself (e.g. arrow values of exported-const object members
  1517. // — SvelteKit actions). Inline-object arrows reached by the general walker
  1518. // get no override, so they still fall through to the <anonymous> skip below.
  1519. let name = nameOverride ?? extractName(node, this.source, this.extractor);
  1520. // A CommonJS export assignment names the function it holds — see below.
  1521. let commonJsExport = false;
  1522. // For arrow functions and function expressions assigned to variables,
  1523. // resolve the name from the parent variable_declarator.
  1524. // e.g. `export const useAuth = () => { ... }` — the arrow_function node
  1525. // has no `name` field; the name lives on the variable_declarator.
  1526. if (
  1527. !nameOverride &&
  1528. name === '<anonymous>' &&
  1529. (node.type === 'arrow_function' || node.type === 'function_expression' || node.type === 'generator_function')
  1530. ) {
  1531. const parent = node.parent;
  1532. if (parent?.type === 'variable_declarator') {
  1533. const varName = getChildByField(parent, 'name');
  1534. if (varName) {
  1535. name = getNodeText(varName, this.source);
  1536. }
  1537. } else if (parent?.type === 'assignment_expression') {
  1538. // `exports.getItems = async (req, res) => {…}` / `module.exports.x =
  1539. // function () {…}` — the CommonJS controller style. The function is
  1540. // anonymous only syntactically: the export property is the name every
  1541. // `router.get('/items', getItems)` resolves. Without a node the handler
  1542. // is invisible to callers/impact and its calls attribute to the file
  1543. // (#1675). Same treatment `const X = () => {}` already gets.
  1544. const exportName = this.commonJsExportName(parent, node);
  1545. if (exportName) {
  1546. name = exportName;
  1547. commonJsExport = true;
  1548. }
  1549. }
  1550. }
  1551. if (name === '<anonymous>') {
  1552. // Don't emit a node for the anonymous wrapper itself, but still visit its
  1553. // body: AMD/RequireJS and CommonJS module wrappers (`define([], function(){…})`,
  1554. // `(function(){…})()`) hold named inner functions and calls that would
  1555. // otherwise be lost — the dispatcher set skipChildren, so nothing else
  1556. // descends into this subtree. (#528)
  1557. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1558. ?? getChildByField(node, this.extractor.bodyField);
  1559. if (body) {
  1560. this.visitFunctionBody(body, '');
  1561. }
  1562. return;
  1563. }
  1564. // Check for misparse artifacts (e.g. C++ macros causing "namespace detail" functions)
  1565. // Skip the node but still visit the body for calls and structural nodes
  1566. if (this.extractor.isMisparsedFunction?.(name, node)) {
  1567. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1568. ?? getChildByField(node, this.extractor.bodyField);
  1569. if (body) {
  1570. this.visitFunctionBody(body, '');
  1571. }
  1572. return;
  1573. }
  1574. const docstring = getPrecedingDocstring(node, this.source);
  1575. const signature = this.extractor.getSignature?.(node, this.source);
  1576. const visibility = this.extractor.getVisibility?.(node);
  1577. const isExported = commonJsExport || this.extractor.isExported?.(node, this.source);
  1578. const isAsync = this.extractor.isAsync?.(node);
  1579. const isStatic = this.extractor.isStatic?.(node);
  1580. const returnType = this.extractor.getReturnType?.(node, this.source);
  1581. const funcNode = this.createNode('function', name, node, {
  1582. docstring,
  1583. signature,
  1584. visibility,
  1585. isExported,
  1586. isAsync,
  1587. isStatic,
  1588. returnType,
  1589. });
  1590. if (!funcNode) return;
  1591. // Extract type annotations (parameter types and return type)
  1592. this.extractTypeAnnotations(node, funcNode.id);
  1593. // Extract decorators applied to the function (rare in JS/TS but
  1594. // present in Python `@decorator def f():` and Java/Kotlin
  1595. // annotations on free functions).
  1596. this.extractDecoratorsFor(node, funcNode.id);
  1597. // Push to stack and visit body
  1598. this.nodeStack.push(funcNode.id);
  1599. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1600. ?? getChildByField(node, this.extractor.bodyField);
  1601. if (body) {
  1602. this.visitFunctionBody(body, funcNode.id);
  1603. }
  1604. this.nodeStack.pop();
  1605. }
  1606. /**
  1607. * Detect a React component declared via an HOC wrapper whose result is itself a
  1608. * component: `forwardRef(...)`, `memo(...)`, `React.forwardRef/memo(...)`, and
  1609. * styled-components / emotion `styled.tag\`…\`` / `styled(Base)\`…\``. These
  1610. * initializers are a call / tagged-template (not a bare arrow), so the const is
  1611. * otherwise classified `constant` — and a constant is skipped by both the
  1612. * JSX-render edge synthesizer and component resolution, so `<Button/>` usages
  1613. * get no edge and callers/impact silently return empty (#841).
  1614. *
  1615. * Returns `{ inner }` — the inline render function to extract as the component
  1616. * body, or `null` when the wrapper has no inline function (`memo(Imported)`,
  1617. * `styled.button\`…\``) and only a bodyless component node is minted — or
  1618. * `undefined` when this initializer is not a recognized component wrapper.
  1619. */
  1620. private reactComponentHoc(valueNode: SyntaxNode): { inner: SyntaxNode | null } | undefined {
  1621. if (valueNode.type !== 'call_expression') return undefined;
  1622. const callee = getChildByField(valueNode, 'function');
  1623. if (!callee) return undefined;
  1624. const calleeText = getNodeText(callee, this.source);
  1625. // styled-components / emotion: `styled.button\`…\`` / `styled(Base)\`…\``.
  1626. // tree-sitter models these tagged templates as a call_expression whose callee
  1627. // is the `styled.x` / `styled(Base)` tag (\b avoids matching `styledFoo`).
  1628. // No inline render fn — the argument is the CSS template.
  1629. if (/^styled\b/.test(calleeText)) return { inner: null };
  1630. // React HOCs: `forwardRef`/`memo`/`React.forwardRef`/`React.memo`.
  1631. if (!REACT_COMPONENT_HOCS.has(calleeText)) return undefined;
  1632. // The first arrow / function-expression argument is the render fn (if inline;
  1633. // `memo(Imported)` passes a bare identifier and has none).
  1634. const args = getChildByField(valueNode, 'arguments');
  1635. let inner: SyntaxNode | null = null;
  1636. if (args) {
  1637. for (let i = 0; i < args.namedChildCount; i++) {
  1638. const a = args.namedChild(i);
  1639. if (a && (a.type === 'arrow_function' || a.type === 'function_expression')) {
  1640. inner = a;
  1641. break;
  1642. }
  1643. }
  1644. }
  1645. return { inner };
  1646. }
  1647. /**
  1648. * Emit a `component` node for an HOC-wrapped React component declaration (see
  1649. * reactComponentHoc). Named by the declarator (`Button`) and located at it so
  1650. * the node range spans the body. When the wrapper has an inline render
  1651. * function, its body is walked so the component's callees (hooks, helpers) are
  1652. * captured under the component node — matching how a plain
  1653. * `const Foo = () => …` arrow component already behaves.
  1654. */
  1655. private extractReactComponentNode(
  1656. name: string,
  1657. declarator: SyntaxNode,
  1658. innerFn: SyntaxNode | null,
  1659. extra: { docstring?: string; signature?: string; isExported?: boolean }
  1660. ): void {
  1661. const compNode = this.createNode('component', name, declarator, extra);
  1662. if (!compNode || !innerFn || !this.extractor) return;
  1663. this.nodeStack.push(compNode.id);
  1664. const body = this.extractor.resolveBody?.(innerFn, this.extractor.bodyField)
  1665. ?? getChildByField(innerFn, this.extractor.bodyField);
  1666. if (body) this.visitFunctionBody(body, compNode.id);
  1667. this.nodeStack.pop();
  1668. }
  1669. /**
  1670. * Extract a class
  1671. */
  1672. private extractClass(node: SyntaxNode, kind: NodeKind = 'class'): void {
  1673. if (!this.extractor) return;
  1674. // Skip forward declarations / elaborated type references (`class Foo;`) in
  1675. // languages that opt in — bodiless there means "not a definition", so it
  1676. // would otherwise mint a phantom node competing with the real definition
  1677. // (#1093). Languages where a bodiless class is complete (Kotlin, Scala)
  1678. // leave the flag unset. Resolved once here and reused for the body walk.
  1679. const resolvedBody = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1680. ?? getChildByField(node, this.extractor.bodyField);
  1681. if (this.extractor.skipBodilessClass && !resolvedBody) return;
  1682. const name = extractName(node, this.source, this.extractor);
  1683. const docstring = getPrecedingDocstring(node, this.source);
  1684. const visibility = this.extractor.getVisibility?.(node);
  1685. const isExported = this.extractor.isExported?.(node, this.source);
  1686. const classNode = this.createNode(kind, name, node, {
  1687. docstring,
  1688. visibility,
  1689. isExported,
  1690. });
  1691. if (!classNode) return;
  1692. // Extract extends/implements
  1693. this.extractInheritance(node, classNode.id);
  1694. // C# primary-constructor parameter dependencies (`class Svc(IRepo r, …)`).
  1695. this.extractCsharpPrimaryCtorParamRefs(node, classNode.id);
  1696. // Extract decorators applied to the class (`@Foo class X {}`).
  1697. this.extractDecoratorsFor(node, classNode.id);
  1698. // Push to stack and visit body
  1699. this.nodeStack.push(classNode.id);
  1700. const body = resolvedBody ?? node;
  1701. // Visit all children for methods and properties
  1702. for (let i = 0; i < body.namedChildCount; i++) {
  1703. const child = body.namedChild(i);
  1704. if (child) {
  1705. this.visitNode(child);
  1706. }
  1707. }
  1708. // Synthesize compile-time-generated members (Lombok accessors, #912). Runs
  1709. // after the body so the hook can dedup against hand-written members, and
  1710. // while the class is still on the stack so containment/QNs attach.
  1711. if (this.extractor.synthesizeMembers) {
  1712. this.extractor.synthesizeMembers(node, this.makeExtractorContext());
  1713. }
  1714. this.nodeStack.pop();
  1715. }
  1716. /**
  1717. * Extract a method
  1718. */
  1719. private extractMethod(node: SyntaxNode): void {
  1720. if (!this.extractor) return;
  1721. // For languages with receiver types (Go, Rust), include receiver in qualified name
  1722. // so FTS can match "scrapeLoop.run" → qualified_name "...::scrapeLoop::run"
  1723. const receiverType = this.extractor.getReceiverType?.(node, this.source);
  1724. // For most languages, only extract as method if inside a class-like node
  1725. // Languages with methodsAreTopLevel (e.g. Go) always treat them as methods
  1726. // Languages with getReceiverType (e.g. Rust) extract as method when receiver is found
  1727. if (!this.isInsideClassLikeNode() && !this.extractor.methodsAreTopLevel && !receiverType) {
  1728. // Skip method_definition nodes inside object literals (getters/setters/methods
  1729. // in inline objects). These are ephemeral and create noise (e.g., Svelte context
  1730. // objects: `ctx.set({ get view() { ... } })`).
  1731. if (node.parent?.type === 'object' || node.parent?.type === 'object_expression') {
  1732. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1733. ?? getChildByField(node, this.extractor.bodyField);
  1734. if (body) {
  1735. this.visitFunctionBody(body, '');
  1736. }
  1737. return;
  1738. }
  1739. // Not inside a class-like node and no receiver type, treat as function
  1740. this.extractFunction(node);
  1741. return;
  1742. }
  1743. const name = extractName(node, this.source, this.extractor);
  1744. // Check for misparse artifacts (e.g. C++ "switch" inside macro-confused class body)
  1745. if (this.extractor.isMisparsedFunction?.(name, node)) {
  1746. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1747. ?? getChildByField(node, this.extractor.bodyField);
  1748. if (body) {
  1749. this.visitFunctionBody(body, '');
  1750. }
  1751. return;
  1752. }
  1753. const docstring = getPrecedingDocstring(node, this.source);
  1754. const signature = this.extractor.getSignature?.(node, this.source);
  1755. const visibility = this.extractor.getVisibility?.(node);
  1756. const isAsync = this.extractor.isAsync?.(node);
  1757. const isStatic = this.extractor.isStatic?.(node);
  1758. // Only persist abstract when true — a false return must not mint `isAbstract: false`
  1759. // on every ordinary method (breaks kernel↔wasm parity JSON equality).
  1760. const isAbstract = this.extractor.isAbstract?.(node) ? true : undefined;
  1761. const returnType = this.extractor.getReturnType?.(node, this.source);
  1762. const extraProps: Partial<Node> = {
  1763. docstring,
  1764. signature,
  1765. visibility,
  1766. isAsync,
  1767. isStatic,
  1768. isAbstract,
  1769. returnType,
  1770. };
  1771. if (receiverType) {
  1772. extraProps.qualifiedName = this.composeReceiverQualifiedName(receiverType, name);
  1773. }
  1774. const methodNode = this.createNode('method', name, node, extraProps);
  1775. if (!methodNode) return;
  1776. // For methods with a receiver type but no class-like parent on the stack
  1777. // (e.g., Rust impl blocks), add a contains edge from the owning struct/trait
  1778. if (receiverType && !this.isInsideClassLikeNode()) {
  1779. const ownerNode = this.nodes.find(
  1780. (n) =>
  1781. n.name === receiverType &&
  1782. n.filePath === this.filePath &&
  1783. (n.kind === 'struct' || n.kind === 'union' || n.kind === 'class' || n.kind === 'enum' || n.kind === 'trait')
  1784. );
  1785. if (ownerNode) {
  1786. this.edges.push({
  1787. source: ownerNode.id,
  1788. target: methodNode.id,
  1789. kind: 'contains',
  1790. });
  1791. }
  1792. }
  1793. // Extract type annotations (parameter types and return type)
  1794. this.extractTypeAnnotations(node, methodNode.id);
  1795. // Extract decorators (`@Get('/list') list() {}`).
  1796. this.extractDecoratorsFor(node, methodNode.id);
  1797. // Push to stack and visit body
  1798. this.nodeStack.push(methodNode.id);
  1799. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1800. ?? getChildByField(node, this.extractor.bodyField);
  1801. if (body) {
  1802. this.visitFunctionBody(body, methodNode.id);
  1803. }
  1804. this.nodeStack.pop();
  1805. }
  1806. /**
  1807. * Extract an interface/protocol/trait
  1808. */
  1809. private extractInterface(node: SyntaxNode): void {
  1810. if (!this.extractor) return;
  1811. const name = extractName(node, this.source, this.extractor);
  1812. const docstring = getPrecedingDocstring(node, this.source);
  1813. const isExported = this.extractor.isExported?.(node, this.source);
  1814. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  1815. const interfaceNode = this.createNode(kind, name, node, {
  1816. docstring,
  1817. isExported,
  1818. });
  1819. if (!interfaceNode) return;
  1820. // Extract extends (interface inheritance)
  1821. this.extractInheritance(node, interfaceNode.id);
  1822. // Visit body children for interface methods and nested types
  1823. this.nodeStack.push(interfaceNode.id);
  1824. let body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1825. ?? getChildByField(node, this.extractor.bodyField);
  1826. if (!body) body = node;
  1827. for (let i = 0; i < body.namedChildCount; i++) {
  1828. const child = body.namedChild(i);
  1829. if (child) {
  1830. this.visitNode(child);
  1831. }
  1832. }
  1833. this.nodeStack.pop();
  1834. }
  1835. /**
  1836. * Extract a struct
  1837. */
  1838. private extractStruct(node: SyntaxNode): void {
  1839. this.extractAggregate(node, 'struct');
  1840. }
  1841. /** Extract a union while sharing the member-walk behavior of aggregate types. */
  1842. private extractUnion(node: SyntaxNode): void {
  1843. this.extractAggregate(node, 'union');
  1844. }
  1845. /** Extract a struct-like declaration without conflating its semantic kind. */
  1846. private extractAggregate(node: SyntaxNode, kind: 'struct' | 'union'): void {
  1847. if (!this.extractor) return;
  1848. // Skip forward declarations and type references (no body = not a definition)
  1849. // — EXCEPT C# positional records (`record struct M(decimal Amount);`),
  1850. // complete definitions with no body block. (#831)
  1851. //
  1852. // `allowBodilessStruct` is the per-language escape hatch for the same
  1853. // situation: a bodiless struct that IS a complete definition (Rust's unit
  1854. // struct `struct Unit;`). Opposite polarity from `skipBodilessClass`
  1855. // (#1093) because the two defaults differ — a bodiless CLASS is kept
  1856. // unless a language opts into skipping, a bodiless STRUCT is skipped
  1857. // unless a language opts into keeping.
  1858. const body = getChildByField(node, this.extractor.bodyField);
  1859. if (!body && node.type !== 'record_declaration' && !this.extractor.allowBodilessStruct)
  1860. return;
  1861. const name = extractName(node, this.source, this.extractor);
  1862. const docstring = getPrecedingDocstring(node, this.source);
  1863. const visibility = this.extractor.getVisibility?.(node);
  1864. const isExported = this.extractor.isExported?.(node, this.source);
  1865. const aggregateNode = this.createNode(kind, name, node, {
  1866. docstring,
  1867. visibility,
  1868. isExported,
  1869. });
  1870. if (!aggregateNode) return;
  1871. // Extract inheritance (e.g. Swift: struct HTTPMethod: RawRepresentable)
  1872. this.extractInheritance(node, aggregateNode.id);
  1873. // C# primary-constructor parameter dependencies (`struct P(int x)`, and
  1874. // `record struct M(decimal Amount)` which the grammar nests here).
  1875. this.extractCsharpPrimaryCtorParamRefs(node, aggregateNode.id);
  1876. // Push to stack for field extraction (bodiless positional records have
  1877. // no members to visit)
  1878. if (body) {
  1879. this.nodeStack.push(aggregateNode.id);
  1880. for (let i = 0; i < body.namedChildCount; i++) {
  1881. const child = body.namedChild(i);
  1882. if (child) {
  1883. this.visitNode(child);
  1884. }
  1885. }
  1886. this.nodeStack.pop();
  1887. }
  1888. }
  1889. /**
  1890. * Extract an enum
  1891. */
  1892. private extractEnum(node: SyntaxNode): void {
  1893. if (!this.extractor) return;
  1894. // Skip forward declarations and type references (no body = not a definition)
  1895. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1896. ?? getChildByField(node, this.extractor.bodyField);
  1897. if (!body) return;
  1898. const name = extractName(node, this.source, this.extractor);
  1899. const docstring = getPrecedingDocstring(node, this.source);
  1900. const visibility = this.extractor.getVisibility?.(node);
  1901. const isExported = this.extractor.isExported?.(node, this.source);
  1902. const enumNode = this.createNode('enum', name, node, {
  1903. docstring,
  1904. visibility,
  1905. isExported,
  1906. });
  1907. if (!enumNode) return;
  1908. // Extract inheritance (e.g. Swift: enum AFError: Error)
  1909. this.extractInheritance(node, enumNode.id);
  1910. // Push to stack and visit body children (enum members, nested types, methods)
  1911. this.nodeStack.push(enumNode.id);
  1912. const memberTypes = this.extractor.enumMemberTypes;
  1913. for (let i = 0; i < body.namedChildCount; i++) {
  1914. const child = body.namedChild(i);
  1915. if (!child) continue;
  1916. if (memberTypes?.includes(child.type)) {
  1917. this.extractEnumMembers(child);
  1918. } else {
  1919. this.visitNode(child);
  1920. }
  1921. }
  1922. this.nodeStack.pop();
  1923. }
  1924. /**
  1925. * Extract enum member names from an enum member node.
  1926. * Handles multi-case declarations (Swift: `case put, delete`) and single-case patterns.
  1927. */
  1928. private extractEnumMembers(node: SyntaxNode): void {
  1929. // Try field-based name first (e.g. Rust enum_variant has a 'name' field)
  1930. const nameNode = getChildByField(node, 'name');
  1931. if (nameNode) {
  1932. this.createNode('enum_member', getNodeText(nameNode, this.source), node);
  1933. return;
  1934. }
  1935. // Check for identifier-like children (Swift: simple_identifier, TS: property_identifier)
  1936. let found = false;
  1937. for (let i = 0; i < node.namedChildCount; i++) {
  1938. const child = node.namedChild(i);
  1939. if (child && (child.type === 'simple_identifier' || child.type === 'identifier' || child.type === 'property_identifier')) {
  1940. this.createNode('enum_member', getNodeText(child, this.source), child);
  1941. found = true;
  1942. }
  1943. }
  1944. // If the node itself IS the identifier (e.g. TS property_identifier directly in enum body)
  1945. if (!found && node.namedChildCount === 0) {
  1946. this.createNode('enum_member', getNodeText(node, this.source), node);
  1947. }
  1948. }
  1949. /**
  1950. * Extract a class property declaration (e.g. C# `public string Name { get; set; }`).
  1951. * Extracts as 'property' kind node inside the owning class.
  1952. */
  1953. private extractProperty(node: SyntaxNode): Node | null {
  1954. if (!this.extractor) return null;
  1955. const docstring = getPrecedingDocstring(node, this.source);
  1956. const visibility = this.extractor.getVisibility?.(node);
  1957. const isStatic = this.extractor.isStatic?.(node) ?? false;
  1958. const hookName = this.extractor.extractPropertyName?.(node, this.source);
  1959. // JS `field_definition` names its key the `property` field (TS uses
  1960. // `name`) — try both before the generic identifier scan (#808).
  1961. const nameNode = hookName
  1962. ? null
  1963. : getChildByField(node, 'name') ||
  1964. getChildByField(node, 'property') ||
  1965. node.namedChildren.find(c => c.type === 'identifier');
  1966. const name = hookName ?? (nameNode ? getNodeText(nameNode, this.source) : null);
  1967. if (!name) return null;
  1968. // Get property type. TS/JS field definitions carry an explicit `type`
  1969. // field (a `type_annotation`); their other named children are the name
  1970. // and the initializer VALUE, which the generic finder below would
  1971. // wrongly pick — so fields use the type field only (#808). Other
  1972. // languages (C# property_declaration) keep the generic scan.
  1973. //
  1974. // A `property_signature` (an interface member, #1638) carries a `type`
  1975. // field and no value, so it reads the type field too. It cannot take the
  1976. // generic scan: that scan's exclusion list covers `identifier` but not the
  1977. // `property_identifier` an interface member is named with, so it stops on
  1978. // the name and `interface Stats { counts: Record<string, number> }` yields
  1979. // `signature: "counts counts"` instead of the type. Named explicitly
  1980. // rather than folded into the field test so no other language's
  1981. // `property_declaration` moves off the generic scan.
  1982. const isTsJsField =
  1983. node.type === 'public_field_definition' || node.type === 'field_definition'
  1984. || node.type === 'property_signature';
  1985. const typeNode = isTsJsField
  1986. ? getChildByField(node, 'type')
  1987. : node.namedChildren.find(
  1988. c => c.type !== 'modifier' && c.type !== 'modifiers'
  1989. && c.type !== 'identifier' && c.type !== 'accessor_list'
  1990. && c.type !== 'accessors' && c.type !== 'equals_value_clause'
  1991. );
  1992. const typeText = typeNode
  1993. ? getNodeText(typeNode, this.source).replace(/^:\s*/, '')
  1994. : undefined;
  1995. const signature = typeText ? `${typeText} ${name}` : name;
  1996. const propNode = this.createNode('property', name, node, {
  1997. docstring,
  1998. signature,
  1999. visibility,
  2000. isStatic,
  2001. });
  2002. // `@Inject() private svc: Foo` and similar — capture the
  2003. // decorator->target relationship for class properties too.
  2004. if (propNode) {
  2005. this.extractDecoratorsFor(node, propNode.id);
  2006. // Emit `references` edges from the property to types named in its
  2007. // type annotation (#381). The generic walker handles TS-style
  2008. // `type_annotation` children; the C# branch walks the `type` field.
  2009. this.extractTypeAnnotations(node, propNode.id);
  2010. }
  2011. return propNode;
  2012. }
  2013. /**
  2014. * Extract a class field declaration (e.g. Java field_declaration, C# field_declaration).
  2015. * Extracts each declarator as a 'field' kind node inside the owning class.
  2016. */
  2017. private extractField(node: SyntaxNode): void {
  2018. if (!this.extractor) return;
  2019. const docstring = getPrecedingDocstring(node, this.source);
  2020. const visibility = this.extractor.getVisibility?.(node);
  2021. const isStatic = this.extractor.isStatic?.(node) ?? false;
  2022. // A class field that is actually a CONSTANT (Java `static final`, C# `const`
  2023. // / `static readonly`) is extracted as `constant` kind, not `field`, so
  2024. // value-reference edges treat it as a target (the gate accepts
  2025. // constant/variable, not field). Scoped to languages whose `isConst`
  2026. // predicate is field-shaped — other languages' fields stay `field`.
  2027. const fieldKind: NodeKind =
  2028. (this.language === 'java' || this.language === 'csharp') &&
  2029. (this.extractor.isConst?.(node) ?? false)
  2030. ? 'constant'
  2031. : 'field';
  2032. // Java field_declaration: "private final String name = value;" → variable_declarator(s) are direct children
  2033. // C# field_declaration: wraps in variable_declaration → variable_declarator(s)
  2034. let declarators = node.namedChildren.filter(
  2035. c => c.type === 'variable_declarator'
  2036. );
  2037. // C#: look inside variable_declaration wrapper
  2038. if (declarators.length === 0) {
  2039. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  2040. if (varDecl) {
  2041. declarators = varDecl.namedChildren.filter(c => c.type === 'variable_declarator');
  2042. }
  2043. }
  2044. // PHP property_declaration: property_element → variable_name → name
  2045. if (declarators.length === 0) {
  2046. const propElements = node.namedChildren.filter(c => c.type === 'property_element');
  2047. if (propElements.length > 0) {
  2048. // Get type annotation if present (e.g. "string", "int", "?Foo")
  2049. const typeNode = node.namedChildren.find(
  2050. c => c.type !== 'visibility_modifier' && c.type !== 'static_modifier'
  2051. && c.type !== 'readonly_modifier' && c.type !== 'property_element'
  2052. && c.type !== 'var_modifier'
  2053. );
  2054. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  2055. for (const elem of propElements) {
  2056. const varName = elem.namedChildren.find(c => c.type === 'variable_name');
  2057. const nameNode = varName?.namedChildren.find(c => c.type === 'name');
  2058. if (!nameNode) continue;
  2059. const name = getNodeText(nameNode, this.source);
  2060. const signature = typeText ? `${typeText} $${name}` : `$${name}`;
  2061. this.createNode('field', name, elem, {
  2062. docstring,
  2063. signature,
  2064. visibility,
  2065. isStatic,
  2066. });
  2067. }
  2068. return;
  2069. }
  2070. }
  2071. if (declarators.length > 0) {
  2072. // Get field type from the type child
  2073. // Java: type is a direct child of field_declaration
  2074. // C#: type is inside variable_declaration wrapper
  2075. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  2076. const typeSearchNode = varDecl ?? node;
  2077. const typeNode = typeSearchNode.namedChildren.find(
  2078. c => c.type !== 'modifiers' && c.type !== 'modifier' && c.type !== 'variable_declarator'
  2079. && c.type !== 'variable_declaration' && c.type !== 'marker_annotation' && c.type !== 'annotation'
  2080. );
  2081. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  2082. for (const decl of declarators) {
  2083. const nameNode = getChildByField(decl, 'name')
  2084. || decl.namedChildren.find(c => c.type === 'identifier');
  2085. if (!nameNode) continue;
  2086. const name = getNodeText(nameNode, this.source);
  2087. const signature = typeText ? `${typeText} ${name}` : name;
  2088. const fieldNode = this.createNode(fieldKind, name, decl, {
  2089. docstring,
  2090. signature,
  2091. visibility,
  2092. isStatic,
  2093. });
  2094. // Java/Kotlin annotations / TS field decorators sit on the
  2095. // outer field_declaration, not on the individual declarator.
  2096. if (fieldNode) {
  2097. this.extractDecoratorsFor(node, fieldNode.id);
  2098. // Same as properties: emit `references` to the field's annotated
  2099. // type. The outer `field_declaration` is the right scope to
  2100. // search from — C# carries the `type` inside `variable_declaration`
  2101. // and the language-aware path in `extractTypeAnnotations` descends
  2102. // into that wrapper (#381).
  2103. this.extractTypeAnnotations(node, fieldNode.id);
  2104. }
  2105. }
  2106. } else {
  2107. // Fallback: try to find an identifier child directly
  2108. const nameNode = getChildByField(node, 'name')
  2109. || node.namedChildren.find(c => c.type === 'identifier');
  2110. if (nameNode) {
  2111. const name = getNodeText(nameNode, this.source);
  2112. this.createNode(fieldKind, name, node, {
  2113. docstring,
  2114. visibility,
  2115. isStatic,
  2116. });
  2117. }
  2118. }
  2119. }
  2120. /**
  2121. * Extract function-valued properties of an object literal as named function
  2122. * nodes (named by their property key). Shared by the two object-of-functions
  2123. * shapes in extractVariable: the object as a direct const value, and the
  2124. * object returned by a store-initializer call. Handles both `key: () => {}` /
  2125. * `key: function() {}` pairs and method shorthand `key() {}`.
  2126. */
  2127. private extractObjectLiteralFunctions(obj: SyntaxNode): void {
  2128. for (let i = 0; i < obj.namedChildCount; i++) {
  2129. const member = obj.namedChild(i);
  2130. if (!member) continue;
  2131. if (member.type === 'pair') {
  2132. const key = getChildByField(member, 'key');
  2133. const value = getChildByField(member, 'value');
  2134. if (key && value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
  2135. this.extractFunction(value, this.objectKeyName(key));
  2136. }
  2137. } else if (member.type === 'method_definition') {
  2138. // Method shorthand: `{ fetchUser() {...} }`. extractMethod deliberately
  2139. // skips object-literal methods, so route through extractFunction with an
  2140. // explicit name (method_definition exposes a `body` field, so resolveBody
  2141. // falls through to it and the node spans the full method).
  2142. const key = getChildByField(member, 'name');
  2143. if (key) this.extractFunction(member, this.objectKeyName(key));
  2144. }
  2145. }
  2146. }
  2147. /**
  2148. * A top-level binding exported by a LATER statement rather than at its
  2149. * declaration: `export default NAME`, `export { NAME }`, `export { NAME as
  2150. * default }`. The declaration's own `isExported` (an `export_statement`
  2151. * ancestor) cannot see these, so a store written as `const useStore =
  2152. * create(…)` + `export default useStore` read as unexported and its actions
  2153. * were never extracted. One anchored regex over the file source; JS-family
  2154. * callers only.
  2155. */
  2156. private isExportedLater(name: string): boolean {
  2157. if (!/^[A-Za-z_$][\w$]*$/.test(name)) return false;
  2158. const re = new RegExp(
  2159. `^[ \\t]*export\\s+(?:default\\s+${name}\\s*;?[ \\t]*$|\\{[^}]*\\b${name}\\b[^}]*\\})`,
  2160. 'm'
  2161. );
  2162. return re.test(this.source);
  2163. }
  2164. /** Property-key text with surrounding quotes stripped (`'foo'` → `foo`). */
  2165. private objectKeyName(key: SyntaxNode): string {
  2166. return getNodeText(key, this.source).replace(/^['"`]|['"`]$/g, '');
  2167. }
  2168. /**
  2169. * Given a `call_expression` initializer (`create((set, get) => ({...}))`),
  2170. * find the object literal RETURNED by a function argument — descending through
  2171. * nested call_expression arguments so middleware wrappers are unwrapped
  2172. * (`create(persist((set, get) => ({...}), {...}))`, devtools, immer,
  2173. * subscribeWithSelector). Returns null when no such object is found — the
  2174. * common case for ordinary call initializers — so this stays cheap and silent
  2175. * rather than guessing. Keyed purely on AST shape; no library names.
  2176. */
  2177. private findInitializerReturnedObject(callNode: SyntaxNode, depth = 0): SyntaxNode | null {
  2178. if (depth > 4) return null;
  2179. const args = getChildByField(callNode, 'arguments');
  2180. if (!args) return null;
  2181. for (let i = 0; i < args.namedChildCount; i++) {
  2182. const arg = args.namedChild(i);
  2183. if (!arg) continue;
  2184. if (arg.type === 'arrow_function' || arg.type === 'function_expression') {
  2185. const obj = this.functionReturnedObject(arg);
  2186. if (obj) return obj;
  2187. } else if (arg.type === 'call_expression') {
  2188. const obj = this.findInitializerReturnedObject(arg, depth + 1);
  2189. if (obj) return obj;
  2190. }
  2191. }
  2192. return null;
  2193. }
  2194. /**
  2195. * The object literal a function expression returns — either the `=> ({...})`
  2196. * arrow form (a parenthesized_expression wrapping an object) or a
  2197. * `=> { return {...} }` block. Returns null for any other body shape.
  2198. */
  2199. private functionReturnedObject(fnNode: SyntaxNode): SyntaxNode | null {
  2200. const body = getChildByField(fnNode, 'body');
  2201. if (!body) return null;
  2202. const asObject = (n: SyntaxNode | null): SyntaxNode | null => {
  2203. if (!n) return null;
  2204. if (n.type === 'object' || n.type === 'object_expression') return n;
  2205. if (n.type === 'parenthesized_expression') {
  2206. for (let i = 0; i < n.namedChildCount; i++) {
  2207. const inner = asObject(n.namedChild(i));
  2208. if (inner) return inner;
  2209. }
  2210. }
  2211. return null;
  2212. };
  2213. // `(set, get) => ({...})` — body is the (parenthesized) object directly.
  2214. const direct = asObject(body);
  2215. if (direct) return direct;
  2216. // `(set, get) => { return {...} }` — scan top-level return statements.
  2217. if (body.type === 'statement_block') {
  2218. for (let i = 0; i < body.namedChildCount; i++) {
  2219. const stmt = body.namedChild(i);
  2220. if (stmt?.type !== 'return_statement') continue;
  2221. for (let j = 0; j < stmt.namedChildCount; j++) {
  2222. const obj = asObject(stmt.namedChild(j));
  2223. if (obj) return obj;
  2224. }
  2225. }
  2226. }
  2227. return null;
  2228. }
  2229. /**
  2230. * RTK Query: from a `createApi({ ..., endpoints: build => ({...}) })` or a
  2231. * `baseApi.injectEndpoints({ endpoints: build => ({...}) })` call initializer,
  2232. * return the object literal of endpoint definitions (the object the `endpoints`
  2233. * arrow returns). Returns null for any other call — the common case — so this
  2234. * stays cheap and silent. Keyed on the RTK entry-point names (`createApi` /
  2235. * `injectEndpoints`) like the framework extractors key on their library APIs.
  2236. */
  2237. private findRtkEndpointsObject(callNode: SyntaxNode): SyntaxNode | null {
  2238. const callee = getChildByField(callNode, 'function');
  2239. if (!callee) return null;
  2240. const calleeName =
  2241. callee.type === 'identifier'
  2242. ? getNodeText(callee, this.source)
  2243. : callee.type === 'member_expression'
  2244. ? getNodeText(getChildByField(callee, 'property') ?? callee, this.source)
  2245. : '';
  2246. if (calleeName !== 'createApi' && calleeName !== 'injectEndpoints') return null;
  2247. const args = getChildByField(callNode, 'arguments');
  2248. if (!args) return null;
  2249. for (let i = 0; i < args.namedChildCount; i++) {
  2250. const arg = args.namedChild(i);
  2251. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2252. for (let j = 0; j < arg.namedChildCount; j++) {
  2253. const member = arg.namedChild(j);
  2254. // Two equally-common spellings: `endpoints: build => ({...})` (pair with an
  2255. // arrow value) and `endpoints(build) { return {...} }` (method shorthand).
  2256. if (member?.type === 'pair') {
  2257. const key = getChildByField(member, 'key');
  2258. if (!key || getNodeText(key, this.source) !== 'endpoints') continue;
  2259. const value = getChildByField(member, 'value');
  2260. if (value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
  2261. return this.functionReturnedObject(value);
  2262. }
  2263. } else if (member?.type === 'method_definition') {
  2264. const key = getChildByField(member, 'name');
  2265. if (!key || getNodeText(key, this.source) !== 'endpoints') continue;
  2266. return this.functionReturnedObject(member);
  2267. }
  2268. }
  2269. }
  2270. return null;
  2271. }
  2272. /**
  2273. * Extract each RTK Query endpoint (`getX: build.query({...})` / `build.mutation`)
  2274. * as a function node named by the endpoint key, spanning its primary handler
  2275. * (the `queryFn`/`query` arrow) so the fetch logic's calls attribute to the
  2276. * endpoint. Without this an endpoint exists only as an object-literal property —
  2277. * never a node — so the generated `useXQuery` hook can't be bridged to it.
  2278. */
  2279. private extractRtkEndpoints(obj: SyntaxNode): void {
  2280. for (let i = 0; i < obj.namedChildCount; i++) {
  2281. const member = obj.namedChild(i);
  2282. if (member?.type !== 'pair') continue;
  2283. const key = getChildByField(member, 'key');
  2284. const value = getChildByField(member, 'value');
  2285. if (!key || value?.type !== 'call_expression') continue;
  2286. // The value must be a builder dispatch `<builder>.query|mutation(...)`.
  2287. const callee = getChildByField(value, 'function');
  2288. if (callee?.type !== 'member_expression') continue;
  2289. const method = getNodeText(getChildByField(callee, 'property') ?? callee, this.source);
  2290. if (method !== 'query' && method !== 'mutation' && method !== 'infiniteQuery') continue;
  2291. const handler = this.rtkEndpointHandler(value);
  2292. if (handler) {
  2293. this.extractFunction(handler, this.objectKeyName(key));
  2294. } else {
  2295. // Factory / config-only handler (`queryFn: makeQueryFn(url)`): no function
  2296. // literal to name. Mint a bare endpoint node spanning the builder call so
  2297. // the generated hook still bridges to it, and walk the call so its handler
  2298. // factory (and any inline transform) is captured as an outgoing edge.
  2299. const epNode = this.createNode('function', this.objectKeyName(key), value, {
  2300. signature: getNodeText(value, this.source).slice(0, 80),
  2301. });
  2302. if (epNode) {
  2303. this.nodeStack.push(epNode.id);
  2304. this.visitFunctionBody(value, epNode.id);
  2305. this.nodeStack.pop();
  2306. }
  2307. }
  2308. }
  2309. }
  2310. /**
  2311. * The primary handler arrow of a `build.query({ queryFn|query: (…) => … })`
  2312. * endpoint — prefers `queryFn`, then `query`, else the first function-valued
  2313. * property. Returns null when the endpoint is config-only (no handler arrow).
  2314. */
  2315. private rtkEndpointHandler(callNode: SyntaxNode): SyntaxNode | null {
  2316. const args = getChildByField(callNode, 'arguments');
  2317. if (!args) return null;
  2318. for (let i = 0; i < args.namedChildCount; i++) {
  2319. const arg = args.namedChild(i);
  2320. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2321. let queryFn: SyntaxNode | null = null;
  2322. let query: SyntaxNode | null = null;
  2323. let firstFn: SyntaxNode | null = null;
  2324. for (let j = 0; j < arg.namedChildCount; j++) {
  2325. const member = arg.namedChild(j);
  2326. // The handler may be `queryFn: () => …` / `query: () => …` (pair) or the
  2327. // method-shorthand `query(arg) { … }` / `queryFn(arg) { … }`.
  2328. let fn: SyntaxNode | null = null;
  2329. let kn = '';
  2330. if (member?.type === 'pair') {
  2331. const v = getChildByField(member, 'value');
  2332. if (v?.type === 'arrow_function' || v?.type === 'function_expression') {
  2333. fn = v;
  2334. const k = getChildByField(member, 'key');
  2335. kn = k ? getNodeText(k, this.source) : '';
  2336. }
  2337. } else if (member?.type === 'method_definition') {
  2338. fn = member;
  2339. const k = getChildByField(member, 'name');
  2340. kn = k ? getNodeText(k, this.source) : '';
  2341. }
  2342. if (!fn) continue;
  2343. if (kn === 'queryFn') queryFn = fn;
  2344. else if (kn === 'query') query = fn;
  2345. if (!firstFn) firstFn = fn;
  2346. }
  2347. if (queryFn) return queryFn;
  2348. if (query) return query;
  2349. if (firstFn) return firstFn;
  2350. }
  2351. return null;
  2352. }
  2353. /**
  2354. * RTK Query generated-hook bindings. `export const { useGetXQuery,
  2355. * useUpdateYMutation } = someApi` destructures the hooks RTK generates per
  2356. * endpoint off a createApi result. They are real exported symbols that
  2357. * components import, but destructured bindings aren't otherwise extracted —
  2358. * mint a function node per binding matching the RTK hook convention so the hook
  2359. * resolves and the synthesizer can bridge it to its endpoint. Gated tight by the
  2360. * caller (object-pattern off a bare identifier) + the name convention here, so
  2361. * ordinary destructures stay unextracted.
  2362. */
  2363. private extractRtkHookBindings(pattern: SyntaxNode, isExported: boolean): void {
  2364. for (let i = 0; i < pattern.namedChildCount; i++) {
  2365. const binding = pattern.namedChild(i);
  2366. if (binding?.type !== 'shorthand_property_identifier_pattern') continue;
  2367. const name = getNodeText(binding, this.source);
  2368. if (!RTK_HOOK_NAME_RE.test(name)) continue;
  2369. this.createNode('function', name, binding, {
  2370. isExported,
  2371. signature: '= RTK Query generated hook',
  2372. });
  2373. }
  2374. }
  2375. /** Cheap per-file heuristic: the file carries ≥2 distinct Vue-store signals
  2376. * (defineStore/createStore/Vuex, or the actions/mutations/getters/namespaced
  2377. * vocabulary). Gates the non-exported `const actions = {…}` Vuex-module form so
  2378. * a stray `const actions` in unrelated code is never mistaken for a store. */
  2379. private looksLikeVueStoreFile(): boolean {
  2380. if (this.vueStoreFile !== null) return this.vueStoreFile;
  2381. const seen = new Set<string>();
  2382. VUE_STORE_FILE_SIGNAL.lastIndex = 0;
  2383. let m: RegExpExecArray | null;
  2384. while ((m = VUE_STORE_FILE_SIGNAL.exec(this.source))) {
  2385. seen.add(m[0]);
  2386. if (seen.size >= 2) break;
  2387. }
  2388. this.vueStoreFile = seen.size >= 2;
  2389. return this.vueStoreFile;
  2390. }
  2391. /** True if an object literal has ≥1 inline function member (`key: () => …` /
  2392. * `method(){}`) — distinguishes an inline action map (zustand/SvelteKit form
  2393. * actions) from a Pinia SETUP store's all-shorthand `return { foo, bar }`
  2394. * (whose functions are body-local consts, walked normally instead). */
  2395. private objectHasInlineFunctions(obj: SyntaxNode): boolean {
  2396. for (let i = 0; i < obj.namedChildCount; i++) {
  2397. const member = obj.namedChild(i);
  2398. if (member?.type === 'method_definition') return true;
  2399. if (member?.type === 'pair') {
  2400. const v = getChildByField(member, 'value');
  2401. if (v?.type === 'arrow_function' || v?.type === 'function_expression') return true;
  2402. }
  2403. }
  2404. return false;
  2405. }
  2406. /** Vue store action/mutation/getter collections defined INLINE in a store call:
  2407. * `defineStore({ actions: {…}, getters: {…} })` (Pinia options form),
  2408. * `defineStore('id', { actions: {…} })`, `createStore({ mutations: {…} })`,
  2409. * `new Vuex.Store({ actions: {…} })`. Returns the object literals under those
  2410. * keys so their methods become nodes. Gated on the store-factory callee. */
  2411. private findVueStoreCollectionObjects(callNode: SyntaxNode): SyntaxNode[] {
  2412. const callee = getChildByField(callNode, 'function') ?? getChildByField(callNode, 'constructor');
  2413. if (!callee) return [];
  2414. const calleeName =
  2415. callee.type === 'identifier'
  2416. ? getNodeText(callee, this.source)
  2417. : callee.type === 'member_expression'
  2418. ? getNodeText(getChildByField(callee, 'property') ?? callee, this.source)
  2419. : '';
  2420. if (!VUE_STORE_FACTORY_CALLEES.has(calleeName) && calleeName !== 'Store') return [];
  2421. const args = getChildByField(callNode, 'arguments');
  2422. if (!args) return [];
  2423. const objects: SyntaxNode[] = [];
  2424. for (let i = 0; i < args.namedChildCount; i++) {
  2425. const arg = args.namedChild(i);
  2426. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2427. for (let j = 0; j < arg.namedChildCount; j++) {
  2428. const member = arg.namedChild(j);
  2429. if (member?.type !== 'pair') continue;
  2430. const key = getChildByField(member, 'key');
  2431. if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue;
  2432. const value = getChildByField(member, 'value');
  2433. if (value && (value.type === 'object' || value.type === 'object_expression')) {
  2434. objects.push(value);
  2435. }
  2436. }
  2437. }
  2438. return objects;
  2439. }
  2440. /** Extract the methods of a store-config object's `actions`/`mutations`/`getters`
  2441. * properties. Used for the canonical Vuex MODULE shape `export default {
  2442. * namespaced, actions: {…}, mutations: {…} }` — object-literal methods aren't
  2443. * otherwise extracted, so the actions/mutations would never be nodes. */
  2444. private extractStoreCollectionMethods(configObj: SyntaxNode): void {
  2445. for (let j = 0; j < configObj.namedChildCount; j++) {
  2446. const member = configObj.namedChild(j);
  2447. if (member?.type !== 'pair') continue;
  2448. const key = getChildByField(member, 'key');
  2449. if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue;
  2450. const value = getChildByField(member, 'value');
  2451. if (value && (value.type === 'object' || value.type === 'object_expression')) {
  2452. this.extractObjectLiteralFunctions(value);
  2453. }
  2454. }
  2455. }
  2456. /** The SETUP function of a Pinia setup store (`defineStore('id', () => {…})`)
  2457. * — an arrow/function arg with a block body. Returns null for the options form
  2458. * (`defineStore({…})`) and for any non-defineStore call. The setup body's local
  2459. * function consts are the store's actions; the generic body walk doesn't reach
  2460. * them (nested functions are separate scopes), so they're extracted explicitly. */
  2461. private findPiniaSetupFn(callNode: SyntaxNode): SyntaxNode | null {
  2462. const callee = getChildByField(callNode, 'function');
  2463. if (!callee || callee.type !== 'identifier' || getNodeText(callee, this.source) !== 'defineStore') return null;
  2464. const args = getChildByField(callNode, 'arguments');
  2465. if (!args) return null;
  2466. for (let i = 0; i < args.namedChildCount; i++) {
  2467. const arg = args.namedChild(i);
  2468. if (arg?.type !== 'arrow_function' && arg?.type !== 'function_expression') continue;
  2469. const body = getChildByField(arg, 'body');
  2470. if (body?.type === 'statement_block') return arg; // block body ⇒ setup form
  2471. }
  2472. return null;
  2473. }
  2474. /** Extract a Pinia setup store's actions: the body-local `const foo = () => …`
  2475. * / `function foo(){}` declarations, named by the binding. (State refs and other
  2476. * consts are left to the normal value-extraction; only the functions matter as
  2477. * the store's callable surface.) */
  2478. private extractPiniaSetupBody(setupFn: SyntaxNode): void {
  2479. const body = getChildByField(setupFn, 'body');
  2480. if (!body || body.type !== 'statement_block') return;
  2481. for (let i = 0; i < body.namedChildCount; i++) {
  2482. const stmt = body.namedChild(i);
  2483. if (!stmt) continue;
  2484. if (stmt.type === 'function_declaration') {
  2485. this.extractFunction(stmt);
  2486. } else if (this.extractor!.variableTypes.includes(stmt.type)) {
  2487. for (let j = 0; j < stmt.namedChildCount; j++) {
  2488. const decl = stmt.namedChild(j);
  2489. if (decl?.type !== 'variable_declarator') continue;
  2490. const v = getChildByField(decl, 'value');
  2491. if (v?.type === 'arrow_function' || v?.type === 'function_expression') {
  2492. this.extractFunction(v); // name resolved from the parent declarator
  2493. }
  2494. }
  2495. }
  2496. }
  2497. }
  2498. /**
  2499. * Extract a variable declaration (const, let, var, etc.)
  2500. *
  2501. * Extracts top-level and module-level variable declarations.
  2502. * Captures the variable name and first 100 chars of initializer in signature for searchability.
  2503. */
  2504. private extractVariable(node: SyntaxNode): void {
  2505. if (!this.extractor) return;
  2506. // Different languages have different variable declaration structures
  2507. // TypeScript/JavaScript: lexical_declaration contains variable_declarator children
  2508. // Python: assignment has left (identifier) and right (value)
  2509. // Go: var_declaration, short_var_declaration, const_declaration
  2510. const isConst = this.extractor.isConst?.(node) ?? false;
  2511. const kind: NodeKind = isConst ? 'constant' : 'variable';
  2512. const docstring = getPrecedingDocstring(node, this.source);
  2513. const isExported = this.extractor.isExported?.(node, this.source) ?? false;
  2514. // Extract variable declarators based on language
  2515. if (this.language === 'typescript' || this.language === 'javascript' ||
  2516. this.language === 'tsx' || this.language === 'jsx' || this.language === 'cfscript' ||
  2517. this.language === 'arkts') {
  2518. // Handle lexical_declaration and variable_declaration
  2519. // These contain one or more variable_declarator children
  2520. for (let i = 0; i < node.namedChildCount; i++) {
  2521. const child = node.namedChild(i);
  2522. if (child?.type === 'variable_declarator') {
  2523. const nameNode = getChildByField(child, 'name');
  2524. const valueNode = getChildByField(child, 'value');
  2525. if (nameNode) {
  2526. // Skip destructured patterns (e.g., `let { x, y } = $props()` in Svelte)
  2527. // These produce ugly multi-line names like "{ class: className }".
  2528. // EXCEPT `export const { useGetXQuery } = someApi` — the RTK Query
  2529. // generated hooks: real exported symbols destructured off a createApi
  2530. // result. Mint a node per binding matching the hook convention (gated
  2531. // on a bare-identifier RHS so ordinary destructures stay skipped).
  2532. if (nameNode.type === 'object_pattern' || nameNode.type === 'array_pattern') {
  2533. if (nameNode.type === 'object_pattern' && valueNode?.type === 'identifier') {
  2534. this.extractRtkHookBindings(nameNode, isExported);
  2535. }
  2536. continue;
  2537. }
  2538. const name = getNodeText(nameNode, this.source);
  2539. // Arrow functions / function expressions: extract as function instead of variable
  2540. if (valueNode && (valueNode.type === 'arrow_function' || valueNode.type === 'function_expression' || valueNode.type === 'generator_function')) {
  2541. this.extractFunction(valueNode);
  2542. continue;
  2543. }
  2544. // Capture first 100 chars of initializer for context (stored in signature for searchability)
  2545. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2546. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2547. // React HOC-wrapped components (`forwardRef`/`memo`/`styled`) — see
  2548. // reactComponentHoc. The initializer is a call / tagged-template (not
  2549. // a bare arrow), so without this the const is a plain `constant`,
  2550. // which the JSX-render synthesizer and component resolution both skip
  2551. // → `<Button/>` usages get no edge and callers/impact return empty
  2552. // (the whole shadcn/ui design-system pattern, #841). PascalCase-gated
  2553. // to the component naming convention so a memoization util
  2554. // (`const cache = memo(fn)`) stays a constant.
  2555. if (valueNode && /^[A-Z]/.test(name)) {
  2556. const hoc = this.reactComponentHoc(valueNode);
  2557. if (hoc) {
  2558. this.extractReactComponentNode(name, child, hoc.inner, {
  2559. docstring,
  2560. signature: initSignature,
  2561. isExported,
  2562. });
  2563. continue;
  2564. }
  2565. }
  2566. const varNode = this.createNode(kind, name, child, {
  2567. docstring,
  2568. signature: initSignature,
  2569. isExported,
  2570. });
  2571. // Extract type annotation references (e.g., const x: ITextModel = ...)
  2572. if (varNode) {
  2573. this.extractVariableTypeAnnotation(child, varNode.id);
  2574. }
  2575. // Exported const object-of-functions — extract each function-valued
  2576. // property as a function named by its key + walk its body so its
  2577. // calls are captured. Two shapes, both keyed on AST shape (not on any
  2578. // library name):
  2579. // `export const actions = { default: async () => {} }` — object is
  2580. // the DIRECT value (SvelteKit form actions / handler maps / route
  2581. // tables).
  2582. // `export const useStore = create((set, get) => ({ fetchUser:
  2583. // async () => {} }))` — object is RETURNED by an initializer call,
  2584. // possibly through middleware wrappers (persist/devtools/immer).
  2585. // Covers Zustand/Redux/Pinia/MobX stores generically. Without
  2586. // this, store actions exist only as object-literal properties —
  2587. // never nodes — so `node`/`callers` on `fetchUser` return "not
  2588. // found" and the agent Reads the store to reconstruct the flow.
  2589. // Scoped to EXPORTED consts to exclude inline-object noise
  2590. // (`ctx.set({...})`) the object-method skip deliberately avoids —
  2591. // where "exported" includes the two-statement form `const useStore
  2592. // = create(…)` … `export default useStore` (see isExportedLater),
  2593. // the shape most React Native stores are written in.
  2594. const objectOfFns =
  2595. valueNode && (valueNode.type === 'object' || valueNode.type === 'object_expression')
  2596. ? valueNode
  2597. : valueNode?.type === 'call_expression'
  2598. ? this.findInitializerReturnedObject(valueNode)
  2599. : null;
  2600. // Only treat as an inline object-of-functions when the object actually
  2601. // HAS inline functions. A Pinia SETUP store `defineStore('id', () => {
  2602. // const foo = …; return { foo } })` returns an ALL-SHORTHAND object
  2603. // whose functions are body-local consts — it must fall through to a
  2604. // normal body walk (extracting those consts), not be skipped here.
  2605. const hasInlineFns = !!objectOfFns && this.objectHasInlineFunctions(objectOfFns);
  2606. const extractObjectMethods =
  2607. (isExported || this.isExportedLater(name)) && !!objectOfFns && hasInlineFns;
  2608. // RTK Query: `createApi`/`injectEndpoints` define endpoints as
  2609. // object-literal properties whose values are `build.query/mutation(...)`
  2610. // calls — nested under an `endpoints` arrow, so neither the
  2611. // object-of-functions path above nor the normal walk extracts them.
  2612. // Extract each endpoint as a function node (named by its key), and skip
  2613. // walking the createApi call body (its handler arrows are extracted
  2614. // individually below, exactly like the store-factory case).
  2615. const rtkEndpoints =
  2616. valueNode?.type === 'call_expression' ? this.findRtkEndpointsObject(valueNode) : null;
  2617. // Pinia SETUP store: `defineStore('id', () => { const foo = …; return {…} })`.
  2618. // Its actions are body-local consts the generic walk can't reach.
  2619. const piniaSetup =
  2620. valueNode?.type === 'call_expression' ? this.findPiniaSetupFn(valueNode) : null;
  2621. // Vue store collections — make `actions`/`mutations`/`getters` findable
  2622. // function nodes (the foundation under any later dispatch-bridge synth).
  2623. // Two positions: INLINE in a store call (`defineStore({ actions: {…} })`
  2624. // / `createStore` / `new Vuex.Store`), and the non-exported Vuex-MODULE
  2625. // form (`const actions = {…}` at a store file's top level, wired via a
  2626. // `export default { actions }`). The Pinia SETUP form is handled by the
  2627. // body walk above (its actions are local consts).
  2628. const storeCollections: SyntaxNode[] = [];
  2629. if (valueNode?.type === 'call_expression' || valueNode?.type === 'new_expression') {
  2630. storeCollections.push(...this.findVueStoreCollectionObjects(valueNode));
  2631. }
  2632. if (objectOfFns && !extractObjectMethods &&
  2633. VUE_STORE_COLLECTION_NAMES.has(name) && this.looksLikeVueStoreFile()) {
  2634. storeCollections.push(objectOfFns);
  2635. }
  2636. // Visit the initializer body for calls — EXCEPT object literals (their
  2637. // function-valued properties are extracted below) and the store-factory
  2638. // / createApi / store-collection call whose nested objects we extract
  2639. // method-by-method below (walking the whole call would re-visit those
  2640. // method arrows and mis-attribute their inner calls to the file scope).
  2641. if (valueNode &&
  2642. valueNode.type !== 'object' &&
  2643. valueNode.type !== 'object_expression' &&
  2644. !(extractObjectMethods && valueNode.type === 'call_expression') &&
  2645. !rtkEndpoints &&
  2646. !piniaSetup &&
  2647. storeCollections.length === 0) {
  2648. this.visitFunctionBody(valueNode, '');
  2649. }
  2650. if (extractObjectMethods && objectOfFns) {
  2651. this.extractObjectLiteralFunctions(objectOfFns);
  2652. }
  2653. if (rtkEndpoints) {
  2654. this.extractRtkEndpoints(rtkEndpoints);
  2655. }
  2656. if (piniaSetup) {
  2657. this.extractPiniaSetupBody(piniaSetup);
  2658. }
  2659. for (const coll of storeCollections) {
  2660. this.extractObjectLiteralFunctions(coll);
  2661. }
  2662. }
  2663. }
  2664. }
  2665. } else if (this.language === 'python' || this.language === 'ruby') {
  2666. // Python/Ruby assignment: left = right
  2667. const left = getChildByField(node, 'left') || node.namedChild(0);
  2668. const right = getChildByField(node, 'right') || node.namedChild(1);
  2669. // Ruby constant assignments (`MAX = 3`) have a `constant`-typed LHS, not
  2670. // `identifier`; without this they were never extracted as symbols at all.
  2671. if (left && (left.type === 'identifier' || left.type === 'constant')) {
  2672. const name = getNodeText(left, this.source);
  2673. // Skip if name starts with lowercase and looks like a function call result
  2674. // Python constants are usually UPPER_CASE
  2675. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  2676. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2677. this.createNode(kind, name, node, {
  2678. docstring,
  2679. signature: initSignature,
  2680. });
  2681. }
  2682. } else if (this.language === 'go') {
  2683. // Go: var_declaration, short_var_declaration, const_declaration
  2684. // These can have multiple identifiers on the left
  2685. const specs = node.namedChildren.filter(c =>
  2686. c.type === 'var_spec' || c.type === 'const_spec'
  2687. );
  2688. for (const spec of specs) {
  2689. const nameNode = spec.namedChild(0);
  2690. let varNode: Node | null = null;
  2691. if (nameNode && nameNode.type === 'identifier') {
  2692. const name = getNodeText(nameNode, this.source);
  2693. const valueNode = spec.namedChildCount > 1 ? spec.namedChild(spec.namedChildCount - 1) : null;
  2694. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2695. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2696. varNode = this.createNode(node.type === 'const_declaration' ? 'constant' : 'variable', name, spec, {
  2697. docstring,
  2698. signature: initSignature,
  2699. });
  2700. }
  2701. // Walk the initializer so composite literals and calls in a
  2702. // package-level `var Query Binding = queryBinding{}` (a registry of
  2703. // implementations) or `var c = pkg.New()` are extracted as
  2704. // instantiates/calls dependencies — the body walker only covers
  2705. // initializers inside functions, not these top-level declarations.
  2706. // Scope the walk to the declared symbol so a call inside an anonymous
  2707. // func_literal initializer — a cobra `RunE: func(){…}` handler, a
  2708. // goroutine or callback closure — attributes to the var instead of
  2709. // leaking to the file node (which reads as "no caller"), issue #693.
  2710. const valueField = getChildByField(spec, 'value');
  2711. if (valueField) {
  2712. if (varNode) this.nodeStack.push(varNode.id);
  2713. this.visitFunctionBody(valueField, varNode?.id ?? '');
  2714. if (varNode) this.nodeStack.pop();
  2715. }
  2716. }
  2717. // Handle short_var_declaration (:=)
  2718. if (node.type === 'short_var_declaration') {
  2719. const left = getChildByField(node, 'left');
  2720. const right = getChildByField(node, 'right');
  2721. if (left) {
  2722. // Can be expression_list with multiple identifiers
  2723. const identifiers = left.type === 'expression_list'
  2724. ? left.namedChildren.filter(c => c.type === 'identifier')
  2725. : [left];
  2726. for (const id of identifiers) {
  2727. const name = getNodeText(id, this.source);
  2728. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  2729. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2730. this.createNode('variable', name, node, {
  2731. docstring,
  2732. signature: initSignature,
  2733. });
  2734. }
  2735. }
  2736. }
  2737. } else if (this.language === 'lua' || this.language === 'luau') {
  2738. // Lua/Luau: variable_declaration → assignment_statement → variable_list
  2739. // (name: identifier...) = expression_list. `local x, y = 1, 2`
  2740. // declares multiple names; only plain identifiers are locals.
  2741. const assign = node.namedChildren.find((c) => c.type === 'assignment_statement') ?? node;
  2742. const varList = assign.namedChildren.find((c) => c.type === 'variable_list');
  2743. const exprList = assign.namedChildren.find((c) => c.type === 'expression_list');
  2744. const values = exprList ? exprList.namedChildren : [];
  2745. const targets = varList ? varList.namedChildren : [];
  2746. targets.forEach((nameNode, i) => {
  2747. const valueNode = values[i];
  2748. const target = this.luaAssignmentTarget(nameNode);
  2749. if (!target) return;
  2750. if (valueNode?.type === 'function_definition') {
  2751. this.extractLuaFunctionValue(valueNode, target.name, target.receiver, docstring);
  2752. return;
  2753. }
  2754. if (valueNode?.type === 'table_constructor') {
  2755. this.extractLuaTableFunctions(valueNode, target.fullName);
  2756. }
  2757. // A dotted assignment updates a table member; it is not a standalone
  2758. // variable node. Function-valued members were handled above.
  2759. if (target.receiver || node.type === 'assignment_statement') return;
  2760. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2761. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2762. this.createNode(kind, target.name, nameNode, { docstring, signature: initSignature, isExported });
  2763. });
  2764. } else if (this.language === 'c') {
  2765. // C: a `declaration` node's name nests inside the `declarator` field —
  2766. // `init_declarator` (with value) or bare/pointer/array declarators (no
  2767. // value); a `function_declarator` is a prototype, not a variable. The
  2768. // generic fallback below only finds a *direct* identifier child, which C
  2769. // never has, so file-scope consts/globals went unextracted entirely (and
  2770. // so had no impact-radius edges). Only file-scope declarations are tracked
  2771. // — locals inside a function body are skipped (a `static const` table read
  2772. // by same-file functions is the value the impact graph wants, not every
  2773. // block-local). C allows several declarators per declaration
  2774. // (`int a = 1, b = 2;`), so iterate them.
  2775. if (!hasFunctionAncestor(node)) {
  2776. for (let i = 0; i < node.namedChildCount; i++) {
  2777. const child = node.namedChild(i);
  2778. if (!child) continue;
  2779. // Accept only `init_declarator` (has a value) and pointer/array
  2780. // declarators. A *bare* `identifier` declarator is deliberately
  2781. // skipped: an unknown leading macro (`CURL_EXTERN`, `XXH_PUBLIC_API`)
  2782. // makes tree-sitter-c misparse a prototype `MACRO RetType fn(args);`
  2783. // as a declaration whose "variable" is the bare return-type
  2784. // identifier, splitting `fn(args)` off as a bogus expression — minting
  2785. // a spurious type-named global for every macro-prefixed prototype in a
  2786. // header. Those misparses are always bare identifiers; real
  2787. // consts/tables always carry an initializer. The only legit loss is
  2788. // uninitialized scalar globals (`static int g;`).
  2789. if (
  2790. child.type !== 'init_declarator' &&
  2791. child.type !== 'pointer_declarator' &&
  2792. child.type !== 'array_declarator'
  2793. ) {
  2794. continue;
  2795. }
  2796. const nameNode = cDeclaratorIdentifier(child);
  2797. if (!nameNode) continue;
  2798. const name = getNodeText(nameNode, this.source);
  2799. if (!name) continue;
  2800. const valueNode =
  2801. child.type === 'init_declarator' ? getChildByField(child, 'value') : null;
  2802. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2803. const initSignature = initValue
  2804. ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}`
  2805. : undefined;
  2806. this.createNode(kind, name, child, { docstring, signature: initSignature, isExported });
  2807. }
  2808. }
  2809. } else if (this.language === 'swift') {
  2810. // Swift top-level property (`let X = …` / `var Y = …`). The name nests in
  2811. // a `pattern`, which the generic fallback can't read, so top-level Swift
  2812. // constants/globals went unextracted. A top-level `let`→`constant`,
  2813. // `var`→`variable`; a computed property (getter, no value) is skipped.
  2814. const { nameNode, isLet, isComputed } = swiftPropertyInfo(node, this.source);
  2815. if (nameNode && !isComputed) {
  2816. this.createNode(isLet ? 'constant' : 'variable', getNodeText(nameNode, this.source), node, {
  2817. docstring,
  2818. isExported,
  2819. });
  2820. }
  2821. } else {
  2822. // Generic fallback for other languages
  2823. // Try to find identifier children
  2824. for (let i = 0; i < node.namedChildCount; i++) {
  2825. const child = node.namedChild(i);
  2826. if (child?.type === 'identifier' || child?.type === 'variable_declarator') {
  2827. const name = child.type === 'identifier'
  2828. ? getNodeText(child, this.source)
  2829. : extractName(child, this.source, this.extractor);
  2830. if (name && name !== '<anonymous>') {
  2831. this.createNode(kind, name, child, {
  2832. docstring,
  2833. isExported,
  2834. });
  2835. }
  2836. }
  2837. }
  2838. }
  2839. }
  2840. /** Resolve a Lua assignment target into its callable name and optional table receiver. */
  2841. private luaAssignmentTarget(node: SyntaxNode): { name: string; receiver?: string; fullName: string } | null {
  2842. if (node.type === 'identifier') {
  2843. const name = getNodeText(node, this.source).trim();
  2844. return name ? { name, fullName: name } : null;
  2845. }
  2846. if (
  2847. node.type !== 'dot_index_expression' &&
  2848. node.type !== 'method_index_expression' &&
  2849. node.type !== 'bracket_index_expression'
  2850. ) return null;
  2851. const table = getChildByField(node, 'table');
  2852. const field = getChildByField(node, 'field') ?? getChildByField(node, 'method');
  2853. if (!table || !field) return null;
  2854. const receiver = getNodeText(table, this.source).trim();
  2855. const name = this.luaStaticFieldName(field, node.type === 'bracket_index_expression');
  2856. if (!receiver || !name) return null;
  2857. return { name, receiver, fullName: `${receiver}.${name}` };
  2858. }
  2859. /** A statically-known Lua field name; dynamic bracket keys are not callable identities. */
  2860. private luaStaticFieldName(node: SyntaxNode, bracketed: boolean): string {
  2861. if (node.type === 'identifier') {
  2862. return bracketed ? '' : getNodeText(node, this.source).trim();
  2863. }
  2864. if (node.type === 'string') {
  2865. const content = node.namedChildren.find((child) => child.type === 'string_content');
  2866. return content ? getNodeText(content, this.source).trim() : '';
  2867. }
  2868. return '';
  2869. }
  2870. /** Extract an anonymous Lua function using the name supplied by its assignment target. */
  2871. private extractLuaFunctionValue(
  2872. node: SyntaxNode,
  2873. name: string,
  2874. receiver?: string,
  2875. docstring?: string
  2876. ): void {
  2877. if (!this.extractor) return;
  2878. const signature = this.extractor.getSignature?.(node, this.source);
  2879. const extra: Partial<Node> = { docstring, signature };
  2880. if (receiver) extra.qualifiedName = this.composeReceiverQualifiedName(receiver, name);
  2881. else extra.isExported = this.extractor.isExported?.(node, this.source);
  2882. const functionNode = this.createNode(receiver ? 'method' : 'function', name, node, extra);
  2883. if (!functionNode) return;
  2884. this.nodeStack.push(functionNode.id);
  2885. const body = getChildByField(node, this.extractor.bodyField);
  2886. if (body) this.visitFunctionBody(body, functionNode.id);
  2887. this.nodeStack.pop();
  2888. }
  2889. /** Extract function-valued keyed fields from a Lua table, including nested tables. */
  2890. private extractLuaTableFunctions(table: SyntaxNode, receiver: string): void {
  2891. for (const field of table.namedChildren) {
  2892. if (field.type !== 'field') continue;
  2893. const nameNode = getChildByField(field, 'name');
  2894. const valueNode = getChildByField(field, 'value');
  2895. if (!nameNode || !valueNode) continue;
  2896. const bracketed = getNodeText(field, this.source).trimStart().startsWith('[');
  2897. const name = this.luaStaticFieldName(nameNode, bracketed);
  2898. if (!name) continue;
  2899. if (valueNode.type === 'function_definition') {
  2900. this.extractLuaFunctionValue(valueNode, name, receiver);
  2901. } else if (valueNode.type === 'table_constructor') {
  2902. this.extractLuaTableFunctions(valueNode, `${receiver}.${name}`);
  2903. }
  2904. }
  2905. }
  2906. /**
  2907. * Extract a type alias (e.g. `export type X = ...` in TypeScript).
  2908. * For languages like Go, resolveTypeAliasKind detects when the type_spec
  2909. * wraps a struct or interface definition and creates the correct node kind.
  2910. * Returns true if children should be skipped (struct/interface handled body visiting).
  2911. */
  2912. private extractTypeAlias(node: SyntaxNode): boolean {
  2913. if (!this.extractor) return false;
  2914. const name = extractName(node, this.source, this.extractor);
  2915. if (name === '<anonymous>') return false;
  2916. const docstring = getPrecedingDocstring(node, this.source);
  2917. const isExported = this.extractor.isExported?.(node, this.source);
  2918. // Check if this type alias is actually a struct or interface definition
  2919. // (e.g. Go: `type Foo struct { ... }` is a type_spec wrapping struct_type)
  2920. const resolvedKind = this.extractor.resolveTypeAliasKind?.(node, this.source);
  2921. if (resolvedKind === 'struct' || resolvedKind === 'union') {
  2922. const aggregateNode = this.createNode(resolvedKind, name, node, { docstring, isExported });
  2923. if (!aggregateNode) return true;
  2924. // Visit body children for field extraction
  2925. this.nodeStack.push(aggregateNode.id);
  2926. // Try Go-style 'type' field first, then find the matching inner aggregate child.
  2927. const typeChild = getChildByField(node, 'type')
  2928. || this.findChildByTypes(
  2929. node,
  2930. resolvedKind === 'union' ? (this.extractor.unionTypes ?? []) : this.extractor.structTypes
  2931. );
  2932. if (typeChild) {
  2933. // Extract struct embedding (e.g. Go: `type DB struct { *Head; Queryable }`)
  2934. this.extractInheritance(typeChild, aggregateNode.id);
  2935. const body = getChildByField(typeChild, this.extractor.bodyField) || typeChild;
  2936. for (let i = 0; i < body.namedChildCount; i++) {
  2937. const child = body.namedChild(i);
  2938. if (child) this.visitNode(child);
  2939. }
  2940. }
  2941. this.nodeStack.pop();
  2942. return true;
  2943. }
  2944. if (resolvedKind === 'enum') {
  2945. const enumNode = this.createNode('enum', name, node, { docstring, isExported });
  2946. if (!enumNode) return true;
  2947. this.nodeStack.push(enumNode.id);
  2948. // Find the inner enum type child (e.g. C: typedef enum { ... } name)
  2949. const innerEnum = this.findChildByTypes(node, this.extractor.enumTypes);
  2950. if (innerEnum) {
  2951. this.extractInheritance(innerEnum, enumNode.id);
  2952. const body = this.extractor.resolveBody?.(innerEnum, this.extractor.bodyField)
  2953. ?? getChildByField(innerEnum, this.extractor.bodyField);
  2954. if (body) {
  2955. const memberTypes = this.extractor.enumMemberTypes;
  2956. for (let i = 0; i < body.namedChildCount; i++) {
  2957. const child = body.namedChild(i);
  2958. if (!child) continue;
  2959. if (memberTypes?.includes(child.type)) {
  2960. this.extractEnumMembers(child);
  2961. } else {
  2962. this.visitNode(child);
  2963. }
  2964. }
  2965. }
  2966. }
  2967. this.nodeStack.pop();
  2968. return true;
  2969. }
  2970. if (resolvedKind === 'interface') {
  2971. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  2972. const interfaceNode = this.createNode(kind, name, node, { docstring, isExported });
  2973. if (!interfaceNode) return true;
  2974. // Extract interface inheritance from the inner type node
  2975. const typeChild = getChildByField(node, 'type');
  2976. if (typeChild) this.extractInheritance(typeChild, interfaceNode.id);
  2977. // Go: extract the interface's method specs as `method` nodes so implicit
  2978. // interface satisfaction (a struct's method set ⊇ the interface's) and
  2979. // impl-navigation can see the contract. Go has no `implements` keyword, so
  2980. // without the interface's method set there's nothing to match against.
  2981. if (this.language === 'go' && typeChild) {
  2982. this.extractGoInterfaceMethods(typeChild, interfaceNode.id);
  2983. }
  2984. return true;
  2985. }
  2986. const typeAliasNode = this.createNode('type_alias', name, node, {
  2987. docstring,
  2988. isExported,
  2989. });
  2990. // Extract type references from the alias value (e.g., `type X = ITextModel | null`)
  2991. if (typeAliasNode && this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) {
  2992. // The value is everything after the `=`, which is typically the last named child
  2993. // In tree-sitter TS: type_alias_declaration has name + value children
  2994. const value = getChildByField(node, 'value');
  2995. if (value) {
  2996. this.extractTypeRefsFromSubtree(value, typeAliasNode.id);
  2997. // `type X = { foo: T; bar(): T }` — make the members first-class
  2998. // property/method nodes under the type alias so `recorder.stop()`
  2999. // can attach the call edge to `RecorderHandle.stop` instead of
  3000. // an unrelated class method picked by path-proximity (#359).
  3001. if (this.language === 'typescript' || this.language === 'tsx' || this.language === 'arkts') {
  3002. this.extractTsTypeAliasMembers(value, typeAliasNode);
  3003. // `type List = [ Service<'name', Req, Resp>, … ]` — surface each
  3004. // entry's string-literal name as a searchable member (issue #634).
  3005. this.extractTsTupleContractNames(value, typeAliasNode);
  3006. }
  3007. }
  3008. }
  3009. return false;
  3010. }
  3011. /**
  3012. * Extract the method specs of a Go `interface_type` body as `method` nodes
  3013. * contained by the interface (e.g. `Marshal`, `Unmarshal` of a `Core`
  3014. * interface). tree-sitter-go names these `method_elem` (newer) or
  3015. * `method_spec` (older). Embedded interfaces (`Reader` inside `ReadWriter`)
  3016. * are `type_identifier`s, not methods, and are left to inheritance extraction.
  3017. */
  3018. private extractGoInterfaceMethods(interfaceType: SyntaxNode, ifaceId: string): void {
  3019. this.nodeStack.push(ifaceId);
  3020. for (let i = 0; i < interfaceType.namedChildCount; i++) {
  3021. const m = interfaceType.namedChild(i);
  3022. if (!m || (m.type !== 'method_elem' && m.type !== 'method_spec')) continue;
  3023. const nameNode = getChildByField(m, 'name') ?? m.namedChild(0);
  3024. if (!nameNode) continue;
  3025. const mname = getNodeText(nameNode, this.source);
  3026. if (mname) {
  3027. this.createNode('method', mname, m, {
  3028. signature: this.extractor?.getSignature?.(m, this.source),
  3029. });
  3030. }
  3031. }
  3032. this.nodeStack.pop();
  3033. }
  3034. /**
  3035. * Surface the members of a TypeScript `type X = { ... }` (or intersection
  3036. * thereof) as `property` / `method` nodes under the type-alias node. Only
  3037. * walks the immediate object_type / intersection operands so anonymous
  3038. * nested object types inside generic arguments (`Promise<{ ok: true }>`)
  3039. * don't produce phantom members.
  3040. */
  3041. private extractTsTypeAliasMembers(value: SyntaxNode, typeAliasNode: Node): void {
  3042. const objectTypes: SyntaxNode[] = [];
  3043. if (value.type === 'object_type') {
  3044. objectTypes.push(value);
  3045. } else if (value.type === 'intersection_type') {
  3046. for (let i = 0; i < value.namedChildCount; i++) {
  3047. const op = value.namedChild(i);
  3048. if (op && op.type === 'object_type') objectTypes.push(op);
  3049. }
  3050. } else {
  3051. return;
  3052. }
  3053. this.nodeStack.push(typeAliasNode.id);
  3054. for (const objType of objectTypes) {
  3055. for (let i = 0; i < objType.namedChildCount; i++) {
  3056. const child = objType.namedChild(i);
  3057. if (!child) continue;
  3058. if (child.type !== 'property_signature' && child.type !== 'method_signature') continue;
  3059. const nameNode = getChildByField(child, 'name');
  3060. const memberName = nameNode ? getNodeText(nameNode, this.source) : '';
  3061. if (!memberName) continue;
  3062. // `foo: () => T` and `foo(): T` are functionally a method on the
  3063. // type contract. Treat the property_signature with a function-typed
  3064. // annotation as a method too so call sites can resolve to it.
  3065. const memberKind: NodeKind = child.type === 'method_signature'
  3066. ? 'method'
  3067. : this.isTsFunctionTypedProperty(child) ? 'method' : 'property';
  3068. const docstring = getPrecedingDocstring(child, this.source);
  3069. const signature = getNodeText(child, this.source);
  3070. this.createNode(memberKind, memberName, child, {
  3071. docstring,
  3072. signature,
  3073. qualifiedName: `${typeAliasNode.name}::${memberName}`,
  3074. });
  3075. // Emit `references` edges from the type alias to types named in the
  3076. // member's signature, matching the interface-member behavior added in
  3077. // #432. We attach refs to the type-alias parent (consistent with
  3078. // interface property_signature treatment).
  3079. this.extractTypeAnnotations(child, typeAliasNode.id);
  3080. }
  3081. }
  3082. this.nodeStack.pop();
  3083. }
  3084. /**
  3085. * Surface the string-literal "names" of a TypeScript service/contract
  3086. * registry written as a tuple of generic instantiations:
  3087. *
  3088. * type MyServiceList = [
  3089. * Service<'query_apply_record', Req, Resp>,
  3090. * Service<'apply_confirm', Req, Resp>,
  3091. * ];
  3092. *
  3093. * Each `Service<'name', …>` tags an entry with a string-literal name that a
  3094. * dynamic factory (`createService<MyServiceList>()`) turns into a callable
  3095. * property (`api.query_apply_record(…)`). Static extraction otherwise never
  3096. * sees that name — it's a type argument, not a declaration — so
  3097. * `codegraph query query_apply_record` returned nothing (issue #634). We emit
  3098. * each name as a `method` node under the type alias (qualifiedName
  3099. * `MyServiceList::query_apply_record`) so it's searchable and resolvable as a
  3100. * symbol. (A call through the proxy, `api.query_apply_record(…)`, still
  3101. * resolves to the imported `api` binding — the receiver's type isn't known —
  3102. * so this fixes discoverability, not the per-method call edge.)
  3103. *
  3104. * Scope is deliberately narrow to avoid noise: only a string literal that is
  3105. * a DIRECT type argument of a `generic_type` that is itself a DIRECT element
  3106. * of a `tuple_type`. This excludes utility types (`Pick`/`Omit`/`Record` are
  3107. * never written as tuples) and string args nested deeper
  3108. * (`Service<'a', Pick<U, 'id'>>` yields only `a`, never `id`). Names must be
  3109. * valid identifiers, which also rules out route paths / arbitrary strings.
  3110. */
  3111. private extractTsTupleContractNames(value: SyntaxNode, typeAliasNode: Node): void {
  3112. const tuples: SyntaxNode[] = [];
  3113. const collectTuples = (n: SyntaxNode, depth: number): void => {
  3114. if (depth > 6) return; // a type expression is shallow; cap defensively
  3115. if (n.type === 'tuple_type') tuples.push(n);
  3116. for (let i = 0; i < n.namedChildCount; i++) {
  3117. const c = n.namedChild(i);
  3118. if (c) collectTuples(c, depth + 1);
  3119. }
  3120. };
  3121. collectTuples(value, 0);
  3122. if (tuples.length === 0) return;
  3123. this.nodeStack.push(typeAliasNode.id);
  3124. for (const tuple of tuples) {
  3125. for (let i = 0; i < tuple.namedChildCount; i++) {
  3126. const entry = tuple.namedChild(i);
  3127. if (!entry || entry.type !== 'generic_type') continue;
  3128. const typeArgs = getChildByField(entry, 'type_arguments');
  3129. if (!typeArgs) continue;
  3130. for (let j = 0; j < typeArgs.namedChildCount; j++) {
  3131. const arg = typeArgs.namedChild(j);
  3132. if (!arg || arg.type !== 'literal_type') continue;
  3133. // literal_type wraps the actual literal; only a string is a name.
  3134. const strNode = arg.namedChild(0);
  3135. if (!strNode || strNode.type !== 'string') continue;
  3136. const name = getNodeText(strNode, this.source)
  3137. .trim()
  3138. .replace(/^['"`]/, '')
  3139. .replace(/['"`]$/, '');
  3140. if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) continue;
  3141. const signature = getNodeText(entry, this.source).replace(/\s+/g, ' ').trim().slice(0, 120);
  3142. this.createNode('method', name, entry, {
  3143. signature,
  3144. qualifiedName: `${typeAliasNode.name}::${name}`,
  3145. });
  3146. }
  3147. }
  3148. }
  3149. this.nodeStack.pop();
  3150. }
  3151. /**
  3152. * `foo: () => T` → property_signature whose type_annotation contains a
  3153. * `function_type`. Treat that as a method-shaped contract member, since
  3154. * the call site `obj.foo()` has identical semantics to `bar(): T`.
  3155. */
  3156. private isTsFunctionTypedProperty(propertySignature: SyntaxNode): boolean {
  3157. const typeAnno = getChildByField(propertySignature, 'type');
  3158. if (!typeAnno) return false;
  3159. for (let i = 0; i < typeAnno.namedChildCount; i++) {
  3160. const inner = typeAnno.namedChild(i);
  3161. if (inner && inner.type === 'function_type') return true;
  3162. }
  3163. return false;
  3164. }
  3165. // extractExportedVariables removed — the walker now descends into
  3166. // export_statement children and the inner declaration's dedicated
  3167. // extractor (extractVariable, extractFunction, extractClass, etc.)
  3168. // handles the symbol with isExported=true via parent-walk in the
  3169. // language extractor's isExported predicate.
  3170. /**
  3171. * Extract an import
  3172. *
  3173. * Creates an import node with the full import statement stored in signature for searchability.
  3174. * Also creates unresolved references for resolution purposes.
  3175. */
  3176. private extractImport(node: SyntaxNode): void {
  3177. if (!this.extractor) return;
  3178. const importText = getNodeText(node, this.source).trim();
  3179. // Try language-specific hook first
  3180. if (this.extractor.extractImport) {
  3181. const info = this.extractor.extractImport(node, this.source);
  3182. if (info) {
  3183. this.createNode('import', info.moduleName, node, {
  3184. signature: info.signature,
  3185. });
  3186. // Create unresolved reference unless the hook handled it
  3187. if (!info.handledRefs && info.moduleName && this.nodeStack.length > 0) {
  3188. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3189. if (parentId) {
  3190. this.unresolvedReferences.push({
  3191. fromNodeId: parentId,
  3192. referenceName: info.moduleName,
  3193. referenceKind: 'imports',
  3194. line: node.startPosition.row + 1,
  3195. column: node.startPosition.column,
  3196. });
  3197. }
  3198. }
  3199. // Link each imported binding to its definition so imported-but-not-
  3200. // called/typed symbols still record a cross-file dependency (TS/JS only).
  3201. if (
  3202. this.language === 'typescript' || this.language === 'tsx' ||
  3203. this.language === 'javascript' || this.language === 'jsx' ||
  3204. this.language === 'arkts'
  3205. ) {
  3206. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3207. if (parentId) this.emitImportBindingRefs(node, parentId);
  3208. }
  3209. // Python `from module import X, Y` — link each imported name to its
  3210. // definition (covers `__init__.py` re-export barrels, which are just
  3211. // `from .sub import X`). Same recall gap as TS: a name imported and
  3212. // used in a non-call position created no dependency edge.
  3213. if (this.language === 'python' && node.type === 'import_from_statement') {
  3214. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3215. if (parentId) this.emitPyFromImportRefs(node, parentId);
  3216. }
  3217. // Rust `use crate::m::Item;` / `pub use self::sub::Item;` — link each
  3218. // imported leaf to its definition. Covers `pub use` re-export hubs
  3219. // (a `mod.rs` re-exporting submodule items, e.g. tokio's `fs/mod.rs`)
  3220. // and items imported but used in non-call/non-type positions.
  3221. if (this.language === 'rust' && node.type === 'use_declaration') {
  3222. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3223. if (parentId) this.emitRustUseBindingRefs(node, parentId);
  3224. }
  3225. // PHP `use Foo\Bar\Baz;` — link to the namespace-qualified definition so
  3226. // an imported-but-DI-injected contract (Laravel's pattern) records a
  3227. // cross-file dependency. Grouped imports are handled in their own branch.
  3228. if (this.language === 'php' && node.type === 'namespace_use_declaration') {
  3229. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3230. if (parentId) this.emitPhpUseRefs(node, parentId);
  3231. }
  3232. // Ruby `require "lib/foo"` / `require_relative "../foo"` — resolve to the
  3233. // required FILE so a file pulled in only by `require` (config-loaded
  3234. // components, gems that don't autoload) records a cross-file dependency.
  3235. if (this.language === 'ruby' && node.type === 'call') {
  3236. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3237. if (parentId) this.emitRubyRequireRefs(node, parentId);
  3238. }
  3239. return;
  3240. }
  3241. // Hook returned null — fall through to multi-import inline handlers only
  3242. // (hook returning null means "I didn't handle this" for multi-import cases,
  3243. // NOT "use generic fallback" — the hook already declined)
  3244. }
  3245. // Multi-import cases that create multiple nodes (can't be expressed with single-return hook)
  3246. // Python import_statement: import os, sys (creates one import per module)
  3247. if (this.language === 'python' && node.type === 'import_statement') {
  3248. const importParentId = this.nodeStack[this.nodeStack.length - 1];
  3249. // A bare `import a.b.c` of an internal module (the standard Django
  3250. // `AppConfig.ready(): import myapp.signals` registration pattern, and any
  3251. // `import pkg.mod` used for its side effects) had no edge to the module
  3252. // file — only `from x import y` was linked. Push an `imports` ref (like
  3253. // Go) so the resolver maps the dotted path to its file. Stdlib/external
  3254. // modules naturally don't resolve (no `os.py` file node in the repo).
  3255. const pushModuleRef = (dotted: SyntaxNode): void => {
  3256. if (!importParentId) return;
  3257. this.unresolvedReferences.push({
  3258. fromNodeId: importParentId,
  3259. referenceName: getNodeText(dotted, this.source),
  3260. referenceKind: 'imports',
  3261. line: dotted.startPosition.row + 1,
  3262. column: dotted.startPosition.column,
  3263. });
  3264. };
  3265. for (let i = 0; i < node.namedChildCount; i++) {
  3266. const child = node.namedChild(i);
  3267. if (child?.type === 'dotted_name') {
  3268. this.createNode('import', getNodeText(child, this.source), node, {
  3269. signature: importText,
  3270. });
  3271. pushModuleRef(child);
  3272. } else if (child?.type === 'aliased_import') {
  3273. const dottedName = child.namedChildren.find(c => c.type === 'dotted_name');
  3274. if (dottedName) {
  3275. this.createNode('import', getNodeText(dottedName, this.source), node, {
  3276. signature: importText,
  3277. });
  3278. pushModuleRef(dottedName);
  3279. }
  3280. }
  3281. }
  3282. return;
  3283. }
  3284. // Go imports: single or grouped (creates one import per spec)
  3285. if (this.language === 'go') {
  3286. const parentId = this.nodeStack.length > 0 ? this.nodeStack[this.nodeStack.length - 1] : null;
  3287. const extractFromSpec = (spec: SyntaxNode): void => {
  3288. const stringLiteral = spec.namedChildren.find(c => c.type === 'interpreted_string_literal');
  3289. if (stringLiteral) {
  3290. const importPath = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  3291. if (importPath) {
  3292. this.createNode('import', importPath, spec, {
  3293. signature: getNodeText(spec, this.source).trim(),
  3294. });
  3295. // Create unresolved reference so the resolver can create imports edges
  3296. if (parentId) {
  3297. this.unresolvedReferences.push({
  3298. fromNodeId: parentId,
  3299. referenceName: importPath,
  3300. referenceKind: 'imports',
  3301. line: spec.startPosition.row + 1,
  3302. column: spec.startPosition.column,
  3303. });
  3304. }
  3305. }
  3306. }
  3307. };
  3308. const importSpecList = node.namedChildren.find(c => c.type === 'import_spec_list');
  3309. if (importSpecList) {
  3310. for (const spec of importSpecList.namedChildren.filter(c => c.type === 'import_spec')) {
  3311. extractFromSpec(spec);
  3312. }
  3313. } else {
  3314. const importSpec = node.namedChildren.find(c => c.type === 'import_spec');
  3315. if (importSpec) {
  3316. extractFromSpec(importSpec);
  3317. }
  3318. }
  3319. return;
  3320. }
  3321. // PHP grouped imports: use X\{A, B} (creates one import per item)
  3322. if (this.language === 'php') {
  3323. const namespacePrefix = node.namedChildren.find(c => c.type === 'namespace_name');
  3324. const useGroup = node.namedChildren.find(c => c.type === 'namespace_use_group');
  3325. if (namespacePrefix && useGroup) {
  3326. const prefix = getNodeText(namespacePrefix, this.source);
  3327. const useClauses = useGroup.namedChildren.filter((c: SyntaxNode) =>
  3328. c.type === 'namespace_use_group_clause' || c.type === 'namespace_use_clause'
  3329. );
  3330. for (const clause of useClauses) {
  3331. const nsName = clause.namedChildren.find((c: SyntaxNode) => c.type === 'namespace_name');
  3332. const name = nsName
  3333. ? nsName.namedChildren.find((c: SyntaxNode) => c.type === 'name')
  3334. : clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  3335. if (name) {
  3336. const fullPath = `${prefix}\\${getNodeText(name, this.source)}`;
  3337. this.createNode('import', fullPath, node, {
  3338. signature: importText,
  3339. });
  3340. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3341. if (parentId) this.pushPhpUseRef(fullPath, parentId, node);
  3342. }
  3343. }
  3344. return;
  3345. }
  3346. }
  3347. // If a hook exists but returned null, it intentionally declined this node — don't create fallback
  3348. if (this.extractor.extractImport) return;
  3349. // Generic fallback for languages without hooks
  3350. this.createNode('import', importText, node, {
  3351. signature: importText,
  3352. });
  3353. }
  3354. /**
  3355. * Emit one `imports` reference per named/default import binding (TS/JS family),
  3356. * attributed to the file node — so the resolver links each imported symbol to
  3357. * the file that DEFINES it.
  3358. *
  3359. * Importing a symbol IS a dependency, but extraction only emits references for
  3360. * calls, instantiations, type annotations, and inheritance. A symbol that's
  3361. * imported and then only re-exported (`export { X } from './x'`), placed in a
  3362. * registry array (`[expressResolver, …]`), passed as an argument, or used in
  3363. * JSX produced NO cross-file edge at all — so the providing file showed a
  3364. * false "0 dependents" and was invisible to blast-radius / `affected`. The
  3365. * resolver maps the local name (alias-aware) to the provider's definition and
  3366. * creates a cross-file `imports` edge; `getFileDependents` picks it up, while
  3367. * `getImpactRadius` keeps it as a bounded leaf (the importing file node).
  3368. *
  3369. * Namespace imports (`import * as NS`) bind a whole module: `NS.member` calls
  3370. * resolve on their own, but a namespace used ONLY via a value-member read
  3371. * (`NS.SOME_CONST`) would leave no edge — so we also emit the namespace local
  3372. * name, which the resolver links to the module FILE as a dependency backstop.
  3373. */
  3374. private emitImportBindingRefs(node: SyntaxNode, fromNodeId: string): void {
  3375. const clause = node.namedChildren.find((c) => c.type === 'import_clause');
  3376. if (!clause) return; // side-effect import (`import './x'`) — no bindings
  3377. const pushRef = (nameNode: SyntaxNode | null | undefined): void => {
  3378. if (!nameNode) return;
  3379. const name = getNodeText(nameNode, this.source);
  3380. if (!name) return;
  3381. this.unresolvedReferences.push({
  3382. fromNodeId,
  3383. referenceName: name,
  3384. referenceKind: 'imports',
  3385. line: nameNode.startPosition.row + 1,
  3386. column: nameNode.startPosition.column,
  3387. });
  3388. };
  3389. for (const child of clause.namedChildren) {
  3390. if (child.type === 'identifier') {
  3391. // default import: `import Foo from './x'`
  3392. pushRef(child);
  3393. } else if (child.type === 'named_imports') {
  3394. // `import { A, B as C } from './x'` — link the LOCAL name (alias if any)
  3395. for (const spec of child.namedChildren) {
  3396. if (spec.type !== 'import_specifier') continue;
  3397. pushRef(getChildByField(spec, 'alias') ?? getChildByField(spec, 'name') ?? spec.namedChild(0));
  3398. }
  3399. } else if (child.type === 'namespace_import') {
  3400. // `import * as NS from './x'` — emit NS so the module-import backstop can
  3401. // record the file dependency even if NS is only used by value-member read.
  3402. pushRef(child.namedChildren.find((c) => c.type === 'identifier') ?? child.namedChild(0));
  3403. }
  3404. }
  3405. }
  3406. /**
  3407. * Emit one `imports` reference per re-exported binding of a
  3408. * `export { A, B as C } from './y'` statement, attributed to the file node —
  3409. * so a barrel that re-exports from another module records a dependency on it.
  3410. *
  3411. * Links the SOURCE-side name (`A`, the `name` field — not the local alias
  3412. * `C`), since that is what the source module defines. `export * from './y'`
  3413. * has no named bindings to attribute and `export { default as X }` can't be
  3414. * name-matched, so both are skipped.
  3415. */
  3416. private emitReExportRefs(node: SyntaxNode, fromNodeId: string): void {
  3417. const clause = node.namedChildren.find((c) => c.type === 'export_clause');
  3418. if (!clause) return; // `export * from './y'` — no named bindings
  3419. for (const spec of clause.namedChildren) {
  3420. if (spec.type !== 'export_specifier') continue;
  3421. const nameNode = getChildByField(spec, 'name') ?? spec.namedChild(0);
  3422. if (!nameNode) continue;
  3423. const name = getNodeText(nameNode, this.source);
  3424. if (!name || name === 'default') continue;
  3425. this.unresolvedReferences.push({
  3426. fromNodeId,
  3427. referenceName: name,
  3428. referenceKind: 'imports',
  3429. line: nameNode.startPosition.row + 1,
  3430. column: nameNode.startPosition.column,
  3431. });
  3432. }
  3433. }
  3434. /**
  3435. * Emit one `imports` reference per binding of a Rust `use` declaration —
  3436. * `use crate::m::Item`, `use crate::m::{A, B as C}`, `pub use self::sub::Item`.
  3437. * Emits the FULL path (e.g. `self::sub::Item`, not just `Item`) so the resolver
  3438. * can resolve the module prefix to a file and find the leaf symbol there —
  3439. * disambiguating common-name re-exports (`pub use self::read::read`, where the
  3440. * leaf `read` collides with many same-named symbols). Falls back to name-match
  3441. * on the leaf when the path can't be resolved. `use ...::*` has no leaf binding.
  3442. */
  3443. private emitRustUseBindingRefs(node: SyntaxNode, fromNodeId: string): void {
  3444. const paths: { text: string; node: SyntaxNode }[] = [];
  3445. const join = (prefix: string, seg: string): string => (prefix ? `${prefix}::${seg}` : seg);
  3446. const collect = (n: SyntaxNode, prefix: string): void => {
  3447. switch (n.type) {
  3448. case 'identifier':
  3449. paths.push({ text: join(prefix, getNodeText(n, this.source)), node: n });
  3450. break;
  3451. case 'scoped_identifier': {
  3452. // Full scoped path (`a::b::C`); combine with any outer group prefix.
  3453. const full = getNodeText(n, this.source).trim();
  3454. paths.push({ text: prefix ? `${prefix}::${full}` : full, node: n });
  3455. break;
  3456. }
  3457. case 'scoped_use_list': {
  3458. // `path::{ ... }` — the group's path becomes the prefix for each item.
  3459. const pathNode = getChildByField(n, 'path');
  3460. const seg = pathNode ? getNodeText(pathNode, this.source).trim() : '';
  3461. const newPrefix = seg ? join(prefix, seg) : prefix;
  3462. const list = getChildByField(n, 'list') ?? n.namedChildren.find((c) => c.type === 'use_list');
  3463. if (list) collect(list, newPrefix);
  3464. break;
  3465. }
  3466. case 'use_list':
  3467. for (let i = 0; i < n.namedChildCount; i++) {
  3468. const c = n.namedChild(i);
  3469. if (c) collect(c, prefix);
  3470. }
  3471. break;
  3472. case 'use_as_clause': {
  3473. // `Path as Alias` → link the source path (the definition), not the alias.
  3474. const p = getChildByField(n, 'path') ?? n.namedChild(0);
  3475. if (p) collect(p, prefix);
  3476. break;
  3477. }
  3478. // use_wildcard → no specific binding to link.
  3479. }
  3480. };
  3481. for (let i = 0; i < node.namedChildCount; i++) {
  3482. const c = node.namedChild(i);
  3483. if (c) collect(c, '');
  3484. }
  3485. for (const p of paths) {
  3486. // The leaf must be a real name (skip a path that is only `self`/`super`/`crate`).
  3487. const leaf = p.text.split('::').pop();
  3488. if (!leaf || leaf === 'self' || leaf === 'super' || leaf === 'crate' || leaf === '*') continue;
  3489. this.unresolvedReferences.push({
  3490. fromNodeId,
  3491. referenceName: p.text,
  3492. referenceKind: 'imports',
  3493. line: p.node.startPosition.row + 1,
  3494. column: p.node.startPosition.column,
  3495. });
  3496. }
  3497. }
  3498. /**
  3499. * Emit an `imports` reference for a single PHP `use Foo\Bar\Baz;` (grouped
  3500. * imports `use Foo\{A, B}` are handled where their per-item nodes are created).
  3501. * The reference targets the namespace-qualified `Foo\Bar::Baz` form classes are
  3502. * stored under (see the PHP `namespace` capture), so it resolves to the RIGHT
  3503. * definition — Laravel has many same-named contracts (`Factory`, `Dispatcher`,
  3504. * `Guard`) across namespaces that a bare-name match can't disambiguate.
  3505. */
  3506. private emitPhpUseRefs(node: SyntaxNode, fromNodeId: string): void {
  3507. const clause = node.namedChildren.find((c: SyntaxNode) => c.type === 'namespace_use_clause');
  3508. if (!clause) return;
  3509. const qn = clause.namedChildren.find((c: SyntaxNode) => c.type === 'qualified_name')
  3510. ?? clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  3511. if (qn) this.pushPhpUseRef(getNodeText(qn, this.source), fromNodeId, node);
  3512. }
  3513. /**
  3514. * Ruby `require`/`require_relative` → an `imports` ref to the required FILE.
  3515. * `require "sidekiq/fetch"` is load-path-relative (matched by file-path suffix
  3516. * via {@link matchByFilePath}); `require_relative "../foo"` is resolved against
  3517. * this file's directory. Bare gem/stdlib requires (`require "json"`, no slash)
  3518. * are skipped — they're external. The path form (a `/` + `.rb`) makes the ref
  3519. * resolve to the file node, so a file pulled in only by `require` — not by a
  3520. * resolved constant/call — still records a cross-file dependency.
  3521. */
  3522. private emitRubyRequireRefs(node: SyntaxNode, fromNodeId: string): void {
  3523. const method = node.namedChildren.find((c: SyntaxNode) => c.type === 'identifier');
  3524. const mname = method ? getNodeText(method, this.source) : '';
  3525. if (mname !== 'require' && mname !== 'require_relative') return;
  3526. const argList = node.namedChildren.find((c: SyntaxNode) => c.type === 'argument_list');
  3527. const str = argList?.namedChildren.find((c: SyntaxNode) => c.type === 'string');
  3528. const content = str?.namedChildren.find((c: SyntaxNode) => c.type === 'string_content');
  3529. if (!content) return;
  3530. const req = getNodeText(content, this.source).trim();
  3531. if (!req) return;
  3532. let refPath: string;
  3533. if (mname === 'require_relative') {
  3534. const slash = this.filePath.lastIndexOf('/');
  3535. const dir = slash >= 0 ? this.filePath.slice(0, slash) : '';
  3536. refPath = path.posix.normalize(dir ? `${dir}/${req}` : req);
  3537. } else {
  3538. refPath = req; // load-path require — suffix-matched against the file path
  3539. }
  3540. if (!refPath.includes('/')) return; // bare gem/stdlib require — external
  3541. if (!refPath.endsWith('.rb')) refPath += '.rb';
  3542. this.unresolvedReferences.push({
  3543. fromNodeId,
  3544. referenceName: refPath,
  3545. referenceKind: 'imports',
  3546. line: node.startPosition.row + 1,
  3547. column: node.startPosition.column,
  3548. });
  3549. }
  3550. /** Convert a PHP FQN `Foo\Bar\Baz` to the stored `Foo\Bar::Baz` and emit an `imports` ref. */
  3551. private pushPhpUseRef(fqn: string, fromNodeId: string, node: SyntaxNode): void {
  3552. const clean = fqn.replace(/^\\/, '');
  3553. const lastSep = clean.lastIndexOf('\\');
  3554. if (lastSep < 0) return; // global-namespace class — already matches by simple name
  3555. this.unresolvedReferences.push({
  3556. fromNodeId,
  3557. referenceName: `${clean.slice(0, lastSep)}::${clean.slice(lastSep + 1)}`,
  3558. referenceKind: 'imports',
  3559. line: node.startPosition.row + 1,
  3560. column: node.startPosition.column,
  3561. });
  3562. }
  3563. /**
  3564. * Emit one `imports` reference per name imported in a Python
  3565. * `from module import A, B as C` statement, attributed to the file node — so
  3566. * the resolver links each imported name to the module that DEFINES it.
  3567. *
  3568. * Same recall gap as TS: extraction only emitted references for calls,
  3569. * instantiations, and inheritance, so a name imported and then used in a
  3570. * non-call position (a list/dict literal, a default argument, a decorator
  3571. * target, or simply re-exported through an `__init__.py` barrel) produced no
  3572. * cross-file edge — the providing module showed a false "0 dependents". Links
  3573. * the LOCAL name (alias when present, since that's what the resolver's import
  3574. * mapping keys on); `from module import *` has no names to attribute.
  3575. */
  3576. private emitPyFromImportRefs(node: SyntaxNode, fromNodeId: string): void {
  3577. const moduleNameNode = getChildByField(node, 'module_name');
  3578. for (const child of node.namedChildren) {
  3579. // Skip the `from <module>` part itself and `import *`.
  3580. if (moduleNameNode &&
  3581. child.startIndex === moduleNameNode.startIndex &&
  3582. child.endIndex === moduleNameNode.endIndex) continue;
  3583. if (child.type === 'wildcard_import') continue;
  3584. let nameNode: SyntaxNode | null | undefined = null;
  3585. if (child.type === 'aliased_import') {
  3586. nameNode = getChildByField(child, 'alias') ?? getChildByField(child, 'name') ?? child.namedChild(0);
  3587. } else if (child.type === 'dotted_name') {
  3588. nameNode = child;
  3589. }
  3590. if (!nameNode) continue;
  3591. const raw = getNodeText(nameNode, this.source);
  3592. // Imported names are simple identifiers; defensively take the last segment.
  3593. const local = raw.includes('.') ? raw.split('.').pop()! : raw;
  3594. if (!local) continue;
  3595. this.unresolvedReferences.push({
  3596. fromNodeId,
  3597. referenceName: local,
  3598. referenceKind: 'imports',
  3599. line: nameNode.startPosition.row + 1,
  3600. column: nameNode.startPosition.column,
  3601. });
  3602. }
  3603. }
  3604. /**
  3605. * Extract a function call
  3606. */
  3607. /**
  3608. * The module an Erlang gen_server target expression statically names, or
  3609. * null when it's dynamic (pid/var/tuple form). Static shapes:
  3610. * - a bare atom — either this module or another one; OTP's dominant
  3611. * registration convention (`{local, ?MODULE}`) names a server process
  3612. * after its module, so `gen_server:call(other_mod, …)` reaches
  3613. * `other_mod`'s handlers. A registered name that matches no module
  3614. * resolves to nothing downstream (the qualified ref just drops).
  3615. * - `?MODULE`, or a macro the file defines as `?MODULE`
  3616. * (`-define(SERVER, ?MODULE)` — the standard self idiom)
  3617. * - a macro the file defines as a bare atom
  3618. * (`-define(STORE, kv_store)` — the cross-module variant)
  3619. * The macro tables are memoized per file (single entry — extraction is
  3620. * file-sequential).
  3621. */
  3622. private erlangServerMacroFile = '';
  3623. private erlangSelfMacros = new Set<string>();
  3624. private erlangAtomMacros = new Map<string, string>();
  3625. private resolveErlangGenServerTarget(target: SyntaxNode): string | null {
  3626. const ownModule = (this.filePath.split('/').pop() ?? '').replace(/\.erl$/, '');
  3627. if (target.type === 'atom') {
  3628. const name = getNodeText(target, this.source).replace(/^'([\s\S]*)'$/, '$1');
  3629. return name || null;
  3630. }
  3631. if (target.type !== 'macro_call_expr') return null;
  3632. const nameNode = getChildByField(target, 'name');
  3633. if (!nameNode) return null;
  3634. const macroName = getNodeText(nameNode, this.source);
  3635. if (macroName === 'MODULE') return ownModule || null;
  3636. if (this.erlangServerMacroFile !== this.filePath) {
  3637. this.erlangServerMacroFile = this.filePath;
  3638. this.erlangSelfMacros = new Set<string>();
  3639. this.erlangAtomMacros = new Map<string, string>();
  3640. let root: SyntaxNode = target;
  3641. while (root.parent) root = root.parent;
  3642. for (let i = 0; i < root.namedChildCount; i++) {
  3643. const form = root.namedChild(i);
  3644. if (form?.type !== 'pp_define') continue;
  3645. const lhs = getChildByField(form, 'lhs');
  3646. const defName = lhs ? getChildByField(lhs, 'name') : null;
  3647. const replacement = getChildByField(form, 'replacement');
  3648. if (!defName || !replacement) continue;
  3649. if (
  3650. replacement.type === 'macro_call_expr' &&
  3651. getChildByField(replacement, 'name') &&
  3652. getNodeText(getChildByField(replacement, 'name')!, this.source) === 'MODULE'
  3653. ) {
  3654. this.erlangSelfMacros.add(getNodeText(defName, this.source));
  3655. } else if (replacement.type === 'atom') {
  3656. this.erlangAtomMacros.set(
  3657. getNodeText(defName, this.source),
  3658. getNodeText(replacement, this.source).replace(/^'([\s\S]*)'$/, '$1'),
  3659. );
  3660. }
  3661. }
  3662. }
  3663. if (this.erlangSelfMacros.has(macroName)) return ownModule || null;
  3664. return this.erlangAtomMacros.get(macroName) ?? null;
  3665. }
  3666. private extractCall(node: SyntaxNode): void {
  3667. if (this.nodeStack.length === 0) return;
  3668. const callerId = this.nodeStack[this.nodeStack.length - 1];
  3669. if (!callerId) return;
  3670. // VB.NET: `foo(args)` is syntactically ambiguous between a call and an
  3671. // index read, so the grammar parses non-empty parens as
  3672. // array_access_expression (field `array`, not `function`) — even Roslyn
  3673. // parses both as InvocationExpression and resolves during binding. Treat
  3674. // all three shapes as call sites: the callee is the member/identifier
  3675. // under the array/function field, qualified with a simple-identifier
  3676. // receiver for resolution. Index reads on collections simply never
  3677. // resolve to a callable, so they cost nothing.
  3678. if (
  3679. this.language === 'vbnet' &&
  3680. (node.type === 'array_access_expression' ||
  3681. node.type === 'invocation_expression' ||
  3682. node.type === 'generic_invocation_expression')
  3683. ) {
  3684. const fn = getChildByField(node, 'function') || getChildByField(node, 'array');
  3685. if (!fn) return;
  3686. let calleeName = '';
  3687. if (fn.type === 'member_access_expression') {
  3688. const member = getChildByField(fn, 'member');
  3689. const memberName = member ? getNodeText(member, this.source) : '';
  3690. if (!memberName) return;
  3691. const receiver = getChildByField(fn, 'object');
  3692. const SKIP = new Set(['me', 'mybase', 'myclass']);
  3693. if (receiver && receiver.type === 'identifier' && !SKIP.has(getNodeText(receiver, this.source).toLowerCase())) {
  3694. calleeName = `${getNodeText(receiver, this.source)}.${memberName}`;
  3695. } else {
  3696. calleeName = memberName;
  3697. }
  3698. } else if (fn.type === 'identifier') {
  3699. calleeName = getNodeText(fn, this.source);
  3700. } else {
  3701. return; // parenthesized/chained receivers: no static name to link
  3702. }
  3703. if (calleeName) {
  3704. this.unresolvedReferences.push({
  3705. fromNodeId: callerId,
  3706. referenceName: calleeName,
  3707. referenceKind: 'calls',
  3708. line: node.startPosition.row + 1,
  3709. column: node.startPosition.column,
  3710. });
  3711. }
  3712. return;
  3713. }
  3714. // Erlang: a local call is `call(expr: atom, args)`; a remote call nests it
  3715. // under `remote(module: remote_module, fun: call)` — the module qualifier
  3716. // lives on the PARENT. Arity is part of a function's identity (#1610), so
  3717. // refs carry the call-site arity: remote calls are emitted as `mod::fn/2`,
  3718. // byte-identical to the qualifiedName the module namespace + arity suffix
  3719. // gives every function (see languages/erlang.ts), so they resolve via
  3720. // matchByQualifiedName; local calls are emitted `fn/2` and resolved by the
  3721. // erlang arity step in matchReference (same-file first). A var/macro callee
  3722. // or module (`F(X)`, `?M(X)`, `Mod:handle(X)`) has no static target —
  3723. // except `?MODULE:fn(X)`, which the bare-name-with-arity + same-file
  3724. // preference resolves correctly. `fun name/1` / `fun mod:name/1` values
  3725. // are function REFERENCES (callback registration) carrying their own
  3726. // written arity, and record construction/update/index/field-access are
  3727. // `references` to the record's struct node.
  3728. if (this.language === 'erlang') {
  3729. const line = node.startPosition.row + 1;
  3730. const column = node.startPosition.column;
  3731. const erlAtom = (n: SyntaxNode): string => getNodeText(n, this.source).replace(/^'([\s\S]*)'$/, '$1');
  3732. if (node.type === 'call') {
  3733. let callee = getChildByField(node, 'expr');
  3734. let moduleNode: SyntaxNode | null = null;
  3735. // remote(module, fun: call) — the shape the grammar produces today; the
  3736. // node-types also permit call(expr: remote), so handle both nestings.
  3737. if (node.parent?.type === 'remote') {
  3738. moduleNode = getChildByField(node.parent, 'module');
  3739. } else if (callee?.type === 'remote') {
  3740. moduleNode = getChildByField(callee, 'module');
  3741. callee = getChildByField(callee, 'fun');
  3742. }
  3743. if (callee?.type === 'atom') {
  3744. const fnBare = erlAtom(callee);
  3745. let calleeName = fnBare;
  3746. const moduleExpr = moduleNode ? getChildByField(moduleNode, 'module') : null;
  3747. if (moduleExpr?.type === 'atom') {
  3748. calleeName = `${erlAtom(moduleExpr)}::${calleeName}`;
  3749. } else if (moduleExpr) {
  3750. // Non-atom module qualifier. `?MODULE:f(X)` targets THIS module —
  3751. // keep the bare name so same-file preference resolves it. Anything
  3752. // else (`Mod:f(X)`) is behaviour-style dynamic dispatch with no
  3753. // static target: emitting the bare name would link an arbitrary
  3754. // same-named function, so stay silent instead.
  3755. const macroName =
  3756. moduleExpr.type === 'macro_call_expr' ? getChildByField(moduleExpr, 'name') : null;
  3757. if (!macroName || getNodeText(macroName, this.source) !== 'MODULE') return;
  3758. }
  3759. // Arity from the call site's own argument list — part of the callee's
  3760. // identity, and what disambiguates `f/1` from `f/2` (#1610).
  3761. const callArgsNode = getChildByField(node, 'args');
  3762. const callArity = callArgsNode ? callArgsNode.namedChildCount : 0;
  3763. this.unresolvedReferences.push({
  3764. fromNodeId: callerId,
  3765. referenceName: `${calleeName}/${callArity}`,
  3766. referenceKind: 'calls',
  3767. line,
  3768. column,
  3769. });
  3770. // gen_server dispatch: `gen_server:call(?SERVER, Msg)` /
  3771. // `gen_server:cast(other_mod, Msg)` — a request routes to the TARGET
  3772. // module's handle_call/handle_cast. The target is static when the
  3773. // first argument names a module: ?MODULE or a ?MODULE-defined macro
  3774. // (the self API-wrapper idiom), a bare atom (OTP's `{local, ?MODULE}`
  3775. // convention names a server after its module, so a cross-module
  3776. // registered name reaches that module's handlers — and a registered
  3777. // name matching no module resolves to nothing), or a macro defined
  3778. // as a bare atom. Pid/var/tuple targets stay silent.
  3779. if (
  3780. moduleExpr?.type === 'atom' &&
  3781. erlAtom(moduleExpr) === 'gen_server' &&
  3782. (fnBare === 'call' || fnBare === 'cast' || fnBare === 'send_request')
  3783. ) {
  3784. const argsNode = getChildByField(node, 'args');
  3785. const target = argsNode?.namedChild(0) ?? null;
  3786. const targetModule = target ? this.resolveErlangGenServerTarget(target) : null;
  3787. if (targetModule) {
  3788. // OTP fixes the handler arities: handle_call/3, handle_cast/2.
  3789. this.unresolvedReferences.push({
  3790. fromNodeId: callerId,
  3791. referenceName: `${targetModule}::${fnBare === 'cast' ? 'handle_cast/2' : 'handle_call/3'}`,
  3792. referenceKind: 'calls',
  3793. line,
  3794. column,
  3795. });
  3796. }
  3797. }
  3798. // MFA-in-argument dispatch: the spawn/apply family names its real
  3799. // callee in ARGUMENT position — `proc_lib:spawn_link(?MODULE,
  3800. // request_process, [Req, Env, Middlewares])` — so the walker above
  3801. // sees only the spawn itself and the spawned function ends up with
  3802. // zero callers (measured on cowboy: request_process had no incoming
  3803. // edges and the agent Read the file to find it). When the (Module,
  3804. // Function) pair is static, lift it as a call edge. The pair is
  3805. // found positionally-agnostically (first adjacent module-atom/
  3806. // ?MODULE + atom pair) so every arity variant works: spawn/3,
  3807. // spawn(Node,M,F,A)/4, timer:apply_after(Time,M,F,A),
  3808. // rpc:call(Node,M,F,A). A var module or fun stays silent.
  3809. const familyKey = moduleExpr?.type === 'atom' ? `${erlAtom(moduleExpr)}:${fnBare}` : fnBare;
  3810. if (ERLANG_MFA_CALLS.has(familyKey)) {
  3811. const argsNode = getChildByField(node, 'args');
  3812. const argExprs = argsNode ? argsNode.namedChildren : [];
  3813. for (let i = 0; i + 1 < argExprs.length; i++) {
  3814. const m = argExprs[i]!;
  3815. const f = argExprs[i + 1]!;
  3816. if (f.type !== 'atom') continue;
  3817. const isLocalModule =
  3818. m.type === 'macro_call_expr' &&
  3819. getChildByField(m, 'name') !== null &&
  3820. getNodeText(getChildByField(m, 'name')!, this.source) === 'MODULE';
  3821. if (m.type !== 'atom' && !isLocalModule) continue;
  3822. // Arity of the spawned/applied function = the length of the
  3823. // static args-list literal directly after the (M, F) pair, when
  3824. // present (`spawn_link(?MODULE, request_process, [Req, Env])` →
  3825. // /2). A var/absent list leaves the ref arity-less; the
  3826. // qualified matcher then resolves it only when the module
  3827. // defines exactly one arity of that name.
  3828. const mfaList = argExprs[i + 2];
  3829. const arityTail = mfaList?.type === 'list' ? `/${mfaList.namedChildCount}` : '';
  3830. this.unresolvedReferences.push({
  3831. fromNodeId: callerId,
  3832. referenceName: (isLocalModule ? erlAtom(f) : `${erlAtom(m)}::${erlAtom(f)}`) + arityTail,
  3833. referenceKind: 'calls',
  3834. line: f.startPosition.row + 1,
  3835. column: f.startPosition.column,
  3836. });
  3837. break;
  3838. }
  3839. }
  3840. }
  3841. return;
  3842. }
  3843. if (node.type === 'internal_fun' || node.type === 'external_fun') {
  3844. const funNode = getChildByField(node, 'fun');
  3845. if (funNode?.type !== 'atom') return; // fun Mod:F/A with var parts — dynamic
  3846. let refName = erlAtom(funNode);
  3847. if (node.type === 'external_fun') {
  3848. const moduleWrapper = getChildByField(node, 'module');
  3849. const moduleAtom = moduleWrapper ? getChildByField(moduleWrapper, 'name') : null;
  3850. if (moduleAtom?.type !== 'atom') return;
  3851. refName = `${erlAtom(moduleAtom)}::${refName}`;
  3852. }
  3853. // `fun f/1` writes its arity — carry it so the ref lands on the
  3854. // matching arity's node (#1610).
  3855. const funArityNode = getChildByField(node, 'arity');
  3856. const funArityValue = funArityNode ? getChildByField(funArityNode, 'value') : null;
  3857. if (funArityValue) refName = `${refName}/${getNodeText(funArityValue, this.source)}`;
  3858. this.unresolvedReferences.push({
  3859. fromNodeId: callerId,
  3860. referenceName: refName,
  3861. referenceKind: 'references',
  3862. line,
  3863. column,
  3864. });
  3865. return;
  3866. }
  3867. if (node.type === 'macro_call_expr') {
  3868. // Macro use site → the `-define` constant node. Function-like uses
  3869. // (`?LOG_AUDIT(X)` — args present) are inlined code, so they join the
  3870. // call chain and connect through the macro node to the body's calls
  3871. // (attributed there by handlePpDefine); bare reads (`?TIMEOUT`) are
  3872. // `references`, answering "where is this macro used" without
  3873. // polluting call paths. Compiler-predefined macros carry no
  3874. // definition to link. The use site's ARGUMENTS are children and keep
  3875. // walking, so a call nested in `?assertEqual(ok, do_thing())` still
  3876. // attributes to the enclosing function.
  3877. const macroName = getChildByField(node, 'name');
  3878. if (!macroName) return;
  3879. const name = getNodeText(macroName, this.source);
  3880. if (ERLANG_PREDEFINED_MACROS.has(name)) return;
  3881. this.unresolvedReferences.push({
  3882. fromNodeId: callerId,
  3883. referenceName: name,
  3884. referenceKind: getChildByField(node, 'args') ? 'calls' : 'references',
  3885. line,
  3886. column,
  3887. });
  3888. return;
  3889. }
  3890. // record_expr / record_update_expr / record_index_expr / record_field_expr
  3891. const recordName = getChildByField(node, 'name');
  3892. const recordAtom = recordName?.type === 'record_name' ? getChildByField(recordName, 'name') : null;
  3893. if (recordAtom?.type === 'atom') {
  3894. this.unresolvedReferences.push({
  3895. fromNodeId: callerId,
  3896. referenceName: erlAtom(recordAtom),
  3897. referenceKind: 'references',
  3898. line,
  3899. column,
  3900. });
  3901. }
  3902. return;
  3903. }
  3904. // Ruby `call` nodes use `receiver` + `method` fields (tree-sitter-ruby), not
  3905. // the `object`/`name`/`function` fields the branches below expect — so
  3906. // without this they fell through to the generic path, which took the
  3907. // receiver as the callee and DROPPED the method name: `lg.log()` produced a
  3908. // `calls` ref to `lg` (unresolvable) and no method edge was ever recorded,
  3909. // so a Ruby method's callers/impact were invisible (#1108 follow-up). Build
  3910. // `receiver.method` so the resolver — and local-variable type inference —
  3911. // can link it; `Foo.new` stays an instantiation.
  3912. if (this.language === 'ruby' && (node.type === 'call' || node.type === 'method_call')) {
  3913. const methodNode = getChildByField(node, 'method');
  3914. const methodName = methodNode ? getNodeText(methodNode, this.source) : '';
  3915. if (!methodName) return; // operator/element-reference call with no method name
  3916. const receiverNode = getChildByField(node, 'receiver');
  3917. const line = node.startPosition.row + 1;
  3918. const column = node.startPosition.column;
  3919. if (!receiverNode) {
  3920. // Bare `foo(...)` — just the method name (unchanged behavior).
  3921. this.unresolvedReferences.push({ fromNodeId: callerId, referenceName: methodName, referenceKind: 'calls', line, column });
  3922. return;
  3923. }
  3924. const receiverName = getNodeText(receiverNode, this.source);
  3925. // `Foo.new` / `Foo::Bar.new` is construction — emit an `instantiates` ref to
  3926. // the class (last `::` segment), preserving the "what creates X" edge.
  3927. if (methodName === 'new') {
  3928. const className = receiverName.includes('::')
  3929. ? receiverName.slice(receiverName.lastIndexOf('::') + 2)
  3930. : receiverName;
  3931. if (/^[A-Z]/.test(className)) {
  3932. this.unresolvedReferences.push({ fromNodeId: callerId, referenceName: className, referenceKind: 'instantiates', line, column });
  3933. return;
  3934. }
  3935. }
  3936. const SKIP_RECEIVERS = new Set(['self', 'super']);
  3937. const skip = SKIP_RECEIVERS.has(receiverName);
  3938. this.unresolvedReferences.push({
  3939. fromNodeId: callerId,
  3940. referenceName: skip ? methodName : `${receiverName}.${methodName}`,
  3941. referenceKind: 'calls',
  3942. line,
  3943. column,
  3944. });
  3945. // A capitalized (constant) receiver — `Foo.bar`, a class/module method call
  3946. // — is itself a dependency on that constant; emit a `references` ref so a
  3947. // class used only via its class methods still records a dependent (the edge
  3948. // the old receiver-only callee happened to provide, now made explicit).
  3949. if (!skip && receiverNode.type === 'constant') {
  3950. this.unresolvedReferences.push({
  3951. fromNodeId: callerId,
  3952. referenceName: receiverName,
  3953. referenceKind: 'references',
  3954. line: receiverNode.startPosition.row + 1,
  3955. column: receiverNode.startPosition.column,
  3956. });
  3957. }
  3958. return;
  3959. }
  3960. // ArkTS build()-DSL handling. Three shapes carry UI-attribute chains, and
  3961. // all of their attribute names are emitted with a LEADING DOT
  3962. // (`.titleStyle`, `.width`) — an impossible identifier that routes them to
  3963. // a dedicated matcher strategy resolving ONLY to decorator-marked
  3964. // attribute helpers (`@Extend`/`@Styles`/`@AnimatableExtend`/`@Builder`
  3965. // functions). Bare names would go through global name matching, where
  3966. // framework attributes (`.width`, `.fontSize`, appearing on nearly every
  3967. // UI line) hit arbitrary same-named symbols — measured on the OpenHarmony
  3968. // samples monorepo, that produced 36k wrong edges (17% of all calls),
  3969. // including single properties with 3,400+ false callers.
  3970. //
  3971. // 1. `Column({space:8}) { … }.height('100%')` — ONE
  3972. // arkui_component_expression: `function:` = the component, chained
  3973. // attributes as repeated `property:`/`arguments:` field pairs.
  3974. // The component ref (`Column`, `TodoRow`) stays a PLAIN name — it
  3975. // resolves to the child `@Component struct`, giving the parent→child
  3976. // component-tree edge the way JSX children do for React.
  3977. // 2. `Image(x).width(10).onClick(this.f)` — ordinary nested
  3978. // call_expressions whose `function:` is a member_expression chained
  3979. // on a CALL RESULT (never a named receiver, so `svc.save()` /
  3980. // `this.vm.load()` are untouched and fall through to the generic
  3981. // paths below).
  3982. // 3. A nested component whose chain starts on the line AFTER its
  3983. // closing `}` inside arkui_children — the grammar detaches the chain
  3984. // into sibling `leading_dot_expression(identifier)` +
  3985. // `parenthesized_expression(args)` statement pairs; reassemble from
  3986. // the siblings.
  3987. //
  3988. // `.onXxx(this.handler)` METHOD-REFERENCE bindings (no call parens, so
  3989. // nothing else records them) additionally emit a call ref to the bare
  3990. // handler name — same-class resolution links the tap→handler hop.
  3991. // Arrow-function handlers need nothing: their bodies' calls already
  3992. // attribute to the enclosing build(). Children/argument subtrees are
  3993. // still walked by the caller, so nested components extract normally.
  3994. if (this.language === 'arkts') {
  3995. const emitAttr = (nameNode: SyntaxNode): void => {
  3996. const attrName = getNodeText(nameNode, this.source);
  3997. if (!attrName) return;
  3998. this.unresolvedReferences.push({
  3999. fromNodeId: callerId,
  4000. referenceName: '.' + attrName,
  4001. referenceKind: 'calls',
  4002. line: nameNode.startPosition.row + 1,
  4003. column: nameNode.startPosition.column,
  4004. });
  4005. };
  4006. // Emit `handler` for each bare `this.handler` among an on-attribute's
  4007. // arguments.
  4008. const emitThisHandlers = (args: SyntaxNode | null): void => {
  4009. if (!args) return;
  4010. for (let j = 0; j < args.namedChildCount; j++) {
  4011. const arg = args.namedChild(j);
  4012. if (arg?.type !== 'member_expression') continue;
  4013. const obj = getChildByField(arg, 'object');
  4014. const prop = getChildByField(arg, 'property');
  4015. if (obj?.type === 'this' && prop) {
  4016. this.unresolvedReferences.push({
  4017. fromNodeId: callerId,
  4018. referenceName: getNodeText(prop, this.source),
  4019. referenceKind: 'calls',
  4020. line: arg.startPosition.row + 1,
  4021. column: arg.startPosition.column,
  4022. });
  4023. }
  4024. }
  4025. };
  4026. // Shape 1: arkui_component_expression with property/arguments pairs.
  4027. if (node.type === 'arkui_component_expression') {
  4028. const componentField = getChildByField(node, 'function');
  4029. if (componentField && componentField.type === 'identifier') {
  4030. this.unresolvedReferences.push({
  4031. fromNodeId: callerId,
  4032. referenceName: getNodeText(componentField, this.source),
  4033. referenceKind: 'calls',
  4034. line: node.startPosition.row + 1,
  4035. column: node.startPosition.column,
  4036. });
  4037. }
  4038. for (let i = 0; i < node.childCount; i++) {
  4039. const child = node.child(i);
  4040. if (!child || child.type !== 'property_identifier') continue;
  4041. emitAttr(child);
  4042. if (/^on[A-Z]/.test(getNodeText(child, this.source))) {
  4043. // The attribute's arguments node is the next `arguments`-typed
  4044. // child before the following attribute name.
  4045. let args: SyntaxNode | null = null;
  4046. for (let k = i + 1; k < node.childCount; k++) {
  4047. const next = node.child(k);
  4048. if (!next) continue;
  4049. if (next.type === 'property_identifier') break;
  4050. if (next.type === 'arguments') {
  4051. args = next;
  4052. break;
  4053. }
  4054. }
  4055. emitThisHandlers(args);
  4056. }
  4057. }
  4058. return;
  4059. }
  4060. // Shape 2: fluent chain on a call result —
  4061. // call_expression(function: member_expression(object: <call>)), or the
  4062. // grammar's DSL-specific arkui_dsl_decorator_member_expression (same
  4063. // object/property fields; produced e.g. by `Column() { … }.alignItems(x)`
  4064. // in some chain positions — it ONLY occurs in attribute chains).
  4065. if (node.type === 'call_expression') {
  4066. const fn = getChildByField(node, 'function');
  4067. if (fn?.type === 'member_expression' || fn?.type === 'arkui_dsl_decorator_member_expression') {
  4068. const obj = getChildByField(fn, 'object');
  4069. const prop = getChildByField(fn, 'property');
  4070. if (
  4071. prop &&
  4072. (fn.type === 'arkui_dsl_decorator_member_expression' ||
  4073. obj?.type === 'call_expression' ||
  4074. obj?.type === 'arkui_component_expression')
  4075. ) {
  4076. emitAttr(prop);
  4077. if (/^on[A-Z]/.test(getNodeText(prop, this.source))) {
  4078. emitThisHandlers(getChildByField(node, 'arguments'));
  4079. }
  4080. return;
  4081. }
  4082. }
  4083. // The INNERMOST call of a proper-form detached chain
  4084. // (`.alignItems(x).layoutWeight(1)…` under a leading_dot_expression)
  4085. // has a BARE IDENTIFIER function — the leading dot was consumed by
  4086. // the wrapper, so it masquerades as a plain `alignItems(...)` call.
  4087. // Walk up the member/call alternation; topping out at
  4088. // leading_dot_expression means the dot belongs to this chain.
  4089. if (fn?.type === 'identifier') {
  4090. let p: SyntaxNode | null = node.parent;
  4091. while (p && (p.type === 'member_expression' || p.type === 'call_expression')) {
  4092. p = p.parent;
  4093. }
  4094. if (p?.type === 'leading_dot_expression') {
  4095. emitAttr(fn);
  4096. if (/^on[A-Z]/.test(getNodeText(fn, this.source))) {
  4097. emitThisHandlers(getChildByField(node, 'arguments'));
  4098. }
  4099. return;
  4100. }
  4101. }
  4102. // Not a chained attribute — fall through to the generic call paths.
  4103. }
  4104. // Shape 3: detached chain segment — leading_dot_expression whose only
  4105. // named child is a bare identifier; its arguments sit in the NEXT
  4106. // sibling statement as a parenthesized_expression.
  4107. if (node.type === 'leading_dot_expression') {
  4108. const only = node.namedChildCount === 1 ? node.namedChild(0) : null;
  4109. if (only && only.type === 'identifier') {
  4110. emitAttr(only);
  4111. if (/^on[A-Z]/.test(getNodeText(only, this.source))) {
  4112. const stmt = node.parent; // expression_statement
  4113. const nextStmt = stmt?.nextNamedSibling;
  4114. const paren = nextStmt?.namedChild(0);
  4115. if (paren?.type === 'parenthesized_expression') {
  4116. emitThisHandlers(paren);
  4117. }
  4118. }
  4119. }
  4120. // The proper form (child is a call_expression chain, as inside
  4121. // `@Extend` bodies) needs nothing here — the walker descends into it
  4122. // and the inner call_expressions take the paths above.
  4123. return;
  4124. }
  4125. }
  4126. // Get the function/method being called
  4127. let calleeName = '';
  4128. // Java/Kotlin method_invocation has 'object' + 'name' fields instead of 'function'
  4129. // PHP member_call_expression has 'object' + 'name', scoped_call_expression has 'scope' + 'name'
  4130. const nameField = getChildByField(node, 'name');
  4131. const objectField = getChildByField(node, 'object') || getChildByField(node, 'scope');
  4132. if (nameField && objectField && (node.type === 'method_invocation' || node.type === 'member_call_expression' || node.type === 'scoped_call_expression')) {
  4133. // Method call with explicit receiver: receiver.method() / $receiver->method() / ClassName::method()
  4134. const methodName = getNodeText(nameField, this.source);
  4135. // Java `this.userbo.toLogin2()` parses as method_invocation(object=field_access(this, userbo)).
  4136. // Without unwrapping, receiverName is `this.userbo` and the name-matcher's
  4137. // single-dot receiver regex fails. Pull out the immediate field after `this.`
  4138. // so the receiver is the field name (`userbo`), which the resolver can then
  4139. // look up in the enclosing class's field declarations.
  4140. // PHP static-factory fluent chain: `Cls::for($x)->method()` — the receiver
  4141. // is itself a static call, so resolution must infer the method's class
  4142. // from what `Cls::for` RETURNS (its `: self` / `: static` / `: Type`),
  4143. // #608 (mirrors the C++ chain fix in #645). Encode `<Cls::factory>().<method>`;
  4144. // the `().` marker lets the PHP resolver split it. The receiver text
  4145. // (`Cls::for('x')`) carries the args, so without this it degrades to an
  4146. // unresolvable string and the call edge is dropped.
  4147. if (methodName && this.language === 'php' && objectField.type === 'scoped_call_expression') {
  4148. const innerScope = getChildByField(objectField, 'scope');
  4149. const innerName = getChildByField(objectField, 'name');
  4150. if (innerScope && innerName) {
  4151. calleeName = `${getNodeText(innerScope, this.source)}::${getNodeText(innerName, this.source)}().${methodName}`;
  4152. } else {
  4153. calleeName = methodName;
  4154. }
  4155. if (calleeName) {
  4156. this.unresolvedReferences.push({
  4157. fromNodeId: callerId,
  4158. referenceName: calleeName,
  4159. referenceKind: 'calls',
  4160. line: node.startPosition.row + 1,
  4161. column: node.startPosition.column,
  4162. });
  4163. }
  4164. return;
  4165. }
  4166. // Java static-factory / fluent chain: `Foo.getInstance().bar()` — the
  4167. // receiver is itself a method call, so resolution must infer bar's class
  4168. // from what `Foo.getInstance` RETURNS (its declared return type), the
  4169. // #645/#608 mechanism. Encode `<inner-receiver>.<inner-method>().<method>`;
  4170. // the `().` marker lets the Java chain resolver split it, and normalizing to
  4171. // empty parens drops any factory args (`Foo.create(cfg).bar()`) that would
  4172. // otherwise leave a `(cfg)` in the receiver text and break the split.
  4173. if (
  4174. methodName &&
  4175. this.language === 'java' &&
  4176. objectField.type === 'method_invocation'
  4177. ) {
  4178. const innerObj = getChildByField(objectField, 'object');
  4179. const innerName = getChildByField(objectField, 'name');
  4180. if (innerObj && innerName) {
  4181. calleeName = `${getNodeText(innerObj, this.source)}.${getNodeText(innerName, this.source)}().${methodName}`;
  4182. this.unresolvedReferences.push({
  4183. fromNodeId: callerId,
  4184. referenceName: calleeName,
  4185. referenceKind: 'calls',
  4186. line: node.startPosition.row + 1,
  4187. column: node.startPosition.column,
  4188. });
  4189. return;
  4190. }
  4191. }
  4192. let receiverName: string;
  4193. if (objectField.type === 'field_access') {
  4194. const inner = getChildByField(objectField, 'object');
  4195. const fld = getChildByField(objectField, 'field');
  4196. if (inner && fld && (inner.type === 'this' || inner.type === 'this_expression')) {
  4197. receiverName = getNodeText(fld, this.source);
  4198. } else {
  4199. receiverName = getNodeText(objectField, this.source);
  4200. }
  4201. } else {
  4202. receiverName = getNodeText(objectField, this.source);
  4203. }
  4204. // Strip PHP $ prefix from variable names
  4205. receiverName = receiverName.replace(/^\$/, '');
  4206. if (methodName) {
  4207. // Skip self/this/parent/static receivers — they don't aid resolution
  4208. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super', 'parent', 'static']);
  4209. if (SKIP_RECEIVERS.has(receiverName)) {
  4210. calleeName = methodName;
  4211. } else {
  4212. calleeName = `${receiverName}.${methodName}`;
  4213. }
  4214. }
  4215. } else if (node.type === 'message_expression') {
  4216. // ObjC message expressions emit one `method` field child per selector
  4217. // keyword: `[obj a:1 b:2 c:3]` has three `method=identifier` siblings.
  4218. // Joining them with `:` reconstructs the full selector and matches the
  4219. // multi-part selector names produced by the ObjC method_definition
  4220. // extractor (`extractObjcMethodName` in languages/objc.ts). Without this
  4221. // join, multi-keyword call sites only emitted the first keyword and never
  4222. // resolved to their target methods (e.g. `GET:parameters:headers:...` had
  4223. // zero callers despite obviously being called).
  4224. const methodKeywords: string[] = [];
  4225. for (let i = 0; i < node.namedChildCount; i++) {
  4226. if (node.fieldNameForNamedChild(i) === 'method') {
  4227. const kw = node.namedChild(i);
  4228. if (kw) methodKeywords.push(getNodeText(kw, this.source));
  4229. }
  4230. }
  4231. if (methodKeywords.length > 0) {
  4232. // A selector keyword takes a `:` when it has an argument. A SINGLE
  4233. // keyword can be unary (`[c reset]` → `reset`) OR take one argument
  4234. // (`[c storeImage:k]` → `storeImage:`) — distinguished by whether the
  4235. // message has a `:` token. Without this, every single-argument message
  4236. // (the most common form: `addObject:`, `storeImage:`, …) was named
  4237. // without the colon and never matched its `storeImage:` method.
  4238. let hasColon = false;
  4239. for (let i = 0; i < node.childCount; i++) {
  4240. if (node.child(i)?.type === ':') { hasColon = true; break; }
  4241. }
  4242. const methodName: string = hasColon
  4243. ? methodKeywords.map((k) => `${k}:`).join('')
  4244. : (methodKeywords[0] as string);
  4245. const receiverField = getChildByField(node, 'receiver');
  4246. const SKIP_RECEIVERS = new Set(['self', 'super']);
  4247. if (receiverField && receiverField.type !== 'message_expression') {
  4248. const receiverName = getNodeText(receiverField, this.source);
  4249. if (receiverName && !SKIP_RECEIVERS.has(receiverName)) {
  4250. calleeName = `${receiverName}.${methodName}`;
  4251. // A CLASS-message receiver (`[SDImageCache alloc]`,
  4252. // `[SDImageCache sharedCache]`) is a capitalized class name. The
  4253. // call resolves the method (`alloc`/`sharedCache`), but the CLASS
  4254. // itself — whose @interface lives in the header — would otherwise
  4255. // never be referenced. Emit a `references` edge to it so a class
  4256. // used only via class messages (alloc/init, singletons, factories)
  4257. // and its header record a dependent.
  4258. if (/^[A-Z][A-Za-z0-9_]*$/.test(receiverName)) {
  4259. this.unresolvedReferences.push({
  4260. fromNodeId: callerId,
  4261. referenceName: receiverName,
  4262. referenceKind: 'references',
  4263. line: receiverField.startPosition.row + 1,
  4264. column: receiverField.startPosition.column,
  4265. });
  4266. }
  4267. } else {
  4268. calleeName = methodName;
  4269. }
  4270. } else if (receiverField && receiverField.type === 'message_expression' && /^\w+$/.test(methodName)) {
  4271. // Chained message send `[[Foo create] doIt]` — the receiver is itself a
  4272. // class message. Recover the inner `Class.selector` and encode
  4273. // `Class.selector().doIt` so resolution infers doIt's class from what
  4274. // `Class.selector` RETURNS (#645/#608). Only a CLASS-factory chain
  4275. // (capitalized inner receiver); a unary outer selector is required
  4276. // because the chain resolver's method part is `\w+` (no `:`). An
  4277. // instance chain (`[[obj foo] bar]`, lowercase inner) stays bare.
  4278. const innerRecv = getChildByField(receiverField, 'receiver');
  4279. const innerRecvName = innerRecv ? getNodeText(innerRecv, this.source) : '';
  4280. if (innerRecv?.type === 'identifier' && /^[A-Z]/.test(innerRecvName)) {
  4281. const innerKw: string[] = [];
  4282. for (let i = 0; i < receiverField.namedChildCount; i++) {
  4283. if (receiverField.fieldNameForNamedChild(i) === 'method') {
  4284. const kw = receiverField.namedChild(i);
  4285. if (kw) innerKw.push(getNodeText(kw, this.source));
  4286. }
  4287. }
  4288. let innerColon = false;
  4289. for (let i = 0; i < receiverField.childCount; i++) {
  4290. if (receiverField.child(i)?.type === ':') { innerColon = true; break; }
  4291. }
  4292. const innerSelector = innerColon ? innerKw.map((k) => `${k}:`).join('') : innerKw[0];
  4293. calleeName = innerSelector ? `${innerRecvName}.${innerSelector}().${methodName}` : methodName;
  4294. } else {
  4295. calleeName = methodName;
  4296. }
  4297. } else {
  4298. calleeName = methodName;
  4299. }
  4300. }
  4301. } else {
  4302. const func = getChildByField(node, 'function') || node.namedChild(0);
  4303. // C++ explicit operator call `a.operator+(b)` / `p->operator+(b)` (#1247):
  4304. // tree-sitter-cpp can't parse an operator_name in field position, so the
  4305. // callee is NOT a field_expression — the call_expression carries
  4306. // `function: <receiver>` plus an ERROR child wrapping the operator_name.
  4307. // Reading the function field alone yields just the receiver (`a`), an
  4308. // unresolvable ref. Recover `<receiver>.operator+` so it resolves like any
  4309. // other member call (matchMethodCall admits the operator method part).
  4310. // The infix forms `a + b` / `a[i]` need receiver type inference and are
  4311. // tracked separately (#1258).
  4312. if (this.language === 'cpp' && func) {
  4313. let operatorName = '';
  4314. for (let i = 0; i < node.namedChildCount; i++) {
  4315. const child = node.namedChild(i);
  4316. if (child?.type !== 'ERROR') continue;
  4317. const op = child.namedChildren.find((c: SyntaxNode) => c.type === 'operator_name');
  4318. if (op) { operatorName = getNodeText(op, this.source); break; }
  4319. }
  4320. if (operatorName) {
  4321. // Call sites may space the symbolic name (nlohmann/json's
  4322. // `it.operator * ()`, `other.operator < (*this)`) while definitions
  4323. // index compact (`operator*`) — normalize so they match. The word
  4324. // forms (`operator new`) keep their space.
  4325. const sym = operatorName.slice('operator'.length).trim();
  4326. if (/^[^\w\s]/.test(sym)) operatorName = `operator${sym.replace(/\s+/g, '')}`;
  4327. // `->` receivers resolve identically to `.` ones. A receiver that
  4328. // isn't a simple identifier/member chain (`(*it)`, a call result, …)
  4329. // can't aid type inference, and a bare operator name would fall
  4330. // through to exact-name matching — which GUESSES among the many
  4331. // same-named operators (on nlohmann/json it linked a std::map
  4332. // `object->operator[]` call to an unrelated in-repo operator[]).
  4333. // Drop the ref: a silent miss, never a wrong edge. `this->` keeps
  4334. // the bare name, matching how `this.method()` calls are emitted —
  4335. // the target is on the enclosing class, where exact-name's same-file
  4336. // preference is reliable.
  4337. const receiver = getNodeText(func, this.source).replace(/->/g, '.').replace(/\s+/g, '');
  4338. if (receiver !== 'this' && !/^[A-Za-z_][\w.]*$/.test(receiver)) return;
  4339. const calleeName = receiver === 'this' ? operatorName : `${receiver}.${operatorName}`;
  4340. this.unresolvedReferences.push({
  4341. fromNodeId: callerId,
  4342. referenceName: calleeName,
  4343. referenceKind: 'calls',
  4344. line: node.startPosition.row + 1,
  4345. column: node.startPosition.column,
  4346. });
  4347. return;
  4348. }
  4349. }
  4350. if (func) {
  4351. if (func.type === 'member_expression' || func.type === 'attribute' || func.type === 'selector_expression' || func.type === 'navigation_expression' || func.type === 'field_expression') {
  4352. // Method call: obj.method() or obj.field.method()
  4353. // Go uses selector_expression with 'field', JS/TS uses member_expression with 'property'
  4354. // Kotlin uses navigation_expression with navigation_suffix > simple_identifier
  4355. // C/C++ use field_expression for both `obj.method()` and `ptr->method()`
  4356. let property = getChildByField(func, 'property') || getChildByField(func, 'field');
  4357. if (!property) {
  4358. const child1 = func.namedChild(1);
  4359. // Kotlin: navigation_suffix wraps the method name — extract simple_identifier from it
  4360. if (child1?.type === 'navigation_suffix') {
  4361. property = child1.namedChildren.find((c: SyntaxNode) => c.type === 'simple_identifier') ?? child1;
  4362. } else {
  4363. property = child1;
  4364. }
  4365. }
  4366. if (property) {
  4367. const methodName = getNodeText(property, this.source);
  4368. // Include receiver name for qualified resolution (e.g., console.print → "console.print")
  4369. // This helps the resolver distinguish method calls from bare function calls
  4370. // (e.g., Python's console.print() vs builtin print())
  4371. // Skip self/this/cls as they don't aid resolution
  4372. const receiver =
  4373. getChildByField(func, 'object') ||
  4374. getChildByField(func, 'operand') ||
  4375. getChildByField(func, 'argument') ||
  4376. func.namedChild(0);
  4377. // A LITERAL receiver — `", ".join(...)`, `"x".toUpperCase()`,
  4378. // `5.times`, `[].concat(...)` — calls a builtin of the literal's
  4379. // type, never a project symbol. The bare-name fallback below let
  4380. // these exact-match an unrelated same-named project function
  4381. // (`", ".join` bound to a local `join` defined inside a DIFFERENT
  4382. // function, #1230). Emit nothing: a silent miss, never a wrong
  4383. // edge. Nested calls in the arguments are visited independently.
  4384. if (receiver && LITERAL_RECEIVER_TYPES.has(receiver.type)) {
  4385. return;
  4386. }
  4387. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super']);
  4388. if (receiver && (receiver.type === 'identifier' || receiver.type === 'simple_identifier' || receiver.type === 'field_identifier')) {
  4389. const receiverName = getNodeText(receiver, this.source);
  4390. if (!SKIP_RECEIVERS.has(receiverName)) {
  4391. calleeName = `${receiverName}.${methodName}`;
  4392. } else {
  4393. calleeName = methodName;
  4394. }
  4395. } else if (
  4396. this.language === 'rust' &&
  4397. receiver &&
  4398. receiver.type === 'field_expression' &&
  4399. getChildByField(receiver, 'value')?.type === 'self' &&
  4400. getChildByField(receiver, 'field')?.type === 'field_identifier'
  4401. ) {
  4402. // Rust `self.<field>.<method>()` — a call through a field of the
  4403. // enclosing type (#1585). Keep the `self.` prefix: the resolver
  4404. // recognizes the shape, reads the field's declared type off the
  4405. // owner struct's declaration, and resolves the method on THAT
  4406. // type — or leaves the ref unresolved when the type is external
  4407. // or unknown. Previously this collapsed to the bare method name,
  4408. // which exact-matched whichever same-named method was nearest —
  4409. // often the calling method itself, a self-edge not in the source.
  4410. // Deeper chains (`self.a.b.m()`), `self.f().m()` and parenthesized
  4411. // receivers keep the bare name. Mirrored in the kernel's
  4412. // extract_call (rustlang.rs).
  4413. const fieldName = getNodeText(getChildByField(receiver, 'field')!, this.source);
  4414. calleeName = `self.${fieldName}.${methodName}`;
  4415. } else if (
  4416. (this.language === 'cpp' ||
  4417. this.language === 'c' ||
  4418. this.language === 'kotlin' ||
  4419. this.language === 'swift' ||
  4420. this.language === 'rust' ||
  4421. this.language === 'go' ||
  4422. this.language === 'scala') &&
  4423. receiver &&
  4424. receiver.type === 'call_expression'
  4425. ) {
  4426. // Receiver that is itself a call — `Foo::instance().bar()`,
  4427. // `openSession()->run()`, `mgr.view().render()` (C/C++),
  4428. // `Foo.getInstance().bar()` (Kotlin) / `Foo.make().draw()` (Swift),
  4429. // `Foo::new().bar()` (Rust), or `New().Method()` (Go). Keep the inner
  4430. // call so resolution can infer bar()'s class from what the inner call
  4431. // RETURNS (#645/#608). Encode as `<innerCallee>().<method>`; the `().`
  4432. // marker never appears in an ordinary ref, so the resolver can detect
  4433. // and split it. Other languages keep the bare-name behavior below.
  4434. let innerCallee: string;
  4435. let reencode: boolean;
  4436. if (this.language === 'kotlin' || this.language === 'swift') {
  4437. // tree-sitter-kotlin/swift expose the inner callee as the
  4438. // call_expression's first named child (a navigation_expression
  4439. // `Foo.getInstance`, or a bare identifier for a free/constructor call).
  4440. const innerNav = receiver.namedChild(0);
  4441. innerCallee = innerNav ? getNodeText(innerNav, this.source).replace(/\s+/g, '') : '';
  4442. // Only re-encode a CLASS / companion-factory / constructor chain,
  4443. // whose receiver chain starts with a capitalized type
  4444. // (`Foo.getInstance().bar()`, `Foo().bar()`). An instance chain
  4445. // (`list.filter{}.map{}`) has a lowercase receiver whose type we
  4446. // can't recover here — re-encoding it would only drop the edge (no
  4447. // chain resolution, no bare-name fallback), regressing recall in
  4448. // fluent codebases. Leave those to the bare-name path.
  4449. reencode = /^[A-Z]/.test(innerCallee);
  4450. } else {
  4451. const innerFn = getChildByField(receiver, 'function');
  4452. innerCallee = innerFn
  4453. ? getNodeText(innerFn, this.source).replace(/->/g, '.').replace(/\s+/g, '')
  4454. : '';
  4455. // Rust: only re-encode an associated-function chain
  4456. // (`Foo::new().bar()`), whose inner callee is a path/`scoped_identifier`.
  4457. // Go: only a bare package-level factory chain (`New().Method()`),
  4458. // whose inner callee is an `identifier`. An instance chain
  4459. // (`x.foo().bar()` Rust, `obj.Method().Other()` Go) keeps bare-name —
  4460. // the resolver can't recover a variable's type, so re-encoding would
  4461. // only drop the edge. C/C++ re-encode any inner.
  4462. if (this.language === 'rust') reencode = innerFn?.type === 'scoped_identifier';
  4463. else if (this.language === 'go') reencode = innerFn?.type === 'identifier';
  4464. // Scala: only a companion-factory / case-class-apply chain whose
  4465. // receiver chain starts with a capitalized type (`Foo.create().bar()`,
  4466. // `Foo(args).bar()`). An instance chain (`list.map().filter()`) has a
  4467. // lowercase receiver whose type we can't recover — leave it bare.
  4468. else if (this.language === 'scala') reencode = /^[A-Z]/.test(innerCallee);
  4469. else reencode = !!innerCallee;
  4470. }
  4471. calleeName = reencode ? `${innerCallee}().${methodName}` : methodName;
  4472. } else if (
  4473. this.language === 'cfscript' &&
  4474. receiver &&
  4475. receiver.type === 'member_expression' &&
  4476. /^(variables|this|local|arguments)\.[A-Za-z_][\w]*$/i.test(getNodeText(receiver, this.source))
  4477. ) {
  4478. // CFML scope-prefixed member call — `variables.svc.save()` /
  4479. // `arguments.svc.save()`: the receiver is a component field,
  4480. // injected property, or typed argument reached through one of
  4481. // CFML's file-local scopes. Keep the full receiver chain so
  4482. // resolution can strip the scope prefix and infer the field's
  4483. // component type from its declaration (#1108). Gated to these
  4484. // scope keywords: such calls previously emitted a bare method
  4485. // name, which either failed to resolve or resolved ambiguously.
  4486. calleeName = `${getNodeText(receiver, this.source)}.${methodName}`;
  4487. } else if (
  4488. (this.language === 'typescript' ||
  4489. this.language === 'javascript' ||
  4490. this.language === 'tsx' ||
  4491. this.language === 'jsx') &&
  4492. receiver &&
  4493. receiver.type === 'member_expression' &&
  4494. getChildByField(receiver, 'object')?.type === 'this' &&
  4495. getChildByField(receiver, 'property')?.type === 'property_identifier'
  4496. ) {
  4497. // TS/JS call through a field of the enclosing class —
  4498. // `this.mailer.send()` (#1496). Keep the `this.<field>` prefix:
  4499. // the resolver reads the field's declared type off the class's
  4500. // own declaration (`private mailer: Mailer`, `mailer = new
  4501. // Mailer()`) and resolves the method on THAT type — or leaves the
  4502. // ref unresolved when the type is external or unknown. Previously
  4503. // this collapsed to the bare method name, which exact-matched
  4504. // whichever same-named method was nearest — the calling method
  4505. // itself when the two share a name, a self-edge not in the
  4506. // source. Same discipline as Rust's `self.<field>` (#1585).
  4507. // Mirrored in the kernel's extract_call (tsjs/extractors.rs).
  4508. const fieldName = getNodeText(getChildByField(receiver, 'property')!, this.source);
  4509. calleeName = `this.${fieldName}.${methodName}`;
  4510. } else if (
  4511. (this.language === 'typescript' ||
  4512. this.language === 'javascript' ||
  4513. this.language === 'tsx' ||
  4514. this.language === 'jsx' ||
  4515. this.language === 'python') &&
  4516. receiver &&
  4517. (receiver.type === 'call_expression' || receiver.type === 'call')
  4518. ) {
  4519. // Receiver that is itself a call — `d.setdefault(k, []).append(v)`,
  4520. // `make().run()`, `res.json().data` (#1683). The bare method name
  4521. // this used to emit exact-matched any top-level project symbol of
  4522. // that name and fabricated a call edge from an unrelated function
  4523. // (`append`, `get`, `run`…). Keep the inner callee, encoded as
  4524. // `<inner>().<method>` like the Java/Kotlin/C++ chains: the
  4525. // marker never appears in an ordinary ref, so nothing name-matches
  4526. // it, and a chain resolver can later infer the receiver's type
  4527. // from what the inner call returns. An inner callee that is not a
  4528. // plain name or member chain (`(await x)()`, `arr[0]()`) has no
  4529. // static receiver at all — emit nothing: a silent miss, never a
  4530. // wrong edge. The inner call is visited on its own either way.
  4531. // Mirrored in the kernel (tsjs/extractors.rs, python.rs).
  4532. const innerFn = getChildByField(receiver, 'function');
  4533. const innerCallee = innerFn ? getNodeText(innerFn, this.source).replace(/\s+/g, '') : '';
  4534. if (!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(innerCallee)) return;
  4535. calleeName = `${innerCallee}().${methodName}`;
  4536. } else if (
  4537. this.language === 'go' &&
  4538. receiver &&
  4539. receiver.type === 'selector_expression' &&
  4540. /^[A-Za-z_]\w*\.[A-Za-z_]\w*$/.test(getNodeText(receiver, this.source).replace(/\s+/g, ''))
  4541. ) {
  4542. // Go 2-hop field chain `target.conn.Exec(...)`: keep the
  4543. // receiver chain so resolution can infer `conn`'s declared type
  4544. // from the Target struct. Previously this emitted the bare
  4545. // method name, and when the field's type is EXTERNAL (sql.DB)
  4546. // the bare name exact-matched an unrelated same-named local
  4547. // method — a fabricated internal dependency (#1276). Chained
  4548. // Go receivers resolve strictly via validated field-hop
  4549. // inference (see matchGoFieldChainCall) or stay unresolved.
  4550. calleeName = `${getNodeText(receiver, this.source).replace(/\s+/g, '')}.${methodName}`;
  4551. } else if (
  4552. TS_JS_CHAIN_LANGUAGES.has(this.language) &&
  4553. receiver &&
  4554. TS_JS_CHAIN_RECEIVER_TYPES.has(receiver.type) &&
  4555. isUnresolvedTsJsChain(receiver, this.source)
  4556. ) {
  4557. // `holder.values.get()` has no inferred property type (#1566).
  4558. // Emitting bare `get` exact-matches an unrelated project method;
  4559. // preserving the chain alone would still allow receiver guessing.
  4560. // Emit nothing until the property type can be established. This
  4561. // also covers host chains such as `chrome.storage.local.get()`
  4562. // (#1707). Calls inside arguments are visited independently.
  4563. // Mirrored in the kernel's extract_call (tsjs/extractors.rs).
  4564. return;
  4565. } else {
  4566. calleeName = methodName;
  4567. }
  4568. }
  4569. } else if (func.type === 'scoped_identifier' || func.type === 'scoped_call_expression') {
  4570. // Scoped call: Module::function()
  4571. calleeName = getNodeText(func, this.source);
  4572. } else if (this.language === 'csharp' && func.type === 'member_access_expression') {
  4573. // C# member call `recv.Method(...)`. When the receiver is itself a call
  4574. // — a chained factory `Foo.Create(args).Bar()` — encode `inner().Bar`
  4575. // with normalized empty parens so resolution can infer Bar's class from
  4576. // what `Foo.Create` RETURNS (#645/#608). A non-call receiver keeps the
  4577. // full member-access text (the existing `recv.Method` behavior).
  4578. const recv = getChildByField(func, 'expression');
  4579. const nameNode = getChildByField(func, 'name');
  4580. const methodName = nameNode ? getNodeText(nameNode, this.source) : '';
  4581. if (recv && recv.type === 'invocation_expression' && methodName) {
  4582. const innerFunc = getChildByField(recv, 'function');
  4583. const innerCallee = innerFunc ? getNodeText(innerFunc, this.source).replace(/\s+/g, '') : '';
  4584. calleeName = innerCallee ? `${innerCallee}().${methodName}` : methodName;
  4585. } else {
  4586. calleeName = getNodeText(func, this.source);
  4587. }
  4588. } else {
  4589. calleeName = getNodeText(func, this.source);
  4590. }
  4591. }
  4592. }
  4593. // Parenthesized type conversions — Go `(*T)(x)` / `(T)(x)` (and a
  4594. // parenthesized callee generally) parse as a call whose "function" is a
  4595. // parenthesized type/expression, so the callee text is the un-resolvable
  4596. // literal `(*T)`. Normalize to the inner name so it resolves to `T` (a real
  4597. // dependency on the converted-to type) instead of dropping on the floor.
  4598. if (calleeName) {
  4599. const conv = calleeName.match(/^\(\s*\*?\s*([A-Za-z_][\w.]*)\s*\)$/);
  4600. if (conv && conv[1]) calleeName = conv[1];
  4601. }
  4602. // C/C++ templated callees — a direct templated call (`fn<T, 256>(args)`,
  4603. // the shape every CUDA kernel-launch site takes once its `<<<…>>>` config
  4604. // is blanked) or a qualified one (`ns::fn<T>(args)`) — carry template
  4605. // arguments in the callee text, which can never match the bare name the
  4606. // function was DEFINED as, so the call edge silently never resolves. Strip
  4607. // them: the same normalization base-class `extends` refs already get
  4608. // (#1043). `operator<`/`operator<<` callees are excluded — their `<` is the
  4609. // operator itself, not a template-argument list.
  4610. if (
  4611. calleeName &&
  4612. calleeName.includes('<') &&
  4613. (this.language === 'cpp' || this.language === 'c') &&
  4614. !calleeName.includes('operator')
  4615. ) {
  4616. calleeName = stripCppTemplateArgs(calleeName);
  4617. }
  4618. // C++ call/launch through a local function pointer: `auto kernel =
  4619. // &flash_fwd_kernel<…>; … kernel<<<grid, block>>>(params);` — the callee
  4620. // is an unresolvable local name. When the same enclosing symbol bound the
  4621. // local from `&fn` (each branch assignment counts), emit the call against
  4622. // every recorded target instead of the local.
  4623. if (calleeName && this.language === 'cpp' && /^[A-Za-z_]\w*$/.test(calleeName)) {
  4624. const targets = this.cppLocalFnPtrs.get(callerId)?.get(calleeName);
  4625. if (targets && targets.size > 0) {
  4626. for (const target of targets) {
  4627. this.unresolvedReferences.push({
  4628. fromNodeId: callerId,
  4629. referenceName: target,
  4630. referenceKind: 'calls',
  4631. line: node.startPosition.row + 1,
  4632. column: node.startPosition.column,
  4633. });
  4634. }
  4635. return;
  4636. }
  4637. }
  4638. if (calleeName) {
  4639. this.unresolvedReferences.push({
  4640. fromNodeId: callerId,
  4641. referenceName: calleeName,
  4642. referenceKind: 'calls',
  4643. line: node.startPosition.row + 1,
  4644. column: node.startPosition.column,
  4645. });
  4646. }
  4647. }
  4648. /**
  4649. * `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  4650. * emit an `instantiates` reference to the class name. The resolver
  4651. * then links it to the class node, producing the `instantiates`
  4652. * edge that powers "what creates instances of X" queries.
  4653. *
  4654. * Children are still walked so nested calls inside the constructor
  4655. * arguments (`new Foo(bar())`) get their own `calls` references.
  4656. */
  4657. /**
  4658. * VB.NET `New Invoice(1)` is syntactically ambiguous between constructing
  4659. * Invoice with an argument and allocating an Invoice array of bound 1; the
  4660. * grammar parses the parenthesized form as array_creation_expression. A
  4661. * user-defined type with no `{...}` array initializer is overwhelmingly a
  4662. * constructor call, so treat it as an instantiation. Predefined element
  4663. * types (`New Byte(1023)`) and brace-initialized forms stay arrays.
  4664. */
  4665. private isVbnetConstructorShapedArrayCreation(node: SyntaxNode): boolean {
  4666. if (this.language !== 'vbnet' || node.type !== 'array_creation_expression') return false;
  4667. const typeNode = getChildByField(node, 'type');
  4668. if (!typeNode || typeNode.type === 'predefined_type' || typeNode.type === 'array_type') return false;
  4669. for (const child of node.namedChildren) {
  4670. if (child?.type === 'array_initializer') return false;
  4671. }
  4672. return true;
  4673. }
  4674. private extractInstantiation(node: SyntaxNode): void {
  4675. if (this.nodeStack.length === 0) return;
  4676. const fromId = this.nodeStack[this.nodeStack.length - 1];
  4677. if (!fromId) return;
  4678. // The class name is in the `constructor`/`type`/first-named-child
  4679. // depending on grammar.
  4680. const ctor =
  4681. getChildByField(node, 'constructor') ||
  4682. getChildByField(node, 'type') ||
  4683. getChildByField(node, 'name') ||
  4684. node.namedChild(0);
  4685. if (!ctor) return;
  4686. // Go composite literals: `Widget{...}` (same package) and `pkga.Widget{...}`
  4687. // (cross-package). Only a directly-named struct type is a meaningful
  4688. // instantiation target — skip slice/map/array literals (`[]T{}`,
  4689. // `map[K]V{}`) whose `type` field is a composite type, not a named type.
  4690. // Unlike `new ns.Foo()`, KEEP the package qualifier (`pkga.Widget`) so the
  4691. // Go cross-package resolver can disambiguate it to the right package's type.
  4692. if (node.type === 'composite_literal') {
  4693. if (ctor.type !== 'type_identifier' && ctor.type !== 'qualified_type') return;
  4694. let goType = getNodeText(ctor, this.source).trim();
  4695. const brIdx = goType.indexOf('['); // strip Go generic args: `Box[T]{}` -> `Box`
  4696. if (brIdx > 0) goType = goType.slice(0, brIdx).trim();
  4697. if (goType) {
  4698. this.unresolvedReferences.push({
  4699. fromNodeId: fromId,
  4700. referenceName: goType,
  4701. referenceKind: 'instantiates',
  4702. line: node.startPosition.row + 1,
  4703. column: node.startPosition.column,
  4704. });
  4705. }
  4706. return;
  4707. }
  4708. // Scala: `new Monoid[Int] { ... }` — the constructor is a `generic_type`
  4709. // (or qualified `stable_type_identifier`) using `[...]` type args, which the
  4710. // generic `<...>` strip below misses. Unwrap to the base type name.
  4711. if (node.type === 'instance_expression') {
  4712. const name = scalaBaseTypeName(ctor, this.source);
  4713. if (name) {
  4714. this.unresolvedReferences.push({
  4715. fromNodeId: fromId,
  4716. referenceName: name,
  4717. referenceKind: 'instantiates',
  4718. line: node.startPosition.row + 1,
  4719. column: node.startPosition.column,
  4720. });
  4721. }
  4722. return;
  4723. }
  4724. let className = getNodeText(ctor, this.source);
  4725. // Strip type-argument suffix first: `new Map<K, V>()` would
  4726. // otherwise produce className 'Map<K, V>' (the constructor
  4727. // field is a `generic_type` node) and resolution would fail
  4728. // because no class is named with the angle-bracket suffix.
  4729. const ltIdx = className.indexOf('<');
  4730. if (ltIdx > 0) className = className.slice(0, ltIdx);
  4731. // VB.NET spells generics with parentheses: `New List(Of String)` /
  4732. // `New Dictionary(Of K, V)(cap)` — strip from the `(` so the bare
  4733. // type name is what resolution matches.
  4734. if (this.language === 'vbnet') {
  4735. const parenIdx = className.indexOf('(');
  4736. if (parenIdx > 0) className = className.slice(0, parenIdx);
  4737. }
  4738. // For namespaced/qualified constructors (`new ns.Foo()`,
  4739. // `new ns::Foo()`) keep the trailing identifier — that's what
  4740. // matches a class node in the index.
  4741. const lastDot = Math.max(
  4742. className.lastIndexOf('.'),
  4743. className.lastIndexOf('::')
  4744. );
  4745. if (lastDot >= 0) className = className.slice(lastDot + 1).replace(/^[:.]/, '');
  4746. className = className.trim();
  4747. if (className) {
  4748. this.unresolvedReferences.push({
  4749. fromNodeId: fromId,
  4750. referenceName: className,
  4751. referenceKind: 'instantiates',
  4752. line: node.startPosition.row + 1,
  4753. column: node.startPosition.column,
  4754. });
  4755. }
  4756. }
  4757. /**
  4758. * Is this C++ `declaration` a stack/direct-initialization object construction
  4759. * that invokes a constructor — `Calculator calc(0)` (direct-init) or
  4760. * `Widget w{1, 2}` (brace-init) — as opposed to a plain variable or a
  4761. * function declaration? Used to emit an `instantiates` edge for the
  4762. * call-less construction syntax (#1035); heap `new T(...)` is handled
  4763. * separately by INSTANTIATION_KINDS.
  4764. *
  4765. * Two signals, both required:
  4766. * - the `type` field is a class-like NAMED type (`type_identifier`,
  4767. * `template_type`, or `qualified_identifier`). Primitives (`int x(0)`),
  4768. * `auto` (`placeholder_type_specifier` — that form always carries a real
  4769. * `call_expression`, already handled), and sized specifiers are excluded —
  4770. * they construct no class; and
  4771. * - a declarator carries constructor arguments: an `init_declarator` whose
  4772. * `value` is an `argument_list` (`(args)`) or `initializer_list` (`{args}`).
  4773. * This skips default construction `Calculator c;` (no value) and the
  4774. * most-vexing-parse `Calculator c();` (a bodyless `function_declarator`,
  4775. * a function decl — not a construction).
  4776. */
  4777. private isCppStackConstruction(node: SyntaxNode): boolean {
  4778. const typeNode = getChildByField(node, 'type');
  4779. if (
  4780. !typeNode ||
  4781. (typeNode.type !== 'type_identifier' &&
  4782. typeNode.type !== 'template_type' &&
  4783. typeNode.type !== 'qualified_identifier')
  4784. ) {
  4785. return false;
  4786. }
  4787. for (let i = 0; i < node.namedChildCount; i++) {
  4788. const child = node.namedChild(i);
  4789. if (child?.type !== 'init_declarator') continue;
  4790. const value = getChildByField(child, 'value');
  4791. if (value && (value.type === 'argument_list' || value.type === 'initializer_list')) {
  4792. return true;
  4793. }
  4794. }
  4795. return false;
  4796. }
  4797. /**
  4798. * Static-member / value-read pass. A type/enum/class used only via a member
  4799. * VALUE — `Enum.value`, `Type.CONST`, `Colors.red`, `Foo::BAR` — recorded no
  4800. * edge, because the body walker only handled CALLS (`Type.method()`). So a
  4801. * type referenced only by an enum value or a static field looked like nothing
  4802. * depended on it (the residual frontier across Dart/Java/C#/Swift/Kotlin/PHP).
  4803. * Emit a `references` edge to the capitalized receiver. Gated to languages
  4804. * where types are Capitalized by convention, and skipped when the access is a
  4805. * call's callee (the call extractor already links the method).
  4806. */
  4807. private extractStaticMemberRef(node: SyntaxNode): void {
  4808. if (!STATIC_MEMBER_LANGS.has(this.language)) return;
  4809. if (this.nodeStack.length === 0) return;
  4810. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  4811. if (!ownerId) return;
  4812. // Dart structures member access as an `identifier` + a sibling `selector`,
  4813. // not a single node. A value-read selector (no `argument_part`) whose
  4814. // previous sibling is a capitalized identifier is `Enum.value`.
  4815. if (this.language === 'dart') {
  4816. if (node.type !== 'selector') return;
  4817. if (node.namedChildren.some((c: SyntaxNode) => c.type === 'argument_part')) return;
  4818. const prev = node.previousNamedSibling;
  4819. if (prev?.type === 'identifier' && /^[A-Z][A-Za-z0-9_]*$/.test(prev.text)) {
  4820. this.pushStaticMemberRef(prev.text, ownerId, prev);
  4821. }
  4822. return;
  4823. }
  4824. if (!MEMBER_ACCESS_TYPES.has(node.type)) return;
  4825. // Skip `Type.method()` — the access is the callee of a call, already linked.
  4826. const parent = node.parent;
  4827. if (parent && this.extractor!.callTypes.includes(parent.type)) {
  4828. const callee =
  4829. getChildByField(parent, 'function') ??
  4830. getChildByField(parent, 'method') ??
  4831. parent.namedChild(0);
  4832. if (callee && callee.startIndex === node.startIndex) return;
  4833. }
  4834. // The receiver must be a SIMPLE capitalized identifier — `Type.X`, not the
  4835. // nested `a.B.c` (whose own head member-access is visited separately) nor a
  4836. // lowercase `obj.field` / `pkg.func`.
  4837. const recv =
  4838. getChildByField(node, 'object') ??
  4839. getChildByField(node, 'expression') ??
  4840. getChildByField(node, 'scope') ??
  4841. node.namedChild(0);
  4842. if (!recv) return;
  4843. const t = recv.type;
  4844. if (
  4845. t === 'identifier' || t === 'type_identifier' || t === 'simple_identifier' ||
  4846. t === 'name' || t === 'scoped_type_identifier'
  4847. ) {
  4848. const text = getNodeText(recv, this.source);
  4849. if (/^[A-Z][A-Za-z0-9_]*$/.test(text)) this.pushStaticMemberRef(text, ownerId, recv);
  4850. }
  4851. }
  4852. private pushStaticMemberRef(name: string, ownerId: string, node: SyntaxNode): void {
  4853. this.unresolvedReferences.push({
  4854. fromNodeId: ownerId,
  4855. referenceName: name,
  4856. referenceKind: 'references',
  4857. line: node.startPosition.row + 1,
  4858. column: node.startPosition.column,
  4859. });
  4860. }
  4861. /**
  4862. * Find a `class_body` child of an `object_creation_expression` — the
  4863. * marker for an anonymous class (`new T() { ... }`). Returns the body
  4864. * node so the caller can walk it as the anon class's members.
  4865. */
  4866. private findAnonymousClassBody(node: SyntaxNode): SyntaxNode | null {
  4867. for (let i = 0; i < node.namedChildCount; i++) {
  4868. const child = node.namedChild(i);
  4869. // Java: `class_body`. C# uses the same node kind.
  4870. if (child && (child.type === 'class_body' || child.type === 'declaration_list')) {
  4871. return child;
  4872. }
  4873. }
  4874. return null;
  4875. }
  4876. /**
  4877. * Extract a Java/C# anonymous class — `new T() { ...members }`. Emits a
  4878. * `class` node named `<T$anon@line>`, an `extends` reference to T (so
  4879. * Phase 5.5 interface-impl can bridge), and walks the body so its
  4880. * `method_declaration` members become method nodes under the anon class.
  4881. *
  4882. * Why this matters: without anon-class extraction, the overrides inside
  4883. * a lambda-returned `new T() { @Override int foo(){...} }` are not nodes,
  4884. * so a call through T.foo (the abstract parent method) has no static
  4885. * target — the agent has to Read the file to find the implementation.
  4886. */
  4887. private extractAnonymousClass(node: SyntaxNode, body: SyntaxNode): void {
  4888. if (!this.extractor) return;
  4889. // The instantiated type sits in the same field/position that
  4890. // extractInstantiation reads from. Use the same lookup so the anon
  4891. // class's `extends` target matches the `instantiates` edge.
  4892. const typeNode =
  4893. getChildByField(node, 'constructor') ||
  4894. getChildByField(node, 'type') ||
  4895. getChildByField(node, 'name') ||
  4896. node.namedChild(0);
  4897. let typeName = typeNode ? getNodeText(typeNode, this.source) : 'Object';
  4898. const ltIdx = typeName.indexOf('<');
  4899. if (ltIdx > 0) typeName = typeName.slice(0, ltIdx);
  4900. const lastDot = Math.max(typeName.lastIndexOf('.'), typeName.lastIndexOf('::'));
  4901. if (lastDot >= 0) typeName = typeName.slice(lastDot + 1).replace(/^[:.]/, '');
  4902. typeName = typeName.trim() || 'Object';
  4903. const anonName = `<${typeName}$anon@${node.startPosition.row + 1}>`;
  4904. const classNode = this.createNode('class', anonName, node, {});
  4905. if (!classNode) return;
  4906. // The anonymous class implicitly extends/implements the named type.
  4907. // We can't tell at extraction time whether T is a class or an interface,
  4908. // so emit `extends`. Resolution will still bind T to whatever it is, and
  4909. // Phase 5.5 (which already handles both `extends` and `implements`) will
  4910. // bridge T's methods to the override names found in the anon body.
  4911. this.unresolvedReferences.push({
  4912. fromNodeId: classNode.id,
  4913. referenceName: typeName,
  4914. referenceKind: 'extends',
  4915. line: typeNode?.startPosition.row ?? node.startPosition.row,
  4916. column: typeNode?.startPosition.column ?? node.startPosition.column,
  4917. });
  4918. // Walk the body's children so method_declaration nodes inside become
  4919. // method nodes scoped to the anon class.
  4920. this.nodeStack.push(classNode.id);
  4921. for (let i = 0; i < body.namedChildCount; i++) {
  4922. const child = body.namedChild(i);
  4923. if (child) this.visitNode(child);
  4924. }
  4925. this.nodeStack.pop();
  4926. }
  4927. /**
  4928. * Scan `declNode` and its preceding siblings (within the parent's
  4929. * named children) for decorator nodes, emitting a `decorates`
  4930. * reference from `decoratedId` to each decorator's function name.
  4931. *
  4932. * Why preceding siblings: in TypeScript, `@Foo class Bar {}` parses
  4933. * as an `export_statement` (or top-level wrapper) with the
  4934. * `decorator` as a child *before* the `class_declaration` — so the
  4935. * decorator isn't a child of the class itself. For methods/
  4936. * properties, the decorator IS a direct child of the declaration,
  4937. * so we also scan declNode.namedChildren.
  4938. *
  4939. * Idempotent across grammars: if neither location yields decorators
  4940. * (most non-decorator-using languages), the function is a no-op.
  4941. */
  4942. private extractDecoratorsFor(declNode: SyntaxNode, decoratedId: string): void {
  4943. const consider = (n: SyntaxNode | null): void => {
  4944. if (!n) return;
  4945. // Solidity `modifier_invocation` (unique to that grammar) sits
  4946. // decorator-position in the function header — OUTSIDE the `body:` field
  4947. // the call walker descends — but its body executes around the function
  4948. // via `_;`, so it is a real call-flow hop (`withdraw → onlyOwner →
  4949. // _checkRole` is the canonical audit trace). The same node type carries
  4950. // base-constructor invocations (`constructor() ERC20("T","TOK")`), the
  4951. // constructor-chain hop. Emit `calls`, not `decorates`, so flow
  4952. // traversal rides it.
  4953. if (n.type === 'modifier_invocation') {
  4954. const target = n.namedChild(0);
  4955. const name = target?.type === 'identifier' ? getNodeText(target, this.source) : undefined;
  4956. if (name) {
  4957. this.unresolvedReferences.push({
  4958. fromNodeId: decoratedId,
  4959. referenceName: name,
  4960. referenceKind: 'calls',
  4961. line: n.startPosition.row + 1,
  4962. column: n.startPosition.column,
  4963. });
  4964. }
  4965. return;
  4966. }
  4967. // `marker_annotation` is Java's grammar for arg-less annotations
  4968. // (`@Override`, `@Deprecated`); `attribute` is Swift's grammar for
  4969. // attributes and PROPERTY WRAPPERS (`@objc`, `@Argument`, `@Published`,
  4970. // `@State`). Without these, those usages would be silently skipped.
  4971. if (
  4972. n.type !== 'decorator' &&
  4973. n.type !== 'annotation' &&
  4974. n.type !== 'marker_annotation' &&
  4975. n.type !== 'attribute'
  4976. ) {
  4977. return;
  4978. }
  4979. // Find the leading identifier: skip the `@` punct, unwrap
  4980. // a call_expression if the decorator is invoked with args.
  4981. let target: SyntaxNode | null = null;
  4982. for (let i = 0; i < n.namedChildCount; i++) {
  4983. const child = n.namedChild(i);
  4984. if (!child) continue;
  4985. if (child.type === 'call_expression') {
  4986. const fn = getChildByField(child, 'function') ?? child.namedChild(0);
  4987. if (fn) target = fn;
  4988. if (target) break;
  4989. }
  4990. if (
  4991. child.type === 'identifier' ||
  4992. child.type === 'member_expression' ||
  4993. child.type === 'scoped_identifier' ||
  4994. child.type === 'navigation_expression' ||
  4995. child.type === 'user_type' || // swift attribute → user_type (`@Argument`)
  4996. child.type === 'type_identifier'
  4997. ) {
  4998. target = child;
  4999. break;
  5000. }
  5001. }
  5002. if (!target) return;
  5003. let name = getNodeText(target, this.source);
  5004. const lt = name.indexOf('<'); // strip generic args: `@Argument<T>` → `Argument`
  5005. if (lt > 0) name = name.slice(0, lt);
  5006. const lastDot = Math.max(name.lastIndexOf('.'), name.lastIndexOf('::'));
  5007. if (lastDot >= 0) name = name.slice(lastDot + 1).replace(/^[:.]/, '');
  5008. name = name.trim();
  5009. if (!name) return;
  5010. this.unresolvedReferences.push({
  5011. fromNodeId: decoratedId,
  5012. referenceName: name,
  5013. referenceKind: 'decorates',
  5014. line: n.startPosition.row + 1,
  5015. column: n.startPosition.column,
  5016. });
  5017. };
  5018. // 1. Decorators that are direct children of the declaration
  5019. // (method/property style, also some grammars for class).
  5020. for (let i = 0; i < declNode.namedChildCount; i++) {
  5021. const child = declNode.namedChild(i);
  5022. consider(child);
  5023. // Java/Kotlin/C# put annotations INSIDE a `modifiers` node
  5024. // (`@MyAnno public class X` → class_declaration → modifiers → annotation),
  5025. // so descend into it — otherwise every annotation usage is silently
  5026. // dropped and annotation types show zero dependents.
  5027. if (child && child.type === 'modifiers') {
  5028. for (let j = 0; j < child.namedChildCount; j++) {
  5029. consider(child.namedChild(j));
  5030. }
  5031. }
  5032. }
  5033. // 2. Decorators that are PRECEDING siblings of the declaration
  5034. // inside the parent's children (TypeScript class style).
  5035. // Walk BACKWARDS from the declaration and stop at the first
  5036. // non-decorator sibling — without that stop, decorators
  5037. // belonging to an EARLIER unrelated declaration leak in
  5038. // (e.g. `@A class Foo {} @B class Bar {}` would otherwise
  5039. // attribute @A to Bar).
  5040. //
  5041. // Note on identity: tree-sitter web bindings return fresh JS
  5042. // wrapper objects from `parent`/`namedChild` navigation, so
  5043. // `sibling === declNode` is unreliable — `startIndex` does
  5044. // the matching instead.
  5045. const parent = declNode.parent;
  5046. if (parent) {
  5047. const declStart = declNode.startIndex;
  5048. let declIdx = -1;
  5049. for (let i = 0; i < parent.namedChildCount; i++) {
  5050. const sibling = parent.namedChild(i);
  5051. if (sibling && sibling.startIndex === declStart) {
  5052. declIdx = i;
  5053. break;
  5054. }
  5055. }
  5056. if (declIdx > 0) {
  5057. for (let j = declIdx - 1; j >= 0; j--) {
  5058. const sibling = parent.namedChild(j);
  5059. if (!sibling) continue;
  5060. if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') {
  5061. break; // non-decorator separator → stop consuming
  5062. }
  5063. consider(sibling);
  5064. }
  5065. }
  5066. }
  5067. }
  5068. /**
  5069. * Visit function body and extract calls (and structural nodes).
  5070. *
  5071. * In addition to call expressions, this also detects class/struct/enum
  5072. * definitions inside function bodies. This handles two cases:
  5073. * 1. Local class/struct/enum definitions (valid in C++, Java, etc.)
  5074. * 2. C++ macro misparsing — macros like NLOHMANN_JSON_NAMESPACE_BEGIN cause
  5075. * tree-sitter to interpret the namespace block as a function_definition,
  5076. * hiding real class/struct/enum nodes inside the "function body".
  5077. */
  5078. /**
  5079. * Rocket route-registration macros — `routes![a::b::handler, c::d::other]`
  5080. * and `catchers![not_found]`. Tree-sitter leaves a macro body as a flat
  5081. * `token_tree` of raw tokens (`identifier`, `::`, `,`), so the handler paths
  5082. * are never seen as references and each handler fn looks like it has no caller
  5083. * — it's mounted by Rocket at runtime, not called by in-repo code, so its file
  5084. * shows 0 dependents. Walk the token tree, reconstruct each comma-separated
  5085. * path, and emit a `references` edge; the Rust path resolver
  5086. * (`resolveRustPathReference`) then links it to the handler fn. The handler
  5087. * names are explicit in source, so this is precise static extraction, not a
  5088. * heuristic — no false edges (resolution still validates each path).
  5089. */
  5090. private extractRustRouteMacro(node: SyntaxNode): void {
  5091. if (this.language !== 'rust') return;
  5092. const macroName = node.namedChild(0);
  5093. if (!macroName) return;
  5094. const name = getNodeText(macroName, this.source);
  5095. if (name !== 'routes' && name !== 'catchers') return;
  5096. const tokenTree = node.namedChildren.find((c: SyntaxNode) => c.type === 'token_tree');
  5097. if (!tokenTree) return;
  5098. const fromId = this.nodeStack[this.nodeStack.length - 1];
  5099. if (!fromId) return;
  5100. // The token tree is a flat stream: `[ id :: id :: id , id … ]`. Group runs
  5101. // of `identifier` tokens (the `::` joiners are anonymous) into one path; a
  5102. // `,` (or the closing `]`) ends a path.
  5103. let parts: string[] = [];
  5104. let line = 0;
  5105. let column = 0;
  5106. const flush = (): void => {
  5107. if (parts.length > 0) {
  5108. this.unresolvedReferences.push({
  5109. fromNodeId: fromId,
  5110. referenceName: parts.join('::'),
  5111. referenceKind: 'references',
  5112. line,
  5113. column,
  5114. });
  5115. parts = [];
  5116. }
  5117. };
  5118. for (let i = 0; i < tokenTree.childCount; i++) {
  5119. const t = tokenTree.child(i);
  5120. if (!t) continue;
  5121. if (t.type === 'identifier') {
  5122. if (parts.length === 0) {
  5123. line = t.startPosition.row + 1;
  5124. column = t.startPosition.column;
  5125. }
  5126. parts.push(getNodeText(t, this.source));
  5127. } else if (t.type === ',') {
  5128. flush();
  5129. }
  5130. }
  5131. flush();
  5132. }
  5133. /**
  5134. * Record a C++ local function-pointer binding (`local = &fn` / `&fn<…>` /
  5135. * `&ns::fn<…>`) for the CURRENT enclosing symbol, so calls through the local
  5136. * resolve to the real target (see cppLocalFnPtrs). Only the address-of shape
  5137. * is accepted — a bare-identifier RHS (`auto x = y;`) is any value copy, and
  5138. * linking through it would guess.
  5139. */
  5140. private recordCppFnPtrBinding(localName: string, value: SyntaxNode | null): void {
  5141. if (!value || value.type !== 'pointer_expression') return;
  5142. if (value.child(0)?.type !== '&') return; // `*p` dereference, not address-of
  5143. const arg = getChildByField(value, 'argument') ?? value.namedChild(0);
  5144. if (
  5145. !arg ||
  5146. (arg.type !== 'identifier' &&
  5147. arg.type !== 'template_function' &&
  5148. arg.type !== 'qualified_identifier')
  5149. ) {
  5150. return;
  5151. }
  5152. const callerId = this.nodeStack[this.nodeStack.length - 1];
  5153. if (!callerId) return;
  5154. const target = stripCppTemplateArgs(getNodeText(arg, this.source));
  5155. if (!target || target === localName) return;
  5156. let locals = this.cppLocalFnPtrs.get(callerId);
  5157. if (!locals) {
  5158. locals = new Map();
  5159. this.cppLocalFnPtrs.set(callerId, locals);
  5160. }
  5161. let targets = locals.get(localName);
  5162. if (!targets) {
  5163. targets = new Set();
  5164. locals.set(localName, targets);
  5165. }
  5166. targets.add(target);
  5167. }
  5168. /**
  5169. * Whether an anonymous function is the whole value of a `variable_declarator`
  5170. * with a plain identifier name — `const NAME = () => {…}` / `= function () {…}`.
  5171. * JS-family only.
  5172. */
  5173. private declaratorBoundFunction(node: SyntaxNode): boolean {
  5174. if (
  5175. this.language !== 'typescript' &&
  5176. this.language !== 'javascript' &&
  5177. this.language !== 'tsx' &&
  5178. this.language !== 'jsx'
  5179. ) {
  5180. return false;
  5181. }
  5182. if (node.type !== 'arrow_function' && node.type !== 'function_expression') return false;
  5183. const declarator = node.parent;
  5184. if (!declarator || declarator.type !== 'variable_declarator') return false;
  5185. const value = getChildByField(declarator, 'value');
  5186. if (!value || value.startIndex !== node.startIndex || value.endIndex !== node.endIndex) return false;
  5187. return getChildByField(declarator, 'name')?.type === 'identifier';
  5188. }
  5189. /**
  5190. * The property a CommonJS export assignment binds a function to —
  5191. * `exports.NAME = <node>` or `module.exports.NAME = <node>` — or null for
  5192. * any other assignment. JS-family only; the node must be the assignment's
  5193. * whole right-hand side.
  5194. */
  5195. private commonJsExportName(assignment: SyntaxNode, value: SyntaxNode): string | null {
  5196. if (
  5197. this.language !== 'typescript' &&
  5198. this.language !== 'javascript' &&
  5199. this.language !== 'tsx' &&
  5200. this.language !== 'jsx'
  5201. ) {
  5202. return null;
  5203. }
  5204. const right = getChildByField(assignment, 'right');
  5205. if (!right || right.startIndex !== value.startIndex || right.endIndex !== value.endIndex) return null;
  5206. const left = getChildByField(assignment, 'left');
  5207. if (!left || left.type !== 'member_expression') return null;
  5208. const object = getChildByField(left, 'object');
  5209. const property = getChildByField(left, 'property');
  5210. if (!object || !property || property.type !== 'property_identifier') return null;
  5211. const objectText = getNodeText(object, this.source);
  5212. if (objectText !== 'exports' && objectText !== 'module.exports') return null;
  5213. return getNodeText(property, this.source);
  5214. }
  5215. /**
  5216. * The declarator name a React handler hook binds an anonymous function to —
  5217. * `const NAME = useCallback(<node>, [...])` — or null for any other shape.
  5218. * JS-family only; the node must be the hook call's FIRST argument, and the
  5219. * call's value must be bound directly by a `variable_declarator`.
  5220. */
  5221. private reactHookBoundName(node: SyntaxNode): string | null {
  5222. if (
  5223. this.language !== 'typescript' &&
  5224. this.language !== 'javascript' &&
  5225. this.language !== 'tsx' &&
  5226. this.language !== 'jsx'
  5227. ) {
  5228. return null;
  5229. }
  5230. if (node.type !== 'arrow_function' && node.type !== 'function_expression') return null;
  5231. const args = node.parent;
  5232. if (!args || args.type !== 'arguments') return null;
  5233. const first = args.namedChild(0);
  5234. if (!first || first.startIndex !== node.startIndex || first.endIndex !== node.endIndex) return null;
  5235. const call = args.parent;
  5236. if (!call || call.type !== 'call_expression') return null;
  5237. const callee = getChildByField(call, 'function');
  5238. if (!callee || !REACT_HANDLER_HOOKS.test(getNodeText(callee, this.source))) return null;
  5239. const declarator = call.parent;
  5240. if (!declarator || declarator.type !== 'variable_declarator') return null;
  5241. const nameNode = getChildByField(declarator, 'name');
  5242. return nameNode?.type === 'identifier' ? getNodeText(nameNode, this.source) : null;
  5243. }
  5244. private visitFunctionBody(body: SyntaxNode, _functionId: string): void {
  5245. if (!this.extractor) return;
  5246. const visitForCallsAndStructure = (node: SyntaxNode): void => {
  5247. const nodeType = node.type;
  5248. // Function-as-value capture (#756) — function bodies are walked here,
  5249. // not in visitNode, so the capture hook must fire in both walkers.
  5250. this.maybeCaptureFnRefs(node, nodeType);
  5251. // Rocket route-registration macros (`routes![…]` / `catchers![…]`): the
  5252. // handler paths live in a raw token tree the call walker can't see.
  5253. if (nodeType === 'macro_invocation') this.extractRustRouteMacro(node);
  5254. if (this.extractor!.callTypes.includes(nodeType)) {
  5255. this.extractCall(node);
  5256. } else if (INSTANTIATION_KINDS.has(nodeType) || this.isVbnetConstructorShapedArrayCreation(node)) {
  5257. // `new Foo()` inside a function body — emit an `instantiates`
  5258. // reference. Without this branch the body walker only knew
  5259. // about `call_expression`, so constructor invocations
  5260. // produced no graph edges at all.
  5261. this.extractInstantiation(node);
  5262. // Anonymous class with body: `new T() { ... }` (Java/C#). Extract as
  5263. // a class so interface-impl synthesis (Phase 5.5) can bridge T's
  5264. // methods to the overrides — same rationale as in visitNode.
  5265. const anonBody = this.findAnonymousClassBody(node);
  5266. if (anonBody) {
  5267. this.extractAnonymousClass(node, anonBody);
  5268. return;
  5269. }
  5270. } else if (this.extractor!.extractBareCall) {
  5271. const calleeName = this.extractor!.extractBareCall(node, this.source);
  5272. if (calleeName && this.nodeStack.length > 0) {
  5273. const callerId = this.nodeStack[this.nodeStack.length - 1];
  5274. if (callerId) {
  5275. this.unresolvedReferences.push({
  5276. fromNodeId: callerId,
  5277. referenceName: calleeName,
  5278. referenceKind: 'calls',
  5279. line: node.startPosition.row + 1,
  5280. column: node.startPosition.column,
  5281. });
  5282. }
  5283. }
  5284. }
  5285. // C++ stack / direct-initialization construction — `Calculator calc(0)`
  5286. // and `Widget w{1, 2}`. Unlike heap `new Calculator(0)` (a new_expression
  5287. // handled above), these carry the constructor arguments directly on the
  5288. // declarator with NO call/new node, so the body walker saw no constructor
  5289. // invocation and recorded no `instantiates` edge (#1035). A declaration's
  5290. // `type` field IS the constructed class name, so reuse extractInstantiation
  5291. // (which strips template args / namespace and emits the `instantiates`
  5292. // ref). Children still recurse below, so a nested ctor-arg call
  5293. // (`Calculator calc(make())`) keeps its own `calls` ref.
  5294. if (nodeType === 'declaration' && this.language === 'cpp' && this.isCppStackConstruction(node)) {
  5295. this.extractInstantiation(node);
  5296. }
  5297. // C++ local function-pointer bindings (see cppLocalFnPtrs): record
  5298. // `auto kernel = &fn<…>;` declarations and `kernel = &other_fn<…>;`
  5299. // branch reassignments so a call/launch through the local links to the
  5300. // real target(s). The body walker sees these in source order, and C++
  5301. // requires declaration-before-use, so the map is always populated before
  5302. // the call that consumes it.
  5303. if (this.language === 'cpp' && this.nodeStack.length > 0) {
  5304. if (nodeType === 'declaration') {
  5305. for (let i = 0; i < node.namedChildCount; i++) {
  5306. const child = node.namedChild(i);
  5307. if (child?.type !== 'init_declarator') continue;
  5308. const decl = getChildByField(child, 'declarator');
  5309. if (decl?.type !== 'identifier') continue;
  5310. this.recordCppFnPtrBinding(
  5311. getNodeText(decl, this.source),
  5312. getChildByField(child, 'value')
  5313. );
  5314. }
  5315. } else if (nodeType === 'assignment_expression') {
  5316. const left = getChildByField(node, 'left');
  5317. if (left?.type === 'identifier') {
  5318. this.recordCppFnPtrBinding(
  5319. getNodeText(left, this.source),
  5320. getChildByField(node, 'right')
  5321. );
  5322. }
  5323. }
  5324. }
  5325. // Static-member / value-read: `Enum.value`, `Type.CONST`, `Foo::BAR`.
  5326. this.extractStaticMemberRef(node);
  5327. // Local variable type annotations inside a body — `const items: Foo[] = []`,
  5328. // `const x: SomeType = svc.load()`. We deliberately do NOT create nodes for
  5329. // locals (that would explode the graph — the data-flow frontier we leave
  5330. // uncovered), but the TYPE a local is annotated with is a real dependency of
  5331. // the enclosing function, so attribute a `references` edge to it. Without
  5332. // this, a function that uses a type ONLY in its body (very common — e.g. a
  5333. // resolver building `const nodes: Node[] = []`) produced no edge to that
  5334. // type, so impact / `affected` missed the dependency entirely. We fall
  5335. // through to the default recursion below so the initializer's calls (and any
  5336. // nested declarators) are still walked.
  5337. if (
  5338. nodeType === 'variable_declarator' &&
  5339. this.TYPE_ANNOTATION_LANGUAGES.has(this.language)
  5340. ) {
  5341. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  5342. if (ownerId) this.extractVariableTypeAnnotation(node, ownerId);
  5343. }
  5344. // Nested NAMED functions inside a body — function declarations and named
  5345. // function expressions like `.on('mount', function onmount(){})` — become
  5346. // their own nodes so the graph can link to them (callback handlers, local
  5347. // helpers). Anonymous arrows/expressions fall through to the default
  5348. // recursion below, keeping their inner calls attributed to the enclosing
  5349. // function: this bounds the new nodes to NAMED functions only (no explosion,
  5350. // no lost edges). extractFunction walks the nested body itself, so we return.
  5351. if (this.extractor!.functionTypes.includes(nodeType)) {
  5352. const nestedName = extractName(node, this.source, this.extractor!);
  5353. if (nestedName && nestedName !== '<anonymous>') {
  5354. this.extractFunction(node);
  5355. return;
  5356. }
  5357. // `const handleSubmit = useCallback(() => {…}, [deps])` — React's
  5358. // memoised handler. The function is anonymous only syntactically: the
  5359. // arrow is the first argument of a call whose result the declarator
  5360. // binds, and that binding is the name every `onPress={handleSubmit}`
  5361. // and `addListener('x', handleSubmit)` uses. Without a node of its own
  5362. // the handler's calls attribute to the component and the JSX prop or
  5363. // event registration has nothing to resolve to — the trigger of a flow
  5364. // is invisible. Bounded to the hooks React documents for handlers
  5365. // (`useCallback`, `useEffectEvent`, the experimental `useEvent`):
  5366. // `useMemo` / `useEffect` callbacks are computations, not handlers.
  5367. const hookBound = this.reactHookBoundName(node);
  5368. if (hookBound) {
  5369. this.extractFunction(node, hookBound);
  5370. return;
  5371. }
  5372. // `const handleClear = () => {…}` inside a body (#1669) — the same
  5373. // binding that names a function at module scope names one here, and in
  5374. // a React component it is how every handler that skips `useCallback`
  5375. // is written. Without a node the handler is absent from callers /
  5376. // impact ("Symbol not found" reads like "no callers") and its calls
  5377. // attribute to the component. extractFunction resolves the name from
  5378. // the declarator; a destructuring or otherwise unnamed binding stays
  5379. // anonymous and falls through.
  5380. if (this.declaratorBoundFunction(node)) {
  5381. this.extractFunction(node);
  5382. return;
  5383. }
  5384. }
  5385. // Extract structural nodes found inside function bodies.
  5386. // Each extract method visits its own children, so we return after extracting.
  5387. if (this.extractor!.classTypes.includes(nodeType)) {
  5388. const classification = this.extractor!.classifyClassNode?.(node) ?? 'class';
  5389. if (classification === 'struct') this.extractStruct(node);
  5390. else if (classification === 'enum') this.extractEnum(node);
  5391. else if (classification === 'interface') this.extractInterface(node);
  5392. else if (classification === 'trait') this.extractClass(node, 'trait');
  5393. else this.extractClass(node);
  5394. return;
  5395. }
  5396. if (this.extractor!.structTypes.includes(nodeType)) {
  5397. this.extractStruct(node);
  5398. return;
  5399. }
  5400. if (this.extractor!.unionTypes?.includes(nodeType)) {
  5401. this.extractUnion(node);
  5402. return;
  5403. }
  5404. if (this.extractor!.enumTypes.includes(nodeType)) {
  5405. this.extractEnum(node);
  5406. return;
  5407. }
  5408. if (this.extractor!.interfaceTypes.includes(nodeType)) {
  5409. this.extractInterface(node);
  5410. return;
  5411. }
  5412. for (let i = 0; i < node.namedChildCount; i++) {
  5413. const child = node.namedChild(i);
  5414. if (child) {
  5415. visitForCallsAndStructure(child);
  5416. }
  5417. }
  5418. };
  5419. visitForCallsAndStructure(body);
  5420. }
  5421. /**
  5422. * Extract inheritance relationships
  5423. */
  5424. private extractInheritance(node: SyntaxNode, classId: string): void {
  5425. // Objective-C @interface MyClass : NSObject <ProtoA, ProtoB>
  5426. if (node.type === 'class_interface') {
  5427. const superclass = getChildByField(node, 'superclass');
  5428. if (superclass) {
  5429. const name = getNodeText(superclass, this.source);
  5430. this.unresolvedReferences.push({
  5431. fromNodeId: classId,
  5432. referenceName: name,
  5433. referenceKind: 'extends',
  5434. line: superclass.startPosition.row + 1,
  5435. column: superclass.startPosition.column,
  5436. });
  5437. }
  5438. for (let j = 0; j < node.namedChildCount; j++) {
  5439. const argList = node.namedChild(j);
  5440. if (argList?.type !== 'parameterized_arguments') continue;
  5441. for (let k = 0; k < argList.namedChildCount; k++) {
  5442. const typeName = argList.namedChild(k);
  5443. if (!typeName) continue;
  5444. const typeId = typeName.namedChildren.find(
  5445. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'identifier'
  5446. );
  5447. if (!typeId) continue;
  5448. const protocolName = getNodeText(typeId, this.source);
  5449. this.unresolvedReferences.push({
  5450. fromNodeId: classId,
  5451. referenceName: protocolName,
  5452. referenceKind: 'implements',
  5453. line: typeId.startPosition.row + 1,
  5454. column: typeId.startPosition.column,
  5455. });
  5456. }
  5457. }
  5458. return;
  5459. }
  5460. // Look for extends/implements clauses
  5461. for (let i = 0; i < node.namedChildCount; i++) {
  5462. const child = node.namedChild(i);
  5463. if (!child) continue;
  5464. if (
  5465. child.type === 'extends_clause' ||
  5466. child.type === 'superclass' ||
  5467. child.type === 'base_clause' || // PHP class extends
  5468. child.type === 'extends_interfaces' // Java interface extends
  5469. ) {
  5470. // Scala: `extends A[X] with B with C` packs EVERY supertype into the
  5471. // one extends_clause (separated by `with`), each a `generic_type` /
  5472. // `type_identifier` / `stable_type_identifier`. The generic path below
  5473. // takes only namedChild(0) and keeps the full text (`A[X]`), so a
  5474. // parameterized supertype — every typeclass in cats/algebra — never
  5475. // matched and `with`-mixed traits past the first were dropped. Iterate
  5476. // all supertypes and unwrap each to its base type name.
  5477. if (this.language === 'scala') {
  5478. for (const target of child.namedChildren) {
  5479. const name = scalaBaseTypeName(target, this.source);
  5480. if (name) {
  5481. this.unresolvedReferences.push({
  5482. fromNodeId: classId,
  5483. referenceName: name,
  5484. referenceKind: 'extends',
  5485. line: target.startPosition.row + 1,
  5486. column: target.startPosition.column,
  5487. });
  5488. }
  5489. }
  5490. continue;
  5491. }
  5492. // Dart: `class C extends Base with M1, M2` — the `superclass` node holds
  5493. // the extends type as a direct `type_identifier` AND a `mixins` child
  5494. // listing the `with` mixins (and `class C with M` has ONLY mixins, no
  5495. // extends type). The generic `namedChild(0)` path would read the
  5496. // `mixins` node itself as the superclass and drop every mixin — yet
  5497. // mixins are Dart's core composition mechanism (Flutter is built on
  5498. // them). Emit `extends` for the base and `implements` for each mixin.
  5499. if (this.language === 'dart' && child.type === 'superclass') {
  5500. for (const t of child.namedChildren) {
  5501. if (t.type === 'mixins') {
  5502. for (const m of t.namedChildren) {
  5503. if (m.type === 'type_identifier') {
  5504. this.unresolvedReferences.push({
  5505. fromNodeId: classId,
  5506. referenceName: getNodeText(m, this.source),
  5507. referenceKind: 'implements',
  5508. line: m.startPosition.row + 1,
  5509. column: m.startPosition.column,
  5510. });
  5511. }
  5512. }
  5513. } else if (t.type === 'type_identifier') {
  5514. this.unresolvedReferences.push({
  5515. fromNodeId: classId,
  5516. referenceName: getNodeText(t, this.source),
  5517. referenceKind: 'extends',
  5518. line: t.startPosition.row + 1,
  5519. column: t.startPosition.column,
  5520. });
  5521. }
  5522. }
  5523. continue;
  5524. }
  5525. // Extract parent class/interface names
  5526. // Java uses type_list wrapper: superclass -> type_identifier, extends_interfaces -> type_list -> type_identifier
  5527. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  5528. const targets = typeList ? typeList.namedChildren : [child.namedChild(0)];
  5529. for (const target of targets) {
  5530. if (target) {
  5531. const name = getNodeText(target, this.source);
  5532. this.unresolvedReferences.push({
  5533. fromNodeId: classId,
  5534. referenceName: name,
  5535. referenceKind: 'extends',
  5536. line: target.startPosition.row + 1,
  5537. column: target.startPosition.column,
  5538. });
  5539. }
  5540. }
  5541. }
  5542. // C++ base classes: `class Derived : public Base, private Other` →
  5543. // base_class_clause holds access specifiers + base type(s). Emit an extends
  5544. // ref per base type (skip the public/private/protected keywords). A
  5545. // templated base (`Base<int>`, `ns::Tpl<int>`) arrives as a `template_type`
  5546. // or a `qualified_identifier` wrapping one; strip the `<…>` args so the ref
  5547. // matches the bare class the template was defined as — `Base`, `ns::Tpl` —
  5548. // instead of never resolving (#1043).
  5549. if (child.type === 'base_class_clause') {
  5550. for (const t of child.namedChildren) {
  5551. if (
  5552. t.type === 'type_identifier' ||
  5553. t.type === 'qualified_identifier' ||
  5554. t.type === 'template_type'
  5555. ) {
  5556. this.unresolvedReferences.push({
  5557. fromNodeId: classId,
  5558. referenceName: stripCppTemplateArgs(getNodeText(t, this.source)),
  5559. referenceKind: 'extends',
  5560. line: t.startPosition.row + 1,
  5561. column: t.startPosition.column,
  5562. });
  5563. }
  5564. }
  5565. }
  5566. if (
  5567. child.type === 'implements_clause' ||
  5568. child.type === 'class_interface_clause' ||
  5569. child.type === 'super_interfaces' || // Java class implements
  5570. child.type === 'interfaces' // Dart
  5571. ) {
  5572. // Extract implemented interfaces
  5573. // Java uses type_list wrapper: super_interfaces -> type_list -> type_identifier
  5574. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  5575. const targets = typeList ? typeList.namedChildren : child.namedChildren;
  5576. for (const iface of targets) {
  5577. if (iface) {
  5578. const name = getNodeText(iface, this.source);
  5579. this.unresolvedReferences.push({
  5580. fromNodeId: classId,
  5581. referenceName: name,
  5582. referenceKind: 'implements',
  5583. line: iface.startPosition.row + 1,
  5584. column: iface.startPosition.column,
  5585. });
  5586. }
  5587. }
  5588. }
  5589. // Python superclass list: `class Flask(Scaffold, Mixin):`
  5590. // argument_list contains identifier children for each parent class
  5591. if (child.type === 'argument_list' && node.type === 'class_definition') {
  5592. for (const arg of child.namedChildren) {
  5593. if (arg.type === 'identifier' || arg.type === 'attribute') {
  5594. const name = getNodeText(arg, this.source);
  5595. this.unresolvedReferences.push({
  5596. fromNodeId: classId,
  5597. referenceName: name,
  5598. referenceKind: 'extends',
  5599. line: arg.startPosition.row + 1,
  5600. column: arg.startPosition.column,
  5601. });
  5602. }
  5603. }
  5604. }
  5605. // Go interface embedding: `type Querier interface { LabelQuerier; ... }`
  5606. // constraint_elem wraps the embedded interface type identifier
  5607. if (child.type === 'constraint_elem') {
  5608. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5609. if (typeId) {
  5610. const name = getNodeText(typeId, this.source);
  5611. this.unresolvedReferences.push({
  5612. fromNodeId: classId,
  5613. referenceName: name,
  5614. referenceKind: 'extends',
  5615. line: typeId.startPosition.row + 1,
  5616. column: typeId.startPosition.column,
  5617. });
  5618. }
  5619. }
  5620. // Go struct embedding: field_declaration without field_identifier
  5621. // e.g. `type DB struct { *Head; Queryable }` — no field name means embedded type
  5622. if (child.type === 'field_declaration') {
  5623. const hasFieldIdentifier = child.namedChildren.some((c: SyntaxNode) => c.type === 'field_identifier');
  5624. if (!hasFieldIdentifier) {
  5625. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5626. if (typeId) {
  5627. const name = getNodeText(typeId, this.source);
  5628. this.unresolvedReferences.push({
  5629. fromNodeId: classId,
  5630. referenceName: name,
  5631. referenceKind: 'extends',
  5632. line: typeId.startPosition.row + 1,
  5633. column: typeId.startPosition.column,
  5634. });
  5635. }
  5636. }
  5637. }
  5638. // Rust trait supertraits: `trait SubTrait: SuperTrait + Display { ... }`
  5639. // trait_bounds contains type_identifier, generic_type, or higher_ranked_trait_bound children
  5640. if (child.type === 'trait_bounds') {
  5641. for (const bound of child.namedChildren) {
  5642. let typeName: string | undefined;
  5643. let posNode: SyntaxNode | undefined;
  5644. if (bound.type === 'type_identifier') {
  5645. typeName = getNodeText(bound, this.source);
  5646. posNode = bound;
  5647. } else if (bound.type === 'generic_type') {
  5648. // e.g. `Deserialize<'de>`
  5649. const inner = bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5650. if (inner) { typeName = getNodeText(inner, this.source); posNode = inner; }
  5651. } else if (bound.type === 'higher_ranked_trait_bound') {
  5652. // e.g. `for<'de> Deserialize<'de>`
  5653. const generic = bound.namedChildren.find((c: SyntaxNode) => c.type === 'generic_type');
  5654. const typeId = generic?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  5655. ?? bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5656. if (typeId) { typeName = getNodeText(typeId, this.source); posNode = typeId; }
  5657. }
  5658. if (typeName && posNode) {
  5659. this.unresolvedReferences.push({
  5660. fromNodeId: classId,
  5661. referenceName: typeName,
  5662. referenceKind: 'extends',
  5663. line: posNode.startPosition.row + 1,
  5664. column: posNode.startPosition.column,
  5665. });
  5666. }
  5667. }
  5668. }
  5669. // VB.NET: `Inherits Base` / `Implements IFoo, IBar(Of T)` are STATEMENTS
  5670. // inside the class body (children of the class node), not header clauses.
  5671. // Each name is a simple/qualified/generic reference; generics unwrap to
  5672. // the base identifier and dotted paths keep the trailing segment.
  5673. if (
  5674. this.language === 'vbnet' &&
  5675. (child.type === 'inherits_statement' || child.type === 'implements_statement')
  5676. ) {
  5677. const kind = child.type === 'inherits_statement' ? 'extends' : 'implements';
  5678. for (const ref of child.namedChildren) {
  5679. if (!ref || (ref.type !== 'simple_name' && ref.type !== 'qualified_name' && ref.type !== 'generic_name' && ref.type !== 'global_qualified_name')) continue;
  5680. let name = getNodeText(ref, this.source);
  5681. name = name.replace(/\(\s*Of\b[^)]*\)/gi, '');
  5682. const lastDot = name.lastIndexOf('.');
  5683. if (lastDot >= 0) name = name.slice(lastDot + 1);
  5684. name = name.trim();
  5685. if (!name) continue;
  5686. this.unresolvedReferences.push({
  5687. fromNodeId: classId,
  5688. referenceName: name,
  5689. referenceKind: kind,
  5690. line: ref.startPosition.row + 1,
  5691. column: ref.startPosition.column,
  5692. });
  5693. }
  5694. }
  5695. // C#: `class Movie : BaseItem, IPlugin` → base_list with identifier children
  5696. // base_list combines both base class and interfaces in a single colon-separated list.
  5697. // We emit all as 'extends' since the syntax doesn't distinguish them.
  5698. if (child.type === 'base_list') {
  5699. for (const baseType of child.namedChildren) {
  5700. if (baseType) {
  5701. // For generic base types like `ClientBase<T>`, extract just the type name
  5702. const name = baseType.type === 'generic_name'
  5703. ? getNodeText(baseType.namedChildren.find((c: SyntaxNode) => c.type === 'identifier') ?? baseType, this.source)
  5704. : getNodeText(baseType, this.source);
  5705. this.unresolvedReferences.push({
  5706. fromNodeId: classId,
  5707. referenceName: name,
  5708. referenceKind: 'extends',
  5709. line: baseType.startPosition.row + 1,
  5710. column: baseType.startPosition.column,
  5711. });
  5712. }
  5713. }
  5714. }
  5715. // Kotlin: `class Foo : Bar, Baz` → delegation_specifier > user_type > type_identifier
  5716. // Also handles `class Foo : Bar()` → delegation_specifier > constructor_invocation > user_type
  5717. if (child.type === 'delegation_specifier') {
  5718. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  5719. const constructorInvocation = child.namedChildren.find((c: SyntaxNode) => c.type === 'constructor_invocation');
  5720. const target = userType ?? constructorInvocation;
  5721. if (target) {
  5722. const typeId = target.type === 'user_type'
  5723. ? target.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier') ?? target
  5724. : target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type')?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  5725. ?? target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type') ?? target;
  5726. const name = getNodeText(typeId, this.source);
  5727. this.unresolvedReferences.push({
  5728. fromNodeId: classId,
  5729. referenceName: name,
  5730. referenceKind: 'extends',
  5731. line: typeId.startPosition.row + 1,
  5732. column: typeId.startPosition.column,
  5733. });
  5734. }
  5735. }
  5736. // Swift: inheritance_specifier > user_type > type_identifier
  5737. // Used for class inheritance, protocol conformance, and protocol inheritance
  5738. if (child.type === 'inheritance_specifier') {
  5739. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  5740. const typeId = userType?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5741. if (typeId) {
  5742. const name = getNodeText(typeId, this.source);
  5743. this.unresolvedReferences.push({
  5744. fromNodeId: classId,
  5745. referenceName: name,
  5746. referenceKind: 'extends',
  5747. line: typeId.startPosition.row + 1,
  5748. column: typeId.startPosition.column,
  5749. });
  5750. }
  5751. }
  5752. // JavaScript class_heritage has bare identifier without extends_clause wrapper
  5753. // e.g. `class Foo extends Bar {}` → class_heritage → identifier("Bar")
  5754. if (
  5755. (child.type === 'identifier' || child.type === 'type_identifier') &&
  5756. node.type === 'class_heritage'
  5757. ) {
  5758. const name = getNodeText(child, this.source);
  5759. this.unresolvedReferences.push({
  5760. fromNodeId: classId,
  5761. referenceName: name,
  5762. referenceKind: 'extends',
  5763. line: child.startPosition.row + 1,
  5764. column: child.startPosition.column,
  5765. });
  5766. }
  5767. // Recurse into container nodes (e.g. field_declaration_list in Go structs,
  5768. // class_heritage in TypeScript which wraps extends_clause/implements_clause)
  5769. if (child.type === 'field_declaration_list' || child.type === 'class_heritage') {
  5770. this.extractInheritance(child, classId);
  5771. }
  5772. // CFML cfscript `component extends="Base" implements="IFoo,IBar" { ... }`
  5773. // (also covers `interface extends="IBase" { ... }`, which reuses the same
  5774. // component_attribute shape). Attributes are generic name=value pairs —
  5775. // (identifier label, expression value) — not a dedicated extends_clause,
  5776. // so filter by the label text. `implements` is a comma-separated list.
  5777. if (child.type === 'component_attribute' && node.type === 'component') {
  5778. const label = child.namedChildren.find((c: SyntaxNode) => c.type === 'identifier');
  5779. const value = child.namedChildren.find((c: SyntaxNode) => c.type !== 'identifier');
  5780. if (label && value) {
  5781. const labelText = getNodeText(label, this.source).toLowerCase();
  5782. if (labelText === 'extends' || labelText === 'implements') {
  5783. const valueText = getNodeText(value, this.source).replace(/^["']|["']$/g, '');
  5784. const names = labelText === 'implements'
  5785. ? valueText.split(',').map((s) => s.trim()).filter(Boolean)
  5786. : [valueText.trim()].filter(Boolean);
  5787. for (const name of names) {
  5788. this.unresolvedReferences.push({
  5789. fromNodeId: classId,
  5790. referenceName: name,
  5791. referenceKind: labelText === 'implements' ? 'implements' : 'extends',
  5792. line: value.startPosition.row + 1,
  5793. column: value.startPosition.column,
  5794. });
  5795. }
  5796. }
  5797. }
  5798. }
  5799. }
  5800. }
  5801. /**
  5802. * Rust `impl Trait for Type` — creates an implements edge from Type to Trait.
  5803. * For plain `impl Type { ... }` (no trait), no inheritance edge is needed.
  5804. */
  5805. private extractRustImplItem(node: SyntaxNode): void {
  5806. // `impl Trait for Type` carries the trait in the grammar's `trait` field;
  5807. // an inherent `impl Type { … }` has none and needs no inheritance edge.
  5808. const traitNode = getChildByField(node, 'trait');
  5809. if (!traitNode) return;
  5810. // Full text, so a scoped path (`std::fmt::Display`) and a generic trait
  5811. // (`From<u32>`) keep their spelling.
  5812. const traitName = getNodeText(traitNode, this.source);
  5813. // The implementing type from the `type` field (#1588). The old positional
  5814. // scan took the LAST type-shaped child, which for a parameterized
  5815. // implementing type (`BufSource<T>`, `Parents<'a>`, `&Foo`) was the trait.
  5816. const typeName = rustImplTypeName(getChildByField(node, 'type'), this.source);
  5817. if (!typeName) return;
  5818. // Find the struct/type node for the implementing type
  5819. const typeNodeId = this.findNodeByName(typeName);
  5820. if (typeNodeId) {
  5821. this.unresolvedReferences.push({
  5822. fromNodeId: typeNodeId,
  5823. referenceName: traitName,
  5824. referenceKind: 'implements',
  5825. line: traitNode.startPosition.row + 1,
  5826. column: traitNode.startPosition.column,
  5827. });
  5828. }
  5829. }
  5830. /**
  5831. * Find a previously-extracted node by name (used for back-references like impl blocks)
  5832. */
  5833. private findNodeByName(name: string): string | undefined {
  5834. for (const node of this.nodes) {
  5835. if (node.name === name && (node.kind === 'struct' || node.kind === 'union' || node.kind === 'enum' || node.kind === 'class')) {
  5836. return node.id;
  5837. }
  5838. }
  5839. return undefined;
  5840. }
  5841. /**
  5842. * Languages that support type annotations (TypeScript, etc.)
  5843. */
  5844. private readonly TYPE_ANNOTATION_LANGUAGES = new Set([
  5845. 'typescript', 'tsx', 'arkts', 'dart', 'kotlin', 'swift', 'rust', 'go', 'java', 'csharp', 'scala', 'php',
  5846. ]);
  5847. /**
  5848. * PHP pseudo-types and `self`/`static`/`parent` that aren't project symbols.
  5849. * (Scalar primitives parse as `primitive_type` and are skipped structurally.)
  5850. */
  5851. private readonly PHP_PSEUDO_TYPES = new Set([
  5852. 'self', 'static', 'parent', 'mixed', 'object', 'iterable', 'callable', 'void',
  5853. 'null', 'false', 'true', 'never', 'array', 'int', 'float', 'string', 'bool',
  5854. ]);
  5855. /**
  5856. * Built-in/primitive type names that shouldn't create references
  5857. */
  5858. private readonly BUILTIN_TYPES = new Set([
  5859. 'string', 'number', 'boolean', 'void', 'null', 'undefined', 'never', 'any', 'unknown',
  5860. 'object', 'symbol', 'bigint', 'true', 'false',
  5861. // Rust
  5862. 'str', 'bool', 'i8', 'i16', 'i32', 'i64', 'i128', 'isize',
  5863. 'u8', 'u16', 'u32', 'u64', 'u128', 'usize', 'f32', 'f64', 'char',
  5864. // Java/C#
  5865. 'int', 'long', 'short', 'byte', 'float', 'double', 'char',
  5866. // Go
  5867. 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64',
  5868. 'float32', 'float64', 'complex64', 'complex128', 'rune', 'error',
  5869. // Scala (capitalized primitives + ubiquitous stdlib aliases)
  5870. 'Int', 'Long', 'Short', 'Byte', 'Float', 'Double', 'Boolean', 'Char', 'Unit',
  5871. 'String', 'Any', 'AnyRef', 'AnyVal', 'Nothing', 'Null',
  5872. ]);
  5873. /**
  5874. * Extract type references from type annotations on a function/method/field node.
  5875. * Creates 'references' edges for parameter types, return types, and field types.
  5876. */
  5877. private extractTypeAnnotations(node: SyntaxNode, nodeId: string): void {
  5878. if (!this.extractor) return;
  5879. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  5880. // C# tree-sitter doesn't produce `type_identifier` leaves — it uses
  5881. // `identifier`, `predefined_type`, `qualified_name`, `generic_name`,
  5882. // etc. — so the generic walker below emits zero references for it.
  5883. // Dispatch to a C#-aware path that only walks type-position subtrees
  5884. // (the `type` field of a parameter/method/property/field), so
  5885. // parameter NAMES never accidentally surface as type refs (#381).
  5886. if (this.language === 'csharp') {
  5887. this.extractCsharpTypeRefs(node, nodeId);
  5888. return;
  5889. }
  5890. // PHP type-hints are `named_type`/`optional_type`/`union_type` wrapping a
  5891. // `name`/`qualified_name` — never `type_identifier` — so the generic walker
  5892. // below emits nothing for them. Dispatch to a PHP-aware path that walks only
  5893. // type positions (parameter / return / property types), so type-hinted
  5894. // dependencies (the constructor-injected contracts that dominate Laravel) are
  5895. // recorded and a `variable_name` like `$events` never mis-emits as a ref.
  5896. if (this.language === 'php') {
  5897. this.extractPhpTypeRefs(node, nodeId);
  5898. return;
  5899. }
  5900. // Dart: a `method_signature` wraps the real `function_signature` (where the
  5901. // params and return type live), and the return type is a bare
  5902. // `type_identifier` child, not a `type` field — so getChildByField below
  5903. // finds neither. Walk the inner signature: param names / the method name are
  5904. // `identifier` (not `type_identifier`), so only types surface.
  5905. if (this.language === 'dart') {
  5906. let sig: SyntaxNode | undefined = node;
  5907. if (node.type === 'method_signature') {
  5908. sig = node.namedChildren.find(
  5909. (c: SyntaxNode) =>
  5910. c.type === 'function_signature' ||
  5911. c.type === 'getter_signature' ||
  5912. c.type === 'setter_signature' ||
  5913. c.type === 'constructor_signature' ||
  5914. c.type === 'factory_constructor_signature'
  5915. ) ?? node;
  5916. }
  5917. this.extractTypeRefsFromSubtree(sig, nodeId);
  5918. return;
  5919. }
  5920. // Extract parameter type annotations. Scala curries — `def f(a)(implicit
  5921. // M: TC)` has MULTIPLE `parameters` siblings, and the typeclass is almost
  5922. // always in the trailing implicit list — so walk every parameter list, not
  5923. // just getChildByField's first match.
  5924. if (this.language === 'scala') {
  5925. for (const pc of node.namedChildren) {
  5926. if (pc.type === 'parameters') this.extractTypeRefsFromSubtree(pc, nodeId);
  5927. }
  5928. } else {
  5929. const params = getChildByField(node, this.extractor.paramsField || 'parameters');
  5930. if (params) {
  5931. this.extractTypeRefsFromSubtree(params, nodeId);
  5932. }
  5933. }
  5934. // Extract return type annotation
  5935. const returnType = getChildByField(node, this.extractor.returnField || 'return_type');
  5936. if (returnType) {
  5937. this.extractTypeRefsFromSubtree(returnType, nodeId);
  5938. }
  5939. // Scala context bounds / type-parameter bounds: `def f[A: Monoid]`,
  5940. // `[F[_]: Monad]`, `[A <: Foo]` carry the bound type inside `type_parameters`.
  5941. // This is THE pervasive way a typeclass is required in Scala, yet the bound
  5942. // never appears in the value parameters. Param NAMES are `identifier` (not
  5943. // `type_identifier`), so only the bound types surface. Scala-only: in other
  5944. // languages a `type_parameters` child holds declaration names as
  5945. // `type_identifier` (TS `<T>`), which would wrongly surface as refs.
  5946. if (this.language === 'scala') {
  5947. const typeParams = node.namedChildren.find(
  5948. (c: SyntaxNode) => c.type === 'type_parameters'
  5949. );
  5950. if (typeParams) {
  5951. this.extractTypeRefsFromSubtree(typeParams, nodeId);
  5952. }
  5953. }
  5954. // Extract direct type annotation (for class fields like `model: ITextModel`)
  5955. const typeAnnotation = node.namedChildren.find(
  5956. (c: SyntaxNode) => c.type === 'type_annotation'
  5957. );
  5958. if (typeAnnotation) {
  5959. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  5960. }
  5961. }
  5962. /**
  5963. * Extract C# type references from a node that owns a type position —
  5964. * a method/constructor declaration, a property declaration, or a
  5965. * field declaration (which wraps `variable_declaration → type`).
  5966. *
  5967. * Walks ONLY into known type fields, so parameter names like
  5968. * `request` in `Build(UserDto request)` are never mis-emitted as
  5969. * type references. Once inside a type subtree, `walkCsharpTypePosition`
  5970. * recognizes C#'s actual type-leaf node kinds (`identifier`,
  5971. * `qualified_name`, `generic_name`, `array_type`, `nullable_type`,
  5972. * `tuple_type`, …) — none of which are `type_identifier`. Closes #381.
  5973. */
  5974. private extractCsharpTypeRefs(node: SyntaxNode, nodeId: string): void {
  5975. // A property's type is under the `type` field; a method/constructor's RETURN
  5976. // type is under `returns` (tree-sitter-c-sharp 0.23.x — older builds used
  5977. // `type` for both). A node carries only one of the two, so checking both
  5978. // covers return types and property types without conflating them.
  5979. const directType = getChildByField(node, 'type') ?? getChildByField(node, 'returns');
  5980. if (directType) this.walkCsharpTypePosition(directType, nodeId);
  5981. // Field declarations wrap declarators in a `variable_declaration`
  5982. // whose `type` field carries the type. The outer `field_declaration`
  5983. // has no `type` field of its own, so the call above is a no-op here
  5984. // and we descend one level.
  5985. const varDecl = node.namedChildren.find((c: SyntaxNode) => c.type === 'variable_declaration');
  5986. if (varDecl) {
  5987. const vdType = getChildByField(varDecl, 'type');
  5988. if (vdType) this.walkCsharpTypePosition(vdType, nodeId);
  5989. }
  5990. // Method / constructor parameters. The field name on
  5991. // `method_declaration` is `parameters`; it points at a
  5992. // `parameter_list` whose `parameter` children each have their own
  5993. // `type` field. Walking ONLY the type field skips parameter NAMES,
  5994. // which would otherwise mis-emit as type references.
  5995. const params = getChildByField(node, 'parameters');
  5996. if (params) {
  5997. for (let i = 0; i < params.namedChildCount; i++) {
  5998. const child = params.namedChild(i);
  5999. if (!child || child.type !== 'parameter') continue;
  6000. const paramType = getChildByField(child, 'type');
  6001. if (paramType) this.walkCsharpTypePosition(paramType, nodeId);
  6002. }
  6003. }
  6004. }
  6005. /**
  6006. * Record the dependencies declared by a C# PRIMARY CONSTRUCTOR
  6007. * (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache) { … }`,
  6008. * C# 12+). The parameter list hangs off the class/struct/record declaration
  6009. * as an unnamed-field `parameter_list` child (not the `parameters` field a
  6010. * method uses), so it's found by node type. Each parameter's declared type
  6011. * becomes a `references` edge from the owning type — these are exactly the
  6012. * services a DI-registered type depends on, so impact/blast-radius and
  6013. * "who depends on this contract" now see them. No-op when there's no primary
  6014. * constructor. (#237)
  6015. */
  6016. private extractCsharpPrimaryCtorParamRefs(node: SyntaxNode, ownerId: string): void {
  6017. if (this.language !== 'csharp') return;
  6018. const paramList = node.namedChildren.find((c: SyntaxNode) => c.type === 'parameter_list');
  6019. if (!paramList) return;
  6020. for (let i = 0; i < paramList.namedChildCount; i++) {
  6021. const param = paramList.namedChild(i);
  6022. if (!param || param.type !== 'parameter') continue;
  6023. const paramType = getChildByField(param, 'type');
  6024. if (paramType) this.walkCsharpTypePosition(paramType, ownerId);
  6025. }
  6026. }
  6027. /**
  6028. * Walk a C# subtree that is KNOWN to be in a type position
  6029. * (return type, parameter type, property type, field type, generic
  6030. * argument). Identifiers here are type names, not parameter names.
  6031. */
  6032. private walkCsharpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  6033. // `predefined_type` is int/string/bool/etc. — never a project ref.
  6034. if (node.type === 'predefined_type') return;
  6035. // Bare type name: `Foo` in `Foo bar`, or the `Foo` inside `List<Foo>`.
  6036. if (node.type === 'identifier') {
  6037. const name = getNodeText(node, this.source);
  6038. if (name && !this.BUILTIN_TYPES.has(name)) {
  6039. this.unresolvedReferences.push({
  6040. fromNodeId,
  6041. referenceName: name,
  6042. referenceKind: 'references',
  6043. line: node.startPosition.row + 1,
  6044. column: node.startPosition.column,
  6045. });
  6046. }
  6047. return;
  6048. }
  6049. // `Namespace.Foo` → the rightmost identifier is the type. Emit the
  6050. // full qualified name as the reference; the resolver can still match
  6051. // on the trailing simple name when needed.
  6052. if (node.type === 'qualified_name') {
  6053. const text = getNodeText(node, this.source);
  6054. const last = text.split('.').pop() ?? text;
  6055. if (last && !this.BUILTIN_TYPES.has(last)) {
  6056. this.unresolvedReferences.push({
  6057. fromNodeId,
  6058. referenceName: last,
  6059. referenceKind: 'references',
  6060. line: node.startPosition.row + 1,
  6061. column: node.startPosition.column,
  6062. });
  6063. }
  6064. return;
  6065. }
  6066. // `(int Code, Foo Payload)` — tuple element has BOTH a `type` and a
  6067. // `name` field; descending into all named children would mis-emit
  6068. // the element name (`Code`, `Payload`) as a type ref. Walk only the
  6069. // type field.
  6070. if (node.type === 'tuple_element') {
  6071. const t = getChildByField(node, 'type');
  6072. if (t) this.walkCsharpTypePosition(t, fromNodeId);
  6073. return;
  6074. }
  6075. // Composite type nodes — recurse into named children. Covers
  6076. // `generic_name` (head identifier + `type_argument_list`),
  6077. // `nullable_type`, `array_type`, `pointer_type`, `tuple_type`,
  6078. // `ref_type`, and any newer wrapping shapes the grammar adds.
  6079. // Identifiers reached here are all type-positional (parameter/field
  6080. // names are gated out before we descend).
  6081. for (let i = 0; i < node.namedChildCount; i++) {
  6082. const child = node.namedChild(i);
  6083. if (child) this.walkCsharpTypePosition(child, fromNodeId);
  6084. }
  6085. }
  6086. /**
  6087. * Extract PHP type references from a method/function/property declaration.
  6088. * Walks ONLY type positions: each parameter's type child (inside
  6089. * `formal_parameters`), the return type, and a property's type — all
  6090. * `named_type` / `optional_type` / `union_type` / … direct children. Parameter
  6091. * and property NAMES are `variable_name` (`$x`), never type nodes, so they
  6092. * can't be mis-emitted.
  6093. */
  6094. private extractPhpTypeRefs(node: SyntaxNode, nodeId: string): void {
  6095. const params = node.namedChildren.find((c: SyntaxNode) => c.type === 'formal_parameters');
  6096. if (params) {
  6097. for (const p of params.namedChildren) {
  6098. // simple_parameter / property_promotion_parameter / variadic_parameter
  6099. for (const c of p.namedChildren) {
  6100. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  6101. }
  6102. }
  6103. }
  6104. // Return type (method/function) and property type are TYPE nodes that are
  6105. // DIRECT children of the declaration.
  6106. for (const c of node.namedChildren) {
  6107. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  6108. }
  6109. }
  6110. /** Walk a PHP subtree KNOWN to be in a type position; emit class/interface refs. */
  6111. private walkPhpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  6112. if (node.type === 'primitive_type') return; // int/string/void/…
  6113. if (node.type === 'name') {
  6114. const name = getNodeText(node, this.source);
  6115. if (name && !this.PHP_PSEUDO_TYPES.has(name)) {
  6116. this.unresolvedReferences.push({
  6117. fromNodeId, referenceName: name, referenceKind: 'references',
  6118. line: node.startPosition.row + 1, column: node.startPosition.column,
  6119. });
  6120. }
  6121. return;
  6122. }
  6123. if (node.type === 'qualified_name') {
  6124. // `App\Contracts\Logger` → match on the trailing simple name (what the
  6125. // class node is stored as, and what a `use` import brings into scope).
  6126. const last = getNodeText(node, this.source).split('\\').pop() ?? '';
  6127. if (last && !this.PHP_PSEUDO_TYPES.has(last)) {
  6128. this.unresolvedReferences.push({
  6129. fromNodeId, referenceName: last, referenceKind: 'references',
  6130. line: node.startPosition.row + 1, column: node.startPosition.column,
  6131. });
  6132. }
  6133. return;
  6134. }
  6135. // optional_type / nullable_type / union_type / intersection_type / named_type → recurse
  6136. for (let i = 0; i < node.namedChildCount; i++) {
  6137. const child = node.namedChild(i);
  6138. if (child) this.walkPhpTypePosition(child, fromNodeId);
  6139. }
  6140. }
  6141. /**
  6142. * Extract type references from a variable's type annotation.
  6143. */
  6144. private extractVariableTypeAnnotation(node: SyntaxNode, nodeId: string): void {
  6145. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  6146. // Find type_annotation child (covers TS `: Type`, Rust `: Type`, etc.)
  6147. const typeAnnotation = node.namedChildren.find(
  6148. (c: SyntaxNode) => c.type === 'type_annotation'
  6149. );
  6150. if (typeAnnotation) {
  6151. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  6152. }
  6153. }
  6154. /**
  6155. * Recursively walk a subtree and extract all type_identifier references.
  6156. * Handles unions, intersections, generics, arrays, etc.
  6157. */
  6158. private extractTypeRefsFromSubtree(node: SyntaxNode, fromNodeId: string): void {
  6159. if (node.type === 'type_identifier') {
  6160. const typeName = getNodeText(node, this.source);
  6161. if (typeName && !this.BUILTIN_TYPES.has(typeName)) {
  6162. this.unresolvedReferences.push({
  6163. fromNodeId,
  6164. referenceName: typeName,
  6165. referenceKind: 'references',
  6166. line: node.startPosition.row + 1,
  6167. column: node.startPosition.column,
  6168. });
  6169. }
  6170. return; // type_identifier is a leaf
  6171. }
  6172. // Recurse into children (handles union_type, intersection_type, generic_type, etc.)
  6173. for (let i = 0; i < node.namedChildCount; i++) {
  6174. const child = node.namedChild(i);
  6175. if (child) {
  6176. this.extractTypeRefsFromSubtree(child, fromNodeId);
  6177. }
  6178. }
  6179. }
  6180. /**
  6181. * Handle Pascal-specific AST structures.
  6182. * Returns true if the node was fully handled and children should be skipped.
  6183. */
  6184. private visitPascalNode(node: SyntaxNode): boolean {
  6185. const nodeType = node.type;
  6186. // Unit/Program/Library → module node
  6187. if (nodeType === 'unit' || nodeType === 'program' || nodeType === 'library') {
  6188. const moduleNameNode = node.namedChildren.find(
  6189. (c: SyntaxNode) => c.type === 'moduleName'
  6190. );
  6191. const name = moduleNameNode ? getNodeText(moduleNameNode, this.source) : '';
  6192. // Fallback to filename without extension if module name is empty
  6193. const moduleName = name || path.basename(this.filePath).replace(/\.[^.]+$/, '');
  6194. this.createNode('module', moduleName, node);
  6195. // Continue visiting children (interface/implementation sections)
  6196. for (let i = 0; i < node.namedChildCount; i++) {
  6197. const child = node.namedChild(i);
  6198. if (child) this.visitNode(child);
  6199. }
  6200. return true;
  6201. }
  6202. // declType wraps declClass/declIntf/declEnum/type-alias
  6203. // The name lives on declType, the inner node determines the kind
  6204. if (nodeType === 'declType') {
  6205. this.extractPascalDeclType(node);
  6206. return true;
  6207. }
  6208. // declUses → import nodes for each unit name
  6209. if (nodeType === 'declUses') {
  6210. this.extractPascalUses(node);
  6211. return true;
  6212. }
  6213. // declConsts → container; visit children for individual declConst
  6214. if (nodeType === 'declConsts') {
  6215. for (let i = 0; i < node.namedChildCount; i++) {
  6216. const child = node.namedChild(i);
  6217. if (child?.type === 'declConst') {
  6218. this.extractPascalConst(child);
  6219. }
  6220. }
  6221. return true;
  6222. }
  6223. // declConst at top level (outside declConsts)
  6224. if (nodeType === 'declConst') {
  6225. this.extractPascalConst(node);
  6226. return true;
  6227. }
  6228. // declTypes → container for type declarations
  6229. if (nodeType === 'declTypes') {
  6230. for (let i = 0; i < node.namedChildCount; i++) {
  6231. const child = node.namedChild(i);
  6232. if (child) this.visitNode(child);
  6233. }
  6234. return true;
  6235. }
  6236. // declVars → container for variable declarations
  6237. if (nodeType === 'declVars') {
  6238. for (let i = 0; i < node.namedChildCount; i++) {
  6239. const child = node.namedChild(i);
  6240. if (child?.type === 'declVar') {
  6241. const nameNode = getChildByField(child, 'name');
  6242. if (nameNode) {
  6243. const name = getNodeText(nameNode, this.source);
  6244. this.createNode('variable', name, child);
  6245. }
  6246. }
  6247. }
  6248. return true;
  6249. }
  6250. // defProc in implementation section → extract calls but don't create duplicate nodes
  6251. if (nodeType === 'defProc') {
  6252. this.extractPascalDefProc(node);
  6253. return true;
  6254. }
  6255. // declProp → property node
  6256. if (nodeType === 'declProp') {
  6257. const nameNode = getChildByField(node, 'name');
  6258. if (nameNode) {
  6259. const name = getNodeText(nameNode, this.source);
  6260. const visibility = this.extractor!.getVisibility?.(node);
  6261. this.createNode('property', name, node, { visibility });
  6262. }
  6263. return true;
  6264. }
  6265. // declField → field node
  6266. if (nodeType === 'declField') {
  6267. const nameNode = getChildByField(node, 'name');
  6268. if (nameNode) {
  6269. const name = getNodeText(nameNode, this.source);
  6270. const visibility = this.extractor!.getVisibility?.(node);
  6271. this.createNode('field', name, node, { visibility });
  6272. }
  6273. return true;
  6274. }
  6275. // declSection → visit children (propagates visibility via getVisibility)
  6276. if (nodeType === 'declSection') {
  6277. for (let i = 0; i < node.namedChildCount; i++) {
  6278. const child = node.namedChild(i);
  6279. if (child) this.visitNode(child);
  6280. }
  6281. return true;
  6282. }
  6283. // exprCall → extract function call reference
  6284. if (nodeType === 'exprCall') {
  6285. this.extractPascalCall(node);
  6286. return true;
  6287. }
  6288. // interface/implementation sections → visit children
  6289. if (nodeType === 'interface' || nodeType === 'implementation') {
  6290. for (let i = 0; i < node.namedChildCount; i++) {
  6291. const child = node.namedChild(i);
  6292. if (child) this.visitNode(child);
  6293. }
  6294. return true;
  6295. }
  6296. // block (begin..end) → visit for calls
  6297. if (nodeType === 'block') {
  6298. this.visitPascalBlock(node);
  6299. return true;
  6300. }
  6301. return false;
  6302. }
  6303. /**
  6304. * Extract a Pascal declType node (class, interface, enum, or type alias)
  6305. */
  6306. private extractPascalDeclType(node: SyntaxNode): void {
  6307. const nameNode = getChildByField(node, 'name');
  6308. if (!nameNode) return;
  6309. const name = getNodeText(nameNode, this.source);
  6310. // Find the inner type declaration
  6311. const declClass = node.namedChildren.find(
  6312. (c: SyntaxNode) => c.type === 'declClass'
  6313. );
  6314. const declIntf = node.namedChildren.find(
  6315. (c: SyntaxNode) => c.type === 'declIntf'
  6316. );
  6317. const typeChild = node.namedChildren.find(
  6318. (c: SyntaxNode) => c.type === 'type'
  6319. );
  6320. if (declClass) {
  6321. const classNode = this.createNode('class', name, node);
  6322. if (classNode) {
  6323. // Extract inheritance from typeref children of declClass
  6324. this.extractPascalInheritance(declClass, classNode.id);
  6325. // Visit class body
  6326. this.nodeStack.push(classNode.id);
  6327. for (let i = 0; i < declClass.namedChildCount; i++) {
  6328. const child = declClass.namedChild(i);
  6329. if (child) this.visitNode(child);
  6330. }
  6331. this.nodeStack.pop();
  6332. }
  6333. } else if (declIntf) {
  6334. const ifaceNode = this.createNode('interface', name, node);
  6335. if (ifaceNode) {
  6336. // Visit interface members
  6337. this.nodeStack.push(ifaceNode.id);
  6338. for (let i = 0; i < declIntf.namedChildCount; i++) {
  6339. const child = declIntf.namedChild(i);
  6340. if (child) this.visitNode(child);
  6341. }
  6342. this.nodeStack.pop();
  6343. }
  6344. } else if (typeChild) {
  6345. // Check if it contains a declEnum
  6346. const declEnum = typeChild.namedChildren.find(
  6347. (c: SyntaxNode) => c.type === 'declEnum'
  6348. );
  6349. if (declEnum) {
  6350. const enumNode = this.createNode('enum', name, node);
  6351. if (enumNode) {
  6352. // Extract enum members
  6353. this.nodeStack.push(enumNode.id);
  6354. for (let i = 0; i < declEnum.namedChildCount; i++) {
  6355. const child = declEnum.namedChild(i);
  6356. if (child?.type === 'declEnumValue') {
  6357. const memberName = getChildByField(child, 'name');
  6358. if (memberName) {
  6359. this.createNode('enum_member', getNodeText(memberName, this.source), child);
  6360. }
  6361. }
  6362. }
  6363. this.nodeStack.pop();
  6364. }
  6365. } else {
  6366. // Simple type alias: type TFoo = string / type TFoo = Integer
  6367. this.createNode('type_alias', name, node);
  6368. }
  6369. } else {
  6370. // Fallback: could be a forward declaration or simple alias
  6371. this.createNode('type_alias', name, node);
  6372. }
  6373. }
  6374. /**
  6375. * Extract Pascal uses clause into individual import nodes
  6376. */
  6377. private extractPascalUses(node: SyntaxNode): void {
  6378. const importText = getNodeText(node, this.source).trim();
  6379. for (let i = 0; i < node.namedChildCount; i++) {
  6380. const child = node.namedChild(i);
  6381. if (child?.type === 'moduleName') {
  6382. const unitName = getNodeText(child, this.source);
  6383. this.createNode('import', unitName, child, {
  6384. signature: importText,
  6385. });
  6386. // Create unresolved reference for resolution
  6387. if (this.nodeStack.length > 0) {
  6388. const parentId = this.nodeStack[this.nodeStack.length - 1];
  6389. if (parentId) {
  6390. this.unresolvedReferences.push({
  6391. fromNodeId: parentId,
  6392. referenceName: unitName,
  6393. referenceKind: 'imports',
  6394. line: child.startPosition.row + 1,
  6395. column: child.startPosition.column,
  6396. });
  6397. }
  6398. }
  6399. }
  6400. }
  6401. }
  6402. /**
  6403. * Extract a Pascal constant declaration
  6404. */
  6405. private extractPascalConst(node: SyntaxNode): void {
  6406. const nameNode = getChildByField(node, 'name');
  6407. if (!nameNode) return;
  6408. const name = getNodeText(nameNode, this.source);
  6409. const defaultValue = node.namedChildren.find(
  6410. (c: SyntaxNode) => c.type === 'defaultValue'
  6411. );
  6412. const sig = defaultValue ? getNodeText(defaultValue, this.source) : undefined;
  6413. this.createNode('constant', name, node, { signature: sig });
  6414. }
  6415. /**
  6416. * Extract Pascal inheritance (extends/implements) from declClass typeref children
  6417. */
  6418. private extractPascalInheritance(declClass: SyntaxNode, classId: string): void {
  6419. const typerefs = declClass.namedChildren.filter(
  6420. (c: SyntaxNode) => c.type === 'typeref'
  6421. );
  6422. for (let i = 0; i < typerefs.length; i++) {
  6423. const ref = typerefs[i]!;
  6424. const name = getNodeText(ref, this.source);
  6425. this.unresolvedReferences.push({
  6426. fromNodeId: classId,
  6427. referenceName: name,
  6428. referenceKind: i === 0 ? 'extends' : 'implements',
  6429. line: ref.startPosition.row + 1,
  6430. column: ref.startPosition.column,
  6431. });
  6432. }
  6433. }
  6434. /**
  6435. * Extract calls and resolve method context from a Pascal defProc (implementation body).
  6436. * Does not create a new node — the declaration was already captured from the interface section.
  6437. */
  6438. private extractPascalDefProc(node: SyntaxNode): void {
  6439. // Find the matching declaration node by name to use as call parent
  6440. const declProc = node.namedChildren.find(
  6441. (c: SyntaxNode) => c.type === 'declProc'
  6442. );
  6443. if (!declProc) return;
  6444. const nameNode = getChildByField(declProc, 'name');
  6445. if (!nameNode) return;
  6446. const fullName = getNodeText(nameNode, this.source).trim();
  6447. // fullName is like "TAuthService.Create"
  6448. const shortName = fullName.includes('.') ? fullName.split('.').pop()! : fullName;
  6449. const fullNameKey = fullName.toLowerCase();
  6450. const shortNameKey = shortName.toLowerCase();
  6451. // Build method index on first use (O(n) once, then O(1) per lookup)
  6452. if (!this.methodIndex) {
  6453. this.methodIndex = new Map();
  6454. for (const n of this.nodes) {
  6455. if (n.kind === 'method' || n.kind === 'function') {
  6456. const nameKey = n.name.toLowerCase();
  6457. // Keep first seen short-name mapping to avoid silently overwriting earlier entries.
  6458. if (!this.methodIndex.has(nameKey)) {
  6459. this.methodIndex.set(nameKey, n.id);
  6460. }
  6461. // For Pascal methods, also index qualified forms (e.g. TAuthService.Create).
  6462. if (n.kind === 'method') {
  6463. const qualifiedParts = n.qualifiedName.split('::');
  6464. if (qualifiedParts.length >= 2) {
  6465. // Create suffix keys so both "Module.Class.Method" and "Class.Method" can resolve.
  6466. for (let i = 0; i < qualifiedParts.length - 1; i++) {
  6467. const scopedName = qualifiedParts.slice(i).join('.').toLowerCase();
  6468. this.methodIndex.set(scopedName, n.id);
  6469. }
  6470. }
  6471. }
  6472. }
  6473. }
  6474. }
  6475. let parentId =
  6476. this.methodIndex.get(fullNameKey) ||
  6477. this.methodIndex.get(shortNameKey);
  6478. // No existing node? This is an implementation-only **free** procedure/function
  6479. // (`procedure Helper; begin … end;` with no interface declaration and not a
  6480. // class method). Create a function node so its body's calls attribute to it,
  6481. // not to the enclosing file/module. A method (`TClass.Method`, a dotted name)
  6482. // always has a node from its class declaration, so this only fires for free
  6483. // routines — and the methodIndex lookup above already covers interface-declared
  6484. // free routines, so there's no duplicate.
  6485. if (!parentId && !fullName.includes('.')) {
  6486. const fnNode = this.createNode('function', fullName, declProc, {
  6487. signature: this.extractor?.getSignature?.(declProc, this.source),
  6488. visibility: this.extractor?.getVisibility?.(declProc),
  6489. });
  6490. if (fnNode) {
  6491. parentId = fnNode.id;
  6492. this.methodIndex.set(fullNameKey, fnNode.id);
  6493. if (!this.methodIndex.has(shortNameKey)) this.methodIndex.set(shortNameKey, fnNode.id);
  6494. }
  6495. }
  6496. if (!parentId) parentId = this.nodeStack[this.nodeStack.length - 1];
  6497. if (!parentId) return;
  6498. // Visit the block for calls
  6499. const block = node.namedChildren.find(
  6500. (c: SyntaxNode) => c.type === 'block'
  6501. );
  6502. if (block) {
  6503. this.nodeStack.push(parentId);
  6504. this.visitPascalBlock(block);
  6505. this.nodeStack.pop();
  6506. }
  6507. }
  6508. /**
  6509. * Extract function calls from a Pascal expression
  6510. */
  6511. private extractPascalCall(node: SyntaxNode): void {
  6512. if (this.nodeStack.length === 0) return;
  6513. const callerId = this.nodeStack[this.nodeStack.length - 1];
  6514. if (!callerId) return;
  6515. // Get the callee name — first child is typically the identifier or exprDot
  6516. const firstChild = node.namedChild(0);
  6517. if (!firstChild) return;
  6518. let calleeName = '';
  6519. if (firstChild.type === 'exprDot') {
  6520. // Chained static-factory call: `TFoo.GetInstance().DoIt()` — the exprDot's
  6521. // receiver is itself an `exprCall`, so the bare identifier list would
  6522. // collapse to just `DoIt` and mis-resolve to a same-named method on an
  6523. // unrelated class. Encode `TFoo.GetInstance().DoIt` so resolution infers
  6524. // DoIt's class from what `TFoo.GetInstance` RETURNS (#645/#608). Only a
  6525. // capitalized class-factory chain; a unary outer method.
  6526. const innerCall = firstChild.namedChildren.find((c: SyntaxNode) => c.type === 'exprCall');
  6527. const outerId = firstChild.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  6528. const method = outerId ? getNodeText(outerId, this.source) : '';
  6529. if (innerCall && method && /^\w+$/.test(method)) {
  6530. const innerFirst = innerCall.namedChild(0);
  6531. let innerCallee = '';
  6532. if (innerFirst?.type === 'exprDot') {
  6533. innerCallee = innerFirst.namedChildren
  6534. .filter((c: SyntaxNode) => c.type === 'identifier')
  6535. .map((id: SyntaxNode) => getNodeText(id, this.source))
  6536. .join('.');
  6537. } else if (innerFirst?.type === 'identifier') {
  6538. innerCallee = getNodeText(innerFirst, this.source);
  6539. }
  6540. // Gate on the Delphi type-naming convention — `TFoo` classes / `IFoo`
  6541. // interfaces — so a class-factory chain re-encodes but a capitalized
  6542. // VARIABLE/parameter chain (Pascal capitalizes locals too: `Curve.X().Y()`,
  6543. // `Self.X().Y()`) stays bare and keeps its existing bare-name resolution.
  6544. calleeName = innerCallee && /^[TI][A-Z]/.test(innerCallee)
  6545. ? `${innerCallee}().${method}`
  6546. : method;
  6547. } else {
  6548. // Qualified call: Obj.Method(...)
  6549. const identifiers = firstChild.namedChildren.filter(
  6550. (c: SyntaxNode) => c.type === 'identifier'
  6551. );
  6552. if (identifiers.length > 0) {
  6553. calleeName = identifiers.map((id: SyntaxNode) => getNodeText(id, this.source)).join('.');
  6554. }
  6555. }
  6556. } else if (firstChild.type === 'identifier') {
  6557. calleeName = getNodeText(firstChild, this.source);
  6558. }
  6559. if (calleeName) {
  6560. this.unresolvedReferences.push({
  6561. fromNodeId: callerId,
  6562. referenceName: calleeName,
  6563. referenceKind: 'calls',
  6564. line: node.startPosition.row + 1,
  6565. column: node.startPosition.column,
  6566. });
  6567. }
  6568. // Also visit arguments for nested calls
  6569. const args = node.namedChildren.find(
  6570. (c: SyntaxNode) => c.type === 'exprArgs'
  6571. );
  6572. if (args) {
  6573. this.visitPascalBlock(args);
  6574. }
  6575. }
  6576. /**
  6577. * Extract a PAREN-LESS Pascal method/procedure call (`Obj.Method;`,
  6578. * `TFoo.GetInstance.DoIt;`). Pascal lets a no-arg method drop its parens, so it
  6579. * parses as a bare `exprDot` (not an `exprCall`). A bare `exprDot` is
  6580. * syntactically identical to a field/property access, so this is only ever
  6581. * called for a STATEMENT-level exprDot (caller-gated): a bare `Obj.Field;`
  6582. * statement is a no-op, so a statement-level dot expression is a call. (An
  6583. * exprDot in assignment LHS/RHS or a condition is left alone — there it really
  6584. * can be a field/property read.)
  6585. */
  6586. private extractPascalParenlessCall(node: SyntaxNode): void {
  6587. if (this.nodeStack.length === 0) return;
  6588. const callerId = this.nodeStack[this.nodeStack.length - 1];
  6589. if (!callerId) return;
  6590. const receiver = node.namedChild(0);
  6591. const outerId = node.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  6592. const method = outerId ? getNodeText(outerId, this.source) : '';
  6593. if (!method) return;
  6594. let calleeName = '';
  6595. // Chained: the receiver is itself a call — a paren-less `TFoo.GetInstance` (an
  6596. // inner exprDot) or a paren'd `TFoo.GetInstance()` (an exprCall). Encode the
  6597. // chain `TFoo.GetInstance().DoIt` so resolution infers DoIt's class from what
  6598. // the factory RETURNS (#645/#608), gated on the Delphi `TFoo`/`IFoo` type
  6599. // convention; a capitalized VARIABLE chain stays a bare method name.
  6600. if ((receiver?.type === 'exprDot' || receiver?.type === 'exprCall') && /^\w+$/.test(method)) {
  6601. const innerCalleeNode = receiver.type === 'exprCall' ? receiver.namedChild(0) : receiver;
  6602. const innerCallee = !innerCalleeNode
  6603. ? ''
  6604. : innerCalleeNode.type === 'identifier'
  6605. ? getNodeText(innerCalleeNode, this.source)
  6606. : innerCalleeNode.namedChildren
  6607. .filter((c: SyntaxNode) => c.type === 'identifier')
  6608. .map((id: SyntaxNode) => getNodeText(id, this.source))
  6609. .join('.');
  6610. if (innerCallee && /^[TI][A-Z]/.test(innerCallee)) {
  6611. calleeName = `${innerCallee}().${method}`;
  6612. // The T/I-prefixed inner is itself a real call — record it too.
  6613. if (receiver.type === 'exprCall') this.extractPascalCall(receiver);
  6614. else this.extractPascalParenlessCall(receiver);
  6615. } else {
  6616. calleeName = method; // non-class receiver: a bare method ref (no field-access ref)
  6617. }
  6618. } else {
  6619. // Simple: `Obj.Method` → the dotted name (resolves via the receiver / bare name).
  6620. calleeName = node.namedChildren
  6621. .filter((c: SyntaxNode) => c.type === 'identifier')
  6622. .map((id: SyntaxNode) => getNodeText(id, this.source))
  6623. .join('.');
  6624. }
  6625. if (calleeName) {
  6626. this.unresolvedReferences.push({
  6627. fromNodeId: callerId,
  6628. referenceName: calleeName,
  6629. referenceKind: 'calls',
  6630. line: node.startPosition.row + 1,
  6631. column: node.startPosition.column,
  6632. });
  6633. }
  6634. }
  6635. /**
  6636. * Recursively visit a Pascal block/statement tree for call expressions
  6637. */
  6638. private visitPascalBlock(node: SyntaxNode): void {
  6639. for (let i = 0; i < node.namedChildCount; i++) {
  6640. const child = node.namedChild(i);
  6641. if (!child) continue;
  6642. // Function-as-value capture (#756): Pascal bodies are walked here, not
  6643. // in visitNode/visitForCallsAndStructure, so the capture hook fires here
  6644. // — assignment RHS is the Delphi event-wiring idiom (`OnFire := Handler`).
  6645. this.maybeCaptureFnRefs(child, child.type);
  6646. if (child.type === 'exprCall') {
  6647. this.extractPascalCall(child);
  6648. // The walker doesn't descend into a call's arguments — dispatch the
  6649. // argument container directly (`RegisterHandler(TargetCb)` / `(@Cb)`).
  6650. const args = child.namedChildren.find((c: SyntaxNode) => c.type === 'exprArgs');
  6651. if (args) this.maybeCaptureFnRefs(args, 'exprArgs');
  6652. } else if (child.type === 'exprDot') {
  6653. // A STATEMENT-level bare exprDot is a paren-less call (`Obj.Free;`,
  6654. // `TFoo.GetInstance.DoIt;`). Anywhere else (assignment side, condition,
  6655. // expression) a bare exprDot is ambiguous with a field/property access,
  6656. // so there we only descend for paren'd inner calls.
  6657. if (node.type === 'statement') {
  6658. this.extractPascalParenlessCall(child);
  6659. } else {
  6660. for (let j = 0; j < child.namedChildCount; j++) {
  6661. const grandchild = child.namedChild(j);
  6662. if (grandchild?.type === 'exprCall') {
  6663. this.extractPascalCall(grandchild);
  6664. }
  6665. }
  6666. }
  6667. } else {
  6668. this.visitPascalBlock(child);
  6669. }
  6670. }
  6671. }
  6672. }
  6673. /**
  6674. * Extract nodes and edges from source code.
  6675. *
  6676. * If `frameworkNames` is provided, framework-specific extractors matching
  6677. * those names and the file's language are run after the tree-sitter pass.
  6678. * Their nodes/references/errors are merged into the returned result.
  6679. */
  6680. export function extractFromSource(
  6681. filePath: string,
  6682. source: string,
  6683. language?: Language,
  6684. frameworkNames?: string[]
  6685. ): ExtractionResult {
  6686. const detectedLanguage = language || detectLanguage(filePath, source);
  6687. const fileExtension = path.extname(filePath).toLowerCase();
  6688. let result: ExtractionResult;
  6689. // Use custom extractor for Svelte
  6690. if (detectedLanguage === 'svelte') {
  6691. const extractor = new SvelteExtractor(filePath, source);
  6692. result = extractor.extract();
  6693. } else if (detectedLanguage === 'vue') {
  6694. // Use custom extractor for Vue
  6695. const extractor = new VueExtractor(filePath, source);
  6696. result = extractor.extract();
  6697. } else if (detectedLanguage === 'astro') {
  6698. // Use custom extractor for Astro (frontmatter + template delegation)
  6699. const extractor = new AstroExtractor(filePath, source);
  6700. result = extractor.extract();
  6701. } else if (detectedLanguage === 'liquid') {
  6702. // Use custom extractor for Liquid
  6703. const extractor = new LiquidExtractor(filePath, source);
  6704. result = extractor.extract();
  6705. } else if (detectedLanguage === 'razor') {
  6706. // Use custom extractor for ASP.NET Razor (.cshtml) / Blazor (.razor) markup
  6707. const extractor = new RazorExtractor(filePath, source);
  6708. result = extractor.extract();
  6709. } else if (detectedLanguage === 'xml') {
  6710. // Custom extractor for MyBatis mapper XML. Non-mapper XML returns just a
  6711. // file node so the watcher tracks it without emitting symbols.
  6712. const extractor = new MyBatisExtractor(filePath, source);
  6713. result = extractor.extract();
  6714. } else if (detectedLanguage === 'cfml' || detectedLanguage === 'cfscript') {
  6715. // Custom extractor for CFML (.cfc/.cfm) — dialect-switches between the
  6716. // tag-based cfml grammar and the bare-script cfscript grammar. Standalone
  6717. // `.cfs` files (language 'cfscript') are always pure script (never `<`-led),
  6718. // so routing them through here too gets them the same anonymous-component
  6719. // filename fallback as a bare-script `.cfc` — without it a `.cfs` whose
  6720. // `component { ... }` declares no name (the grammar has no `name` field;
  6721. // CFML never spells one in source) stays `<anonymous>`.
  6722. const extractor = new CfmlExtractor(filePath, source, detectedLanguage);
  6723. result = extractor.extract();
  6724. } else if (isFileLevelOnlyLanguage(detectedLanguage)) {
  6725. // No symbol extraction at this stage — files are tracked at the file-record
  6726. // level only. Framework extractors (Drupal routing yml, Spring `@Value`
  6727. // resolution against application.yml/application.properties) run later and
  6728. // add per-file nodes/references when they apply.
  6729. result = { nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: 0 };
  6730. } else if (
  6731. detectedLanguage === 'pascal' &&
  6732. (fileExtension === '.dfm' || fileExtension === '.fmx')
  6733. ) {
  6734. // Use custom extractor for DFM/FMX form files
  6735. const extractor = new DfmExtractor(filePath, source);
  6736. result = extractor.extract();
  6737. } else {
  6738. // Native-kernel route (docs/design/rust-kernel-migration-plan.md): gated
  6739. // per language, null when not routed/available or on a kernel error —
  6740. // the wasm TreeSitterExtractor below stays the fallback either way.
  6741. const kernelResult = tryKernelExtract(filePath, source, detectedLanguage);
  6742. if (kernelResult) {
  6743. result = kernelResult;
  6744. } else {
  6745. // A kernel-deferred file already paid the (offset-preserving) preParse
  6746. // at the route point — reuse those bytes instead of blanking again.
  6747. const deferredPre = takeDeferredPreParse(filePath, source, detectedLanguage);
  6748. const extractor = new TreeSitterExtractor(
  6749. filePath,
  6750. deferredPre ?? source,
  6751. detectedLanguage,
  6752. { sourceIsPreParsed: deferredPre != null }
  6753. );
  6754. result = extractor.extract();
  6755. }
  6756. }
  6757. // Framework-specific extraction (routes, middleware, etc.)
  6758. if (frameworkNames && frameworkNames.length > 0) {
  6759. const allResolvers = getAllFrameworkResolvers();
  6760. const applicable = getApplicableFrameworks(
  6761. allResolvers.filter((r) => frameworkNames.includes(r.name)),
  6762. detectedLanguage
  6763. );
  6764. for (const fw of applicable) {
  6765. if (!fw.extract) continue;
  6766. try {
  6767. const fwResult = fw.extract(filePath, source);
  6768. result.nodes.push(...fwResult.nodes);
  6769. result.unresolvedReferences.push(...fwResult.references);
  6770. } catch (err) {
  6771. result.errors.push({
  6772. message: `Framework extractor '${fw.name}' failed: ${
  6773. err instanceof Error ? err.message : String(err)
  6774. }`,
  6775. filePath,
  6776. severity: 'warning',
  6777. });
  6778. }
  6779. }
  6780. }
  6781. return result;
  6782. }