tree-sitter.ts 300 KB

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