tree-sitter.ts 312 KB

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