tree-sitter.ts 295 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610
  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. * Build qualified name from node stack
  1312. */
  1313. private buildQualifiedName(name: string): string {
  1314. // Build a qualified name from the semantic hierarchy only (no file path).
  1315. // The file path is stored separately in filePath and pollutes FTS if included here.
  1316. // C/C++ enclosing namespaces prefix first (empty for every other language).
  1317. const parts: string[] = [...this.namespacePrefix];
  1318. for (const nodeId of this.nodeStack) {
  1319. const node = this.nodes.find((n) => n.id === nodeId);
  1320. if (node && node.kind !== 'file') {
  1321. parts.push(node.name);
  1322. }
  1323. }
  1324. parts.push(name);
  1325. return parts.join('::');
  1326. }
  1327. /**
  1328. * Build an ExtractorContext for passing to language-specific visitNode hooks.
  1329. */
  1330. private makeExtractorContext(): ExtractorContext {
  1331. // eslint-disable-next-line @typescript-eslint/no-this-alias
  1332. const self = this;
  1333. return {
  1334. createNode: (kind, name, node, extra) => self.createNode(kind, name, node, extra),
  1335. visitNode: (node) => self.visitNode(node),
  1336. visitFunctionBody: (body, functionId) => self.visitFunctionBody(body, functionId),
  1337. addUnresolvedReference: (ref) => self.unresolvedReferences.push(ref),
  1338. pushScope: (nodeId) => self.nodeStack.push(nodeId),
  1339. popScope: () => self.nodeStack.pop(),
  1340. get filePath() { return self.filePath; },
  1341. get source() { return self.source; },
  1342. get nodeStack() { return self.nodeStack; },
  1343. get nodes() { return self.nodes; },
  1344. };
  1345. }
  1346. /**
  1347. * Check if the current node stack indicates we are inside a class-like node
  1348. * (class, struct, interface, trait). File nodes do not count as class-like.
  1349. */
  1350. private isInsideClassLikeNode(): boolean {
  1351. if (this.nodeStack.length === 0) return false;
  1352. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1353. if (!parentId) return false;
  1354. const parentNode = this.nodes.find((n) => n.id === parentId);
  1355. if (!parentNode) return false;
  1356. return (
  1357. parentNode.kind === 'class' ||
  1358. parentNode.kind === 'struct' ||
  1359. parentNode.kind === 'interface' ||
  1360. parentNode.kind === 'trait' ||
  1361. parentNode.kind === 'enum' ||
  1362. parentNode.kind === 'module'
  1363. );
  1364. }
  1365. /**
  1366. * Ruby `CONST = …` assignment whose LHS is a `constant` node — a class/module
  1367. * (or top-level) constant worth extracting as a symbol even inside a class.
  1368. * Other languages don't give an assignment a `constant`-typed LHS, so this
  1369. * gate is effectively Ruby-only.
  1370. */
  1371. private isClassScopeConstantAssignment(node: SyntaxNode): boolean {
  1372. if (node.type !== 'assignment') return false;
  1373. const left = getChildByField(node, 'left') ?? node.namedChild(0);
  1374. return left?.type === 'constant';
  1375. }
  1376. /**
  1377. * Extract a function
  1378. */
  1379. private extractFunction(node: SyntaxNode, nameOverride?: string): void {
  1380. if (!this.extractor) return;
  1381. // If the language provides getReceiverType and this function has a receiver
  1382. // (e.g., Rust function_item inside an impl block), extract as method instead
  1383. if (this.extractor.getReceiverType?.(node, this.source)) {
  1384. this.extractMethod(node);
  1385. return;
  1386. }
  1387. // nameOverride is supplied only for explicitly-named anonymous functions the
  1388. // caller resolved itself (e.g. arrow values of exported-const object members
  1389. // — SvelteKit actions). Inline-object arrows reached by the general walker
  1390. // get no override, so they still fall through to the <anonymous> skip below.
  1391. let name = nameOverride ?? extractName(node, this.source, this.extractor);
  1392. // For arrow functions and function expressions assigned to variables,
  1393. // resolve the name from the parent variable_declarator.
  1394. // e.g. `export const useAuth = () => { ... }` — the arrow_function node
  1395. // has no `name` field; the name lives on the variable_declarator.
  1396. if (
  1397. !nameOverride &&
  1398. name === '<anonymous>' &&
  1399. (node.type === 'arrow_function' || node.type === 'function_expression')
  1400. ) {
  1401. const parent = node.parent;
  1402. if (parent?.type === 'variable_declarator') {
  1403. const varName = getChildByField(parent, 'name');
  1404. if (varName) {
  1405. name = getNodeText(varName, this.source);
  1406. }
  1407. }
  1408. }
  1409. if (name === '<anonymous>') {
  1410. // Don't emit a node for the anonymous wrapper itself, but still visit its
  1411. // body: AMD/RequireJS and CommonJS module wrappers (`define([], function(){…})`,
  1412. // `(function(){…})()`) hold named inner functions and calls that would
  1413. // otherwise be lost — the dispatcher set skipChildren, so nothing else
  1414. // descends into this subtree. (#528)
  1415. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1416. ?? getChildByField(node, this.extractor.bodyField);
  1417. if (body) {
  1418. this.visitFunctionBody(body, '');
  1419. }
  1420. return;
  1421. }
  1422. // Check for misparse artifacts (e.g. C++ macros causing "namespace detail" functions)
  1423. // Skip the node but still visit the body for calls and structural nodes
  1424. if (this.extractor.isMisparsedFunction?.(name, node)) {
  1425. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1426. ?? getChildByField(node, this.extractor.bodyField);
  1427. if (body) {
  1428. this.visitFunctionBody(body, '');
  1429. }
  1430. return;
  1431. }
  1432. const docstring = getPrecedingDocstring(node, this.source);
  1433. const signature = this.extractor.getSignature?.(node, this.source);
  1434. const visibility = this.extractor.getVisibility?.(node);
  1435. const isExported = this.extractor.isExported?.(node, this.source);
  1436. const isAsync = this.extractor.isAsync?.(node);
  1437. const isStatic = this.extractor.isStatic?.(node);
  1438. const returnType = this.extractor.getReturnType?.(node, this.source);
  1439. const funcNode = this.createNode('function', name, node, {
  1440. docstring,
  1441. signature,
  1442. visibility,
  1443. isExported,
  1444. isAsync,
  1445. isStatic,
  1446. returnType,
  1447. });
  1448. if (!funcNode) return;
  1449. // Extract type annotations (parameter types and return type)
  1450. this.extractTypeAnnotations(node, funcNode.id);
  1451. // Extract decorators applied to the function (rare in JS/TS but
  1452. // present in Python `@decorator def f():` and Java/Kotlin
  1453. // annotations on free functions).
  1454. this.extractDecoratorsFor(node, funcNode.id);
  1455. // Push to stack and visit body
  1456. this.nodeStack.push(funcNode.id);
  1457. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1458. ?? getChildByField(node, this.extractor.bodyField);
  1459. if (body) {
  1460. this.visitFunctionBody(body, funcNode.id);
  1461. }
  1462. this.nodeStack.pop();
  1463. }
  1464. /**
  1465. * Detect a React component declared via an HOC wrapper whose result is itself a
  1466. * component: `forwardRef(...)`, `memo(...)`, `React.forwardRef/memo(...)`, and
  1467. * styled-components / emotion `styled.tag\`…\`` / `styled(Base)\`…\``. These
  1468. * initializers are a call / tagged-template (not a bare arrow), so the const is
  1469. * otherwise classified `constant` — and a constant is skipped by both the
  1470. * JSX-render edge synthesizer and component resolution, so `<Button/>` usages
  1471. * get no edge and callers/impact silently return empty (#841).
  1472. *
  1473. * Returns `{ inner }` — the inline render function to extract as the component
  1474. * body, or `null` when the wrapper has no inline function (`memo(Imported)`,
  1475. * `styled.button\`…\``) and only a bodyless component node is minted — or
  1476. * `undefined` when this initializer is not a recognized component wrapper.
  1477. */
  1478. private reactComponentHoc(valueNode: SyntaxNode): { inner: SyntaxNode | null } | undefined {
  1479. if (valueNode.type !== 'call_expression') return undefined;
  1480. const callee = getChildByField(valueNode, 'function');
  1481. if (!callee) return undefined;
  1482. const calleeText = getNodeText(callee, this.source);
  1483. // styled-components / emotion: `styled.button\`…\`` / `styled(Base)\`…\``.
  1484. // tree-sitter models these tagged templates as a call_expression whose callee
  1485. // is the `styled.x` / `styled(Base)` tag (\b avoids matching `styledFoo`).
  1486. // No inline render fn — the argument is the CSS template.
  1487. if (/^styled\b/.test(calleeText)) return { inner: null };
  1488. // React HOCs: `forwardRef`/`memo`/`React.forwardRef`/`React.memo`.
  1489. if (!REACT_COMPONENT_HOCS.has(calleeText)) return undefined;
  1490. // The first arrow / function-expression argument is the render fn (if inline;
  1491. // `memo(Imported)` passes a bare identifier and has none).
  1492. const args = getChildByField(valueNode, 'arguments');
  1493. let inner: SyntaxNode | null = null;
  1494. if (args) {
  1495. for (let i = 0; i < args.namedChildCount; i++) {
  1496. const a = args.namedChild(i);
  1497. if (a && (a.type === 'arrow_function' || a.type === 'function_expression')) {
  1498. inner = a;
  1499. break;
  1500. }
  1501. }
  1502. }
  1503. return { inner };
  1504. }
  1505. /**
  1506. * Emit a `component` node for an HOC-wrapped React component declaration (see
  1507. * reactComponentHoc). Named by the declarator (`Button`) and located at it so
  1508. * the node range spans the body. When the wrapper has an inline render
  1509. * function, its body is walked so the component's callees (hooks, helpers) are
  1510. * captured under the component node — matching how a plain
  1511. * `const Foo = () => …` arrow component already behaves.
  1512. */
  1513. private extractReactComponentNode(
  1514. name: string,
  1515. declarator: SyntaxNode,
  1516. innerFn: SyntaxNode | null,
  1517. extra: { docstring?: string; signature?: string; isExported?: boolean }
  1518. ): void {
  1519. const compNode = this.createNode('component', name, declarator, extra);
  1520. if (!compNode || !innerFn || !this.extractor) return;
  1521. this.nodeStack.push(compNode.id);
  1522. const body = this.extractor.resolveBody?.(innerFn, this.extractor.bodyField)
  1523. ?? getChildByField(innerFn, this.extractor.bodyField);
  1524. if (body) this.visitFunctionBody(body, compNode.id);
  1525. this.nodeStack.pop();
  1526. }
  1527. /**
  1528. * Extract a class
  1529. */
  1530. private extractClass(node: SyntaxNode, kind: NodeKind = 'class'): void {
  1531. if (!this.extractor) return;
  1532. // Skip forward declarations / elaborated type references (`class Foo;`) in
  1533. // languages that opt in — bodiless there means "not a definition", so it
  1534. // would otherwise mint a phantom node competing with the real definition
  1535. // (#1093). Languages where a bodiless class is complete (Kotlin, Scala)
  1536. // leave the flag unset. Resolved once here and reused for the body walk.
  1537. const resolvedBody = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1538. ?? getChildByField(node, this.extractor.bodyField);
  1539. if (this.extractor.skipBodilessClass && !resolvedBody) return;
  1540. const name = extractName(node, this.source, this.extractor);
  1541. const docstring = getPrecedingDocstring(node, this.source);
  1542. const visibility = this.extractor.getVisibility?.(node);
  1543. const isExported = this.extractor.isExported?.(node, this.source);
  1544. const classNode = this.createNode(kind, name, node, {
  1545. docstring,
  1546. visibility,
  1547. isExported,
  1548. });
  1549. if (!classNode) return;
  1550. // Extract extends/implements
  1551. this.extractInheritance(node, classNode.id);
  1552. // C# primary-constructor parameter dependencies (`class Svc(IRepo r, …)`).
  1553. this.extractCsharpPrimaryCtorParamRefs(node, classNode.id);
  1554. // Extract decorators applied to the class (`@Foo class X {}`).
  1555. this.extractDecoratorsFor(node, classNode.id);
  1556. // Push to stack and visit body
  1557. this.nodeStack.push(classNode.id);
  1558. const body = resolvedBody ?? node;
  1559. // Visit all children for methods and properties
  1560. for (let i = 0; i < body.namedChildCount; i++) {
  1561. const child = body.namedChild(i);
  1562. if (child) {
  1563. this.visitNode(child);
  1564. }
  1565. }
  1566. // Synthesize compile-time-generated members (Lombok accessors, #912). Runs
  1567. // after the body so the hook can dedup against hand-written members, and
  1568. // while the class is still on the stack so containment/QNs attach.
  1569. if (this.extractor.synthesizeMembers) {
  1570. this.extractor.synthesizeMembers(node, this.makeExtractorContext());
  1571. }
  1572. this.nodeStack.pop();
  1573. }
  1574. /**
  1575. * Extract a method
  1576. */
  1577. private extractMethod(node: SyntaxNode): void {
  1578. if (!this.extractor) return;
  1579. // For languages with receiver types (Go, Rust), include receiver in qualified name
  1580. // so FTS can match "scrapeLoop.run" → qualified_name "...::scrapeLoop::run"
  1581. const receiverType = this.extractor.getReceiverType?.(node, this.source);
  1582. // For most languages, only extract as method if inside a class-like node
  1583. // Languages with methodsAreTopLevel (e.g. Go) always treat them as methods
  1584. // Languages with getReceiverType (e.g. Rust) extract as method when receiver is found
  1585. if (!this.isInsideClassLikeNode() && !this.extractor.methodsAreTopLevel && !receiverType) {
  1586. // Skip method_definition nodes inside object literals (getters/setters/methods
  1587. // in inline objects). These are ephemeral and create noise (e.g., Svelte context
  1588. // objects: `ctx.set({ get view() { ... } })`).
  1589. if (node.parent?.type === 'object' || node.parent?.type === 'object_expression') {
  1590. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1591. ?? getChildByField(node, this.extractor.bodyField);
  1592. if (body) {
  1593. this.visitFunctionBody(body, '');
  1594. }
  1595. return;
  1596. }
  1597. // Not inside a class-like node and no receiver type, treat as function
  1598. this.extractFunction(node);
  1599. return;
  1600. }
  1601. const name = extractName(node, this.source, this.extractor);
  1602. // Check for misparse artifacts (e.g. C++ "switch" inside macro-confused class body)
  1603. if (this.extractor.isMisparsedFunction?.(name, node)) {
  1604. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1605. ?? getChildByField(node, this.extractor.bodyField);
  1606. if (body) {
  1607. this.visitFunctionBody(body, '');
  1608. }
  1609. return;
  1610. }
  1611. const docstring = getPrecedingDocstring(node, this.source);
  1612. const signature = this.extractor.getSignature?.(node, this.source);
  1613. const visibility = this.extractor.getVisibility?.(node);
  1614. const isAsync = this.extractor.isAsync?.(node);
  1615. const isStatic = this.extractor.isStatic?.(node);
  1616. const returnType = this.extractor.getReturnType?.(node, this.source);
  1617. const extraProps: Partial<Node> = {
  1618. docstring,
  1619. signature,
  1620. visibility,
  1621. isAsync,
  1622. isStatic,
  1623. returnType,
  1624. };
  1625. if (receiverType) {
  1626. extraProps.qualifiedName = `${receiverType}::${name}`;
  1627. }
  1628. const methodNode = this.createNode('method', name, node, extraProps);
  1629. if (!methodNode) return;
  1630. // For methods with a receiver type but no class-like parent on the stack
  1631. // (e.g., Rust impl blocks), add a contains edge from the owning struct/trait
  1632. if (receiverType && !this.isInsideClassLikeNode()) {
  1633. const ownerNode = this.nodes.find(
  1634. (n) =>
  1635. n.name === receiverType &&
  1636. n.filePath === this.filePath &&
  1637. (n.kind === 'struct' || n.kind === 'class' || n.kind === 'enum' || n.kind === 'trait')
  1638. );
  1639. if (ownerNode) {
  1640. this.edges.push({
  1641. source: ownerNode.id,
  1642. target: methodNode.id,
  1643. kind: 'contains',
  1644. });
  1645. }
  1646. }
  1647. // Extract type annotations (parameter types and return type)
  1648. this.extractTypeAnnotations(node, methodNode.id);
  1649. // Extract decorators (`@Get('/list') list() {}`).
  1650. this.extractDecoratorsFor(node, methodNode.id);
  1651. // Push to stack and visit body
  1652. this.nodeStack.push(methodNode.id);
  1653. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1654. ?? getChildByField(node, this.extractor.bodyField);
  1655. if (body) {
  1656. this.visitFunctionBody(body, methodNode.id);
  1657. }
  1658. this.nodeStack.pop();
  1659. }
  1660. /**
  1661. * Extract an interface/protocol/trait
  1662. */
  1663. private extractInterface(node: SyntaxNode): void {
  1664. if (!this.extractor) return;
  1665. const name = extractName(node, this.source, this.extractor);
  1666. const docstring = getPrecedingDocstring(node, this.source);
  1667. const isExported = this.extractor.isExported?.(node, this.source);
  1668. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  1669. const interfaceNode = this.createNode(kind, name, node, {
  1670. docstring,
  1671. isExported,
  1672. });
  1673. if (!interfaceNode) return;
  1674. // Extract extends (interface inheritance)
  1675. this.extractInheritance(node, interfaceNode.id);
  1676. // Visit body children for interface methods and nested types
  1677. this.nodeStack.push(interfaceNode.id);
  1678. let body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1679. ?? getChildByField(node, this.extractor.bodyField);
  1680. if (!body) body = node;
  1681. for (let i = 0; i < body.namedChildCount; i++) {
  1682. const child = body.namedChild(i);
  1683. if (child) {
  1684. this.visitNode(child);
  1685. }
  1686. }
  1687. this.nodeStack.pop();
  1688. }
  1689. /**
  1690. * Extract a struct
  1691. */
  1692. private extractStruct(node: SyntaxNode): void {
  1693. if (!this.extractor) return;
  1694. // Skip forward declarations and type references (no body = not a definition)
  1695. // — EXCEPT C# positional records (`record struct M(decimal Amount);`),
  1696. // complete definitions with no body block. (#831)
  1697. const body = getChildByField(node, this.extractor.bodyField);
  1698. if (!body && node.type !== 'record_declaration') return;
  1699. const name = extractName(node, this.source, this.extractor);
  1700. const docstring = getPrecedingDocstring(node, this.source);
  1701. const visibility = this.extractor.getVisibility?.(node);
  1702. const isExported = this.extractor.isExported?.(node, this.source);
  1703. const structNode = this.createNode('struct', name, node, {
  1704. docstring,
  1705. visibility,
  1706. isExported,
  1707. });
  1708. if (!structNode) return;
  1709. // Extract inheritance (e.g. Swift: struct HTTPMethod: RawRepresentable)
  1710. this.extractInheritance(node, structNode.id);
  1711. // C# primary-constructor parameter dependencies (`struct P(int x)`, and
  1712. // `record struct M(decimal Amount)` which the grammar nests here).
  1713. this.extractCsharpPrimaryCtorParamRefs(node, structNode.id);
  1714. // Push to stack for field extraction (bodiless positional records have
  1715. // no members to visit)
  1716. if (body) {
  1717. this.nodeStack.push(structNode.id);
  1718. for (let i = 0; i < body.namedChildCount; i++) {
  1719. const child = body.namedChild(i);
  1720. if (child) {
  1721. this.visitNode(child);
  1722. }
  1723. }
  1724. this.nodeStack.pop();
  1725. }
  1726. }
  1727. /**
  1728. * Extract an enum
  1729. */
  1730. private extractEnum(node: SyntaxNode): void {
  1731. if (!this.extractor) return;
  1732. // Skip forward declarations and type references (no body = not a definition)
  1733. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  1734. ?? getChildByField(node, this.extractor.bodyField);
  1735. if (!body) return;
  1736. const name = extractName(node, this.source, this.extractor);
  1737. const docstring = getPrecedingDocstring(node, this.source);
  1738. const visibility = this.extractor.getVisibility?.(node);
  1739. const isExported = this.extractor.isExported?.(node, this.source);
  1740. const enumNode = this.createNode('enum', name, node, {
  1741. docstring,
  1742. visibility,
  1743. isExported,
  1744. });
  1745. if (!enumNode) return;
  1746. // Extract inheritance (e.g. Swift: enum AFError: Error)
  1747. this.extractInheritance(node, enumNode.id);
  1748. // Push to stack and visit body children (enum members, nested types, methods)
  1749. this.nodeStack.push(enumNode.id);
  1750. const memberTypes = this.extractor.enumMemberTypes;
  1751. for (let i = 0; i < body.namedChildCount; i++) {
  1752. const child = body.namedChild(i);
  1753. if (!child) continue;
  1754. if (memberTypes?.includes(child.type)) {
  1755. this.extractEnumMembers(child);
  1756. } else {
  1757. this.visitNode(child);
  1758. }
  1759. }
  1760. this.nodeStack.pop();
  1761. }
  1762. /**
  1763. * Extract enum member names from an enum member node.
  1764. * Handles multi-case declarations (Swift: `case put, delete`) and single-case patterns.
  1765. */
  1766. private extractEnumMembers(node: SyntaxNode): void {
  1767. // Try field-based name first (e.g. Rust enum_variant has a 'name' field)
  1768. const nameNode = getChildByField(node, 'name');
  1769. if (nameNode) {
  1770. this.createNode('enum_member', getNodeText(nameNode, this.source), node);
  1771. return;
  1772. }
  1773. // Check for identifier-like children (Swift: simple_identifier, TS: property_identifier)
  1774. let found = false;
  1775. for (let i = 0; i < node.namedChildCount; i++) {
  1776. const child = node.namedChild(i);
  1777. if (child && (child.type === 'simple_identifier' || child.type === 'identifier' || child.type === 'property_identifier')) {
  1778. this.createNode('enum_member', getNodeText(child, this.source), child);
  1779. found = true;
  1780. }
  1781. }
  1782. // If the node itself IS the identifier (e.g. TS property_identifier directly in enum body)
  1783. if (!found && node.namedChildCount === 0) {
  1784. this.createNode('enum_member', getNodeText(node, this.source), node);
  1785. }
  1786. }
  1787. /**
  1788. * Extract a class property declaration (e.g. C# `public string Name { get; set; }`).
  1789. * Extracts as 'property' kind node inside the owning class.
  1790. */
  1791. private extractProperty(node: SyntaxNode): Node | null {
  1792. if (!this.extractor) return null;
  1793. const docstring = getPrecedingDocstring(node, this.source);
  1794. const visibility = this.extractor.getVisibility?.(node);
  1795. const isStatic = this.extractor.isStatic?.(node) ?? false;
  1796. const hookName = this.extractor.extractPropertyName?.(node, this.source);
  1797. // JS `field_definition` names its key the `property` field (TS uses
  1798. // `name`) — try both before the generic identifier scan (#808).
  1799. const nameNode = hookName
  1800. ? null
  1801. : getChildByField(node, 'name') ||
  1802. getChildByField(node, 'property') ||
  1803. node.namedChildren.find(c => c.type === 'identifier');
  1804. const name = hookName ?? (nameNode ? getNodeText(nameNode, this.source) : null);
  1805. if (!name) return null;
  1806. // Get property type. TS/JS field definitions carry an explicit `type`
  1807. // field (a `type_annotation`); their other named children are the name
  1808. // and the initializer VALUE, which the generic finder below would
  1809. // wrongly pick — so fields use the type field only (#808). Other
  1810. // languages (C# property_declaration) keep the generic scan.
  1811. const isTsJsField =
  1812. node.type === 'public_field_definition' || node.type === 'field_definition';
  1813. const typeNode = isTsJsField
  1814. ? getChildByField(node, 'type')
  1815. : node.namedChildren.find(
  1816. c => c.type !== 'modifier' && c.type !== 'modifiers'
  1817. && c.type !== 'identifier' && c.type !== 'accessor_list'
  1818. && c.type !== 'accessors' && c.type !== 'equals_value_clause'
  1819. );
  1820. const typeText = typeNode
  1821. ? getNodeText(typeNode, this.source).replace(/^:\s*/, '')
  1822. : undefined;
  1823. const signature = typeText ? `${typeText} ${name}` : name;
  1824. const propNode = this.createNode('property', name, node, {
  1825. docstring,
  1826. signature,
  1827. visibility,
  1828. isStatic,
  1829. });
  1830. // `@Inject() private svc: Foo` and similar — capture the
  1831. // decorator->target relationship for class properties too.
  1832. if (propNode) {
  1833. this.extractDecoratorsFor(node, propNode.id);
  1834. // Emit `references` edges from the property to types named in its
  1835. // type annotation (#381). The generic walker handles TS-style
  1836. // `type_annotation` children; the C# branch walks the `type` field.
  1837. this.extractTypeAnnotations(node, propNode.id);
  1838. }
  1839. return propNode;
  1840. }
  1841. /**
  1842. * Extract a class field declaration (e.g. Java field_declaration, C# field_declaration).
  1843. * Extracts each declarator as a 'field' kind node inside the owning class.
  1844. */
  1845. private extractField(node: SyntaxNode): void {
  1846. if (!this.extractor) return;
  1847. const docstring = getPrecedingDocstring(node, this.source);
  1848. const visibility = this.extractor.getVisibility?.(node);
  1849. const isStatic = this.extractor.isStatic?.(node) ?? false;
  1850. // A class field that is actually a CONSTANT (Java `static final`, C# `const`
  1851. // / `static readonly`) is extracted as `constant` kind, not `field`, so
  1852. // value-reference edges treat it as a target (the gate accepts
  1853. // constant/variable, not field). Scoped to languages whose `isConst`
  1854. // predicate is field-shaped — other languages' fields stay `field`.
  1855. const fieldKind: NodeKind =
  1856. (this.language === 'java' || this.language === 'csharp') &&
  1857. (this.extractor.isConst?.(node) ?? false)
  1858. ? 'constant'
  1859. : 'field';
  1860. // Java field_declaration: "private final String name = value;" → variable_declarator(s) are direct children
  1861. // C# field_declaration: wraps in variable_declaration → variable_declarator(s)
  1862. let declarators = node.namedChildren.filter(
  1863. c => c.type === 'variable_declarator'
  1864. );
  1865. // C#: look inside variable_declaration wrapper
  1866. if (declarators.length === 0) {
  1867. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  1868. if (varDecl) {
  1869. declarators = varDecl.namedChildren.filter(c => c.type === 'variable_declarator');
  1870. }
  1871. }
  1872. // PHP property_declaration: property_element → variable_name → name
  1873. if (declarators.length === 0) {
  1874. const propElements = node.namedChildren.filter(c => c.type === 'property_element');
  1875. if (propElements.length > 0) {
  1876. // Get type annotation if present (e.g. "string", "int", "?Foo")
  1877. const typeNode = node.namedChildren.find(
  1878. c => c.type !== 'visibility_modifier' && c.type !== 'static_modifier'
  1879. && c.type !== 'readonly_modifier' && c.type !== 'property_element'
  1880. && c.type !== 'var_modifier'
  1881. );
  1882. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  1883. for (const elem of propElements) {
  1884. const varName = elem.namedChildren.find(c => c.type === 'variable_name');
  1885. const nameNode = varName?.namedChildren.find(c => c.type === 'name');
  1886. if (!nameNode) continue;
  1887. const name = getNodeText(nameNode, this.source);
  1888. const signature = typeText ? `${typeText} $${name}` : `$${name}`;
  1889. this.createNode('field', name, elem, {
  1890. docstring,
  1891. signature,
  1892. visibility,
  1893. isStatic,
  1894. });
  1895. }
  1896. return;
  1897. }
  1898. }
  1899. if (declarators.length > 0) {
  1900. // Get field type from the type child
  1901. // Java: type is a direct child of field_declaration
  1902. // C#: type is inside variable_declaration wrapper
  1903. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  1904. const typeSearchNode = varDecl ?? node;
  1905. const typeNode = typeSearchNode.namedChildren.find(
  1906. c => c.type !== 'modifiers' && c.type !== 'modifier' && c.type !== 'variable_declarator'
  1907. && c.type !== 'variable_declaration' && c.type !== 'marker_annotation' && c.type !== 'annotation'
  1908. );
  1909. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  1910. for (const decl of declarators) {
  1911. const nameNode = getChildByField(decl, 'name')
  1912. || decl.namedChildren.find(c => c.type === 'identifier');
  1913. if (!nameNode) continue;
  1914. const name = getNodeText(nameNode, this.source);
  1915. const signature = typeText ? `${typeText} ${name}` : name;
  1916. const fieldNode = this.createNode(fieldKind, name, decl, {
  1917. docstring,
  1918. signature,
  1919. visibility,
  1920. isStatic,
  1921. });
  1922. // Java/Kotlin annotations / TS field decorators sit on the
  1923. // outer field_declaration, not on the individual declarator.
  1924. if (fieldNode) {
  1925. this.extractDecoratorsFor(node, fieldNode.id);
  1926. // Same as properties: emit `references` to the field's annotated
  1927. // type. The outer `field_declaration` is the right scope to
  1928. // search from — C# carries the `type` inside `variable_declaration`
  1929. // and the language-aware path in `extractTypeAnnotations` descends
  1930. // into that wrapper (#381).
  1931. this.extractTypeAnnotations(node, fieldNode.id);
  1932. }
  1933. }
  1934. } else {
  1935. // Fallback: try to find an identifier child directly
  1936. const nameNode = getChildByField(node, 'name')
  1937. || node.namedChildren.find(c => c.type === 'identifier');
  1938. if (nameNode) {
  1939. const name = getNodeText(nameNode, this.source);
  1940. this.createNode(fieldKind, name, node, {
  1941. docstring,
  1942. visibility,
  1943. isStatic,
  1944. });
  1945. }
  1946. }
  1947. }
  1948. /**
  1949. * Extract function-valued properties of an object literal as named function
  1950. * nodes (named by their property key). Shared by the two object-of-functions
  1951. * shapes in extractVariable: the object as a direct const value, and the
  1952. * object returned by a store-initializer call. Handles both `key: () => {}` /
  1953. * `key: function() {}` pairs and method shorthand `key() {}`.
  1954. */
  1955. private extractObjectLiteralFunctions(obj: SyntaxNode): void {
  1956. for (let i = 0; i < obj.namedChildCount; i++) {
  1957. const member = obj.namedChild(i);
  1958. if (!member) continue;
  1959. if (member.type === 'pair') {
  1960. const key = getChildByField(member, 'key');
  1961. const value = getChildByField(member, 'value');
  1962. if (key && value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
  1963. this.extractFunction(value, this.objectKeyName(key));
  1964. }
  1965. } else if (member.type === 'method_definition') {
  1966. // Method shorthand: `{ fetchUser() {...} }`. extractMethod deliberately
  1967. // skips object-literal methods, so route through extractFunction with an
  1968. // explicit name (method_definition exposes a `body` field, so resolveBody
  1969. // falls through to it and the node spans the full method).
  1970. const key = getChildByField(member, 'name');
  1971. if (key) this.extractFunction(member, this.objectKeyName(key));
  1972. }
  1973. }
  1974. }
  1975. /** Property-key text with surrounding quotes stripped (`'foo'` → `foo`). */
  1976. private objectKeyName(key: SyntaxNode): string {
  1977. return getNodeText(key, this.source).replace(/^['"`]|['"`]$/g, '');
  1978. }
  1979. /**
  1980. * Given a `call_expression` initializer (`create((set, get) => ({...}))`),
  1981. * find the object literal RETURNED by a function argument — descending through
  1982. * nested call_expression arguments so middleware wrappers are unwrapped
  1983. * (`create(persist((set, get) => ({...}), {...}))`, devtools, immer,
  1984. * subscribeWithSelector). Returns null when no such object is found — the
  1985. * common case for ordinary call initializers — so this stays cheap and silent
  1986. * rather than guessing. Keyed purely on AST shape; no library names.
  1987. */
  1988. private findInitializerReturnedObject(callNode: SyntaxNode, depth = 0): SyntaxNode | null {
  1989. if (depth > 4) return null;
  1990. const args = getChildByField(callNode, 'arguments');
  1991. if (!args) return null;
  1992. for (let i = 0; i < args.namedChildCount; i++) {
  1993. const arg = args.namedChild(i);
  1994. if (!arg) continue;
  1995. if (arg.type === 'arrow_function' || arg.type === 'function_expression') {
  1996. const obj = this.functionReturnedObject(arg);
  1997. if (obj) return obj;
  1998. } else if (arg.type === 'call_expression') {
  1999. const obj = this.findInitializerReturnedObject(arg, depth + 1);
  2000. if (obj) return obj;
  2001. }
  2002. }
  2003. return null;
  2004. }
  2005. /**
  2006. * The object literal a function expression returns — either the `=> ({...})`
  2007. * arrow form (a parenthesized_expression wrapping an object) or a
  2008. * `=> { return {...} }` block. Returns null for any other body shape.
  2009. */
  2010. private functionReturnedObject(fnNode: SyntaxNode): SyntaxNode | null {
  2011. const body = getChildByField(fnNode, 'body');
  2012. if (!body) return null;
  2013. const asObject = (n: SyntaxNode | null): SyntaxNode | null => {
  2014. if (!n) return null;
  2015. if (n.type === 'object' || n.type === 'object_expression') return n;
  2016. if (n.type === 'parenthesized_expression') {
  2017. for (let i = 0; i < n.namedChildCount; i++) {
  2018. const inner = asObject(n.namedChild(i));
  2019. if (inner) return inner;
  2020. }
  2021. }
  2022. return null;
  2023. };
  2024. // `(set, get) => ({...})` — body is the (parenthesized) object directly.
  2025. const direct = asObject(body);
  2026. if (direct) return direct;
  2027. // `(set, get) => { return {...} }` — scan top-level return statements.
  2028. if (body.type === 'statement_block') {
  2029. for (let i = 0; i < body.namedChildCount; i++) {
  2030. const stmt = body.namedChild(i);
  2031. if (stmt?.type !== 'return_statement') continue;
  2032. for (let j = 0; j < stmt.namedChildCount; j++) {
  2033. const obj = asObject(stmt.namedChild(j));
  2034. if (obj) return obj;
  2035. }
  2036. }
  2037. }
  2038. return null;
  2039. }
  2040. /**
  2041. * RTK Query: from a `createApi({ ..., endpoints: build => ({...}) })` or a
  2042. * `baseApi.injectEndpoints({ endpoints: build => ({...}) })` call initializer,
  2043. * return the object literal of endpoint definitions (the object the `endpoints`
  2044. * arrow returns). Returns null for any other call — the common case — so this
  2045. * stays cheap and silent. Keyed on the RTK entry-point names (`createApi` /
  2046. * `injectEndpoints`) like the framework extractors key on their library APIs.
  2047. */
  2048. private findRtkEndpointsObject(callNode: SyntaxNode): SyntaxNode | null {
  2049. const callee = getChildByField(callNode, 'function');
  2050. if (!callee) return null;
  2051. const calleeName =
  2052. callee.type === 'identifier'
  2053. ? getNodeText(callee, this.source)
  2054. : callee.type === 'member_expression'
  2055. ? getNodeText(getChildByField(callee, 'property') ?? callee, this.source)
  2056. : '';
  2057. if (calleeName !== 'createApi' && calleeName !== 'injectEndpoints') return null;
  2058. const args = getChildByField(callNode, 'arguments');
  2059. if (!args) return null;
  2060. for (let i = 0; i < args.namedChildCount; i++) {
  2061. const arg = args.namedChild(i);
  2062. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2063. for (let j = 0; j < arg.namedChildCount; j++) {
  2064. const member = arg.namedChild(j);
  2065. // Two equally-common spellings: `endpoints: build => ({...})` (pair with an
  2066. // arrow value) and `endpoints(build) { return {...} }` (method shorthand).
  2067. if (member?.type === 'pair') {
  2068. const key = getChildByField(member, 'key');
  2069. if (!key || getNodeText(key, this.source) !== 'endpoints') continue;
  2070. const value = getChildByField(member, 'value');
  2071. if (value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
  2072. return this.functionReturnedObject(value);
  2073. }
  2074. } else if (member?.type === 'method_definition') {
  2075. const key = getChildByField(member, 'name');
  2076. if (!key || getNodeText(key, this.source) !== 'endpoints') continue;
  2077. return this.functionReturnedObject(member);
  2078. }
  2079. }
  2080. }
  2081. return null;
  2082. }
  2083. /**
  2084. * Extract each RTK Query endpoint (`getX: build.query({...})` / `build.mutation`)
  2085. * as a function node named by the endpoint key, spanning its primary handler
  2086. * (the `queryFn`/`query` arrow) so the fetch logic's calls attribute to the
  2087. * endpoint. Without this an endpoint exists only as an object-literal property —
  2088. * never a node — so the generated `useXQuery` hook can't be bridged to it.
  2089. */
  2090. private extractRtkEndpoints(obj: SyntaxNode): void {
  2091. for (let i = 0; i < obj.namedChildCount; i++) {
  2092. const member = obj.namedChild(i);
  2093. if (member?.type !== 'pair') continue;
  2094. const key = getChildByField(member, 'key');
  2095. const value = getChildByField(member, 'value');
  2096. if (!key || value?.type !== 'call_expression') continue;
  2097. // The value must be a builder dispatch `<builder>.query|mutation(...)`.
  2098. const callee = getChildByField(value, 'function');
  2099. if (callee?.type !== 'member_expression') continue;
  2100. const method = getNodeText(getChildByField(callee, 'property') ?? callee, this.source);
  2101. if (method !== 'query' && method !== 'mutation' && method !== 'infiniteQuery') continue;
  2102. const handler = this.rtkEndpointHandler(value);
  2103. if (handler) {
  2104. this.extractFunction(handler, this.objectKeyName(key));
  2105. } else {
  2106. // Factory / config-only handler (`queryFn: makeQueryFn(url)`): no function
  2107. // literal to name. Mint a bare endpoint node spanning the builder call so
  2108. // the generated hook still bridges to it, and walk the call so its handler
  2109. // factory (and any inline transform) is captured as an outgoing edge.
  2110. const epNode = this.createNode('function', this.objectKeyName(key), value, {
  2111. signature: getNodeText(value, this.source).slice(0, 80),
  2112. });
  2113. if (epNode) {
  2114. this.nodeStack.push(epNode.id);
  2115. this.visitFunctionBody(value, epNode.id);
  2116. this.nodeStack.pop();
  2117. }
  2118. }
  2119. }
  2120. }
  2121. /**
  2122. * The primary handler arrow of a `build.query({ queryFn|query: (…) => … })`
  2123. * endpoint — prefers `queryFn`, then `query`, else the first function-valued
  2124. * property. Returns null when the endpoint is config-only (no handler arrow).
  2125. */
  2126. private rtkEndpointHandler(callNode: SyntaxNode): SyntaxNode | null {
  2127. const args = getChildByField(callNode, 'arguments');
  2128. if (!args) return null;
  2129. for (let i = 0; i < args.namedChildCount; i++) {
  2130. const arg = args.namedChild(i);
  2131. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2132. let queryFn: SyntaxNode | null = null;
  2133. let query: SyntaxNode | null = null;
  2134. let firstFn: SyntaxNode | null = null;
  2135. for (let j = 0; j < arg.namedChildCount; j++) {
  2136. const member = arg.namedChild(j);
  2137. // The handler may be `queryFn: () => …` / `query: () => …` (pair) or the
  2138. // method-shorthand `query(arg) { … }` / `queryFn(arg) { … }`.
  2139. let fn: SyntaxNode | null = null;
  2140. let kn = '';
  2141. if (member?.type === 'pair') {
  2142. const v = getChildByField(member, 'value');
  2143. if (v?.type === 'arrow_function' || v?.type === 'function_expression') {
  2144. fn = v;
  2145. const k = getChildByField(member, 'key');
  2146. kn = k ? getNodeText(k, this.source) : '';
  2147. }
  2148. } else if (member?.type === 'method_definition') {
  2149. fn = member;
  2150. const k = getChildByField(member, 'name');
  2151. kn = k ? getNodeText(k, this.source) : '';
  2152. }
  2153. if (!fn) continue;
  2154. if (kn === 'queryFn') queryFn = fn;
  2155. else if (kn === 'query') query = fn;
  2156. if (!firstFn) firstFn = fn;
  2157. }
  2158. if (queryFn) return queryFn;
  2159. if (query) return query;
  2160. if (firstFn) return firstFn;
  2161. }
  2162. return null;
  2163. }
  2164. /**
  2165. * RTK Query generated-hook bindings. `export const { useGetXQuery,
  2166. * useUpdateYMutation } = someApi` destructures the hooks RTK generates per
  2167. * endpoint off a createApi result. They are real exported symbols that
  2168. * components import, but destructured bindings aren't otherwise extracted —
  2169. * mint a function node per binding matching the RTK hook convention so the hook
  2170. * resolves and the synthesizer can bridge it to its endpoint. Gated tight by the
  2171. * caller (object-pattern off a bare identifier) + the name convention here, so
  2172. * ordinary destructures stay unextracted.
  2173. */
  2174. private extractRtkHookBindings(pattern: SyntaxNode, isExported: boolean): void {
  2175. for (let i = 0; i < pattern.namedChildCount; i++) {
  2176. const binding = pattern.namedChild(i);
  2177. if (binding?.type !== 'shorthand_property_identifier_pattern') continue;
  2178. const name = getNodeText(binding, this.source);
  2179. if (!RTK_HOOK_NAME_RE.test(name)) continue;
  2180. this.createNode('function', name, binding, {
  2181. isExported,
  2182. signature: '= RTK Query generated hook',
  2183. });
  2184. }
  2185. }
  2186. /** Cheap per-file heuristic: the file carries ≥2 distinct Vue-store signals
  2187. * (defineStore/createStore/Vuex, or the actions/mutations/getters/namespaced
  2188. * vocabulary). Gates the non-exported `const actions = {…}` Vuex-module form so
  2189. * a stray `const actions` in unrelated code is never mistaken for a store. */
  2190. private looksLikeVueStoreFile(): boolean {
  2191. if (this.vueStoreFile !== null) return this.vueStoreFile;
  2192. const seen = new Set<string>();
  2193. VUE_STORE_FILE_SIGNAL.lastIndex = 0;
  2194. let m: RegExpExecArray | null;
  2195. while ((m = VUE_STORE_FILE_SIGNAL.exec(this.source))) {
  2196. seen.add(m[0]);
  2197. if (seen.size >= 2) break;
  2198. }
  2199. this.vueStoreFile = seen.size >= 2;
  2200. return this.vueStoreFile;
  2201. }
  2202. /** True if an object literal has ≥1 inline function member (`key: () => …` /
  2203. * `method(){}`) — distinguishes an inline action map (zustand/SvelteKit form
  2204. * actions) from a Pinia SETUP store's all-shorthand `return { foo, bar }`
  2205. * (whose functions are body-local consts, walked normally instead). */
  2206. private objectHasInlineFunctions(obj: SyntaxNode): boolean {
  2207. for (let i = 0; i < obj.namedChildCount; i++) {
  2208. const member = obj.namedChild(i);
  2209. if (member?.type === 'method_definition') return true;
  2210. if (member?.type === 'pair') {
  2211. const v = getChildByField(member, 'value');
  2212. if (v?.type === 'arrow_function' || v?.type === 'function_expression') return true;
  2213. }
  2214. }
  2215. return false;
  2216. }
  2217. /** Vue store action/mutation/getter collections defined INLINE in a store call:
  2218. * `defineStore({ actions: {…}, getters: {…} })` (Pinia options form),
  2219. * `defineStore('id', { actions: {…} })`, `createStore({ mutations: {…} })`,
  2220. * `new Vuex.Store({ actions: {…} })`. Returns the object literals under those
  2221. * keys so their methods become nodes. Gated on the store-factory callee. */
  2222. private findVueStoreCollectionObjects(callNode: SyntaxNode): SyntaxNode[] {
  2223. const callee = getChildByField(callNode, 'function') ?? getChildByField(callNode, 'constructor');
  2224. if (!callee) return [];
  2225. const calleeName =
  2226. callee.type === 'identifier'
  2227. ? getNodeText(callee, this.source)
  2228. : callee.type === 'member_expression'
  2229. ? getNodeText(getChildByField(callee, 'property') ?? callee, this.source)
  2230. : '';
  2231. if (!VUE_STORE_FACTORY_CALLEES.has(calleeName) && calleeName !== 'Store') return [];
  2232. const args = getChildByField(callNode, 'arguments');
  2233. if (!args) return [];
  2234. const objects: SyntaxNode[] = [];
  2235. for (let i = 0; i < args.namedChildCount; i++) {
  2236. const arg = args.namedChild(i);
  2237. if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue;
  2238. for (let j = 0; j < arg.namedChildCount; j++) {
  2239. const member = arg.namedChild(j);
  2240. if (member?.type !== 'pair') continue;
  2241. const key = getChildByField(member, 'key');
  2242. if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue;
  2243. const value = getChildByField(member, 'value');
  2244. if (value && (value.type === 'object' || value.type === 'object_expression')) {
  2245. objects.push(value);
  2246. }
  2247. }
  2248. }
  2249. return objects;
  2250. }
  2251. /** Extract the methods of a store-config object's `actions`/`mutations`/`getters`
  2252. * properties. Used for the canonical Vuex MODULE shape `export default {
  2253. * namespaced, actions: {…}, mutations: {…} }` — object-literal methods aren't
  2254. * otherwise extracted, so the actions/mutations would never be nodes. */
  2255. private extractStoreCollectionMethods(configObj: SyntaxNode): void {
  2256. for (let j = 0; j < configObj.namedChildCount; j++) {
  2257. const member = configObj.namedChild(j);
  2258. if (member?.type !== 'pair') continue;
  2259. const key = getChildByField(member, 'key');
  2260. if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue;
  2261. const value = getChildByField(member, 'value');
  2262. if (value && (value.type === 'object' || value.type === 'object_expression')) {
  2263. this.extractObjectLiteralFunctions(value);
  2264. }
  2265. }
  2266. }
  2267. /** The SETUP function of a Pinia setup store (`defineStore('id', () => {…})`)
  2268. * — an arrow/function arg with a block body. Returns null for the options form
  2269. * (`defineStore({…})`) and for any non-defineStore call. The setup body's local
  2270. * function consts are the store's actions; the generic body walk doesn't reach
  2271. * them (nested functions are separate scopes), so they're extracted explicitly. */
  2272. private findPiniaSetupFn(callNode: SyntaxNode): SyntaxNode | null {
  2273. const callee = getChildByField(callNode, 'function');
  2274. if (!callee || callee.type !== 'identifier' || getNodeText(callee, this.source) !== 'defineStore') return null;
  2275. const args = getChildByField(callNode, 'arguments');
  2276. if (!args) return null;
  2277. for (let i = 0; i < args.namedChildCount; i++) {
  2278. const arg = args.namedChild(i);
  2279. if (arg?.type !== 'arrow_function' && arg?.type !== 'function_expression') continue;
  2280. const body = getChildByField(arg, 'body');
  2281. if (body?.type === 'statement_block') return arg; // block body ⇒ setup form
  2282. }
  2283. return null;
  2284. }
  2285. /** Extract a Pinia setup store's actions: the body-local `const foo = () => …`
  2286. * / `function foo(){}` declarations, named by the binding. (State refs and other
  2287. * consts are left to the normal value-extraction; only the functions matter as
  2288. * the store's callable surface.) */
  2289. private extractPiniaSetupBody(setupFn: SyntaxNode): void {
  2290. const body = getChildByField(setupFn, 'body');
  2291. if (!body || body.type !== 'statement_block') return;
  2292. for (let i = 0; i < body.namedChildCount; i++) {
  2293. const stmt = body.namedChild(i);
  2294. if (!stmt) continue;
  2295. if (stmt.type === 'function_declaration') {
  2296. this.extractFunction(stmt);
  2297. } else if (this.extractor!.variableTypes.includes(stmt.type)) {
  2298. for (let j = 0; j < stmt.namedChildCount; j++) {
  2299. const decl = stmt.namedChild(j);
  2300. if (decl?.type !== 'variable_declarator') continue;
  2301. const v = getChildByField(decl, 'value');
  2302. if (v?.type === 'arrow_function' || v?.type === 'function_expression') {
  2303. this.extractFunction(v); // name resolved from the parent declarator
  2304. }
  2305. }
  2306. }
  2307. }
  2308. }
  2309. /**
  2310. * Extract a variable declaration (const, let, var, etc.)
  2311. *
  2312. * Extracts top-level and module-level variable declarations.
  2313. * Captures the variable name and first 100 chars of initializer in signature for searchability.
  2314. */
  2315. private extractVariable(node: SyntaxNode): void {
  2316. if (!this.extractor) return;
  2317. // Different languages have different variable declaration structures
  2318. // TypeScript/JavaScript: lexical_declaration contains variable_declarator children
  2319. // Python: assignment has left (identifier) and right (value)
  2320. // Go: var_declaration, short_var_declaration, const_declaration
  2321. const isConst = this.extractor.isConst?.(node) ?? false;
  2322. const kind: NodeKind = isConst ? 'constant' : 'variable';
  2323. const docstring = getPrecedingDocstring(node, this.source);
  2324. const isExported = this.extractor.isExported?.(node, this.source) ?? false;
  2325. // Extract variable declarators based on language
  2326. if (this.language === 'typescript' || this.language === 'javascript' ||
  2327. this.language === 'tsx' || this.language === 'jsx' || this.language === 'cfscript' ||
  2328. this.language === 'arkts') {
  2329. // Handle lexical_declaration and variable_declaration
  2330. // These contain one or more variable_declarator children
  2331. for (let i = 0; i < node.namedChildCount; i++) {
  2332. const child = node.namedChild(i);
  2333. if (child?.type === 'variable_declarator') {
  2334. const nameNode = getChildByField(child, 'name');
  2335. const valueNode = getChildByField(child, 'value');
  2336. if (nameNode) {
  2337. // Skip destructured patterns (e.g., `let { x, y } = $props()` in Svelte)
  2338. // These produce ugly multi-line names like "{ class: className }".
  2339. // EXCEPT `export const { useGetXQuery } = someApi` — the RTK Query
  2340. // generated hooks: real exported symbols destructured off a createApi
  2341. // result. Mint a node per binding matching the hook convention (gated
  2342. // on a bare-identifier RHS so ordinary destructures stay skipped).
  2343. if (nameNode.type === 'object_pattern' || nameNode.type === 'array_pattern') {
  2344. if (nameNode.type === 'object_pattern' && valueNode?.type === 'identifier') {
  2345. this.extractRtkHookBindings(nameNode, isExported);
  2346. }
  2347. continue;
  2348. }
  2349. const name = getNodeText(nameNode, this.source);
  2350. // Arrow functions / function expressions: extract as function instead of variable
  2351. if (valueNode && (valueNode.type === 'arrow_function' || valueNode.type === 'function_expression')) {
  2352. this.extractFunction(valueNode);
  2353. continue;
  2354. }
  2355. // Capture first 100 chars of initializer for context (stored in signature for searchability)
  2356. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2357. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2358. // React HOC-wrapped components (`forwardRef`/`memo`/`styled`) — see
  2359. // reactComponentHoc. The initializer is a call / tagged-template (not
  2360. // a bare arrow), so without this the const is a plain `constant`,
  2361. // which the JSX-render synthesizer and component resolution both skip
  2362. // → `<Button/>` usages get no edge and callers/impact return empty
  2363. // (the whole shadcn/ui design-system pattern, #841). PascalCase-gated
  2364. // to the component naming convention so a memoization util
  2365. // (`const cache = memo(fn)`) stays a constant.
  2366. if (valueNode && /^[A-Z]/.test(name)) {
  2367. const hoc = this.reactComponentHoc(valueNode);
  2368. if (hoc) {
  2369. this.extractReactComponentNode(name, child, hoc.inner, {
  2370. docstring,
  2371. signature: initSignature,
  2372. isExported,
  2373. });
  2374. continue;
  2375. }
  2376. }
  2377. const varNode = this.createNode(kind, name, child, {
  2378. docstring,
  2379. signature: initSignature,
  2380. isExported,
  2381. });
  2382. // Extract type annotation references (e.g., const x: ITextModel = ...)
  2383. if (varNode) {
  2384. this.extractVariableTypeAnnotation(child, varNode.id);
  2385. }
  2386. // Exported const object-of-functions — extract each function-valued
  2387. // property as a function named by its key + walk its body so its
  2388. // calls are captured. Two shapes, both keyed on AST shape (not on any
  2389. // library name):
  2390. // `export const actions = { default: async () => {} }` — object is
  2391. // the DIRECT value (SvelteKit form actions / handler maps / route
  2392. // tables).
  2393. // `export const useStore = create((set, get) => ({ fetchUser:
  2394. // async () => {} }))` — object is RETURNED by an initializer call,
  2395. // possibly through middleware wrappers (persist/devtools/immer).
  2396. // Covers Zustand/Redux/Pinia/MobX stores generically. Without
  2397. // this, store actions exist only as object-literal properties —
  2398. // never nodes — so `node`/`callers` on `fetchUser` return "not
  2399. // found" and the agent Reads the store to reconstruct the flow.
  2400. // Scoped to EXPORTED consts to exclude inline-object noise
  2401. // (`ctx.set({...})`) the object-method skip deliberately avoids.
  2402. const objectOfFns =
  2403. valueNode && (valueNode.type === 'object' || valueNode.type === 'object_expression')
  2404. ? valueNode
  2405. : valueNode?.type === 'call_expression'
  2406. ? this.findInitializerReturnedObject(valueNode)
  2407. : null;
  2408. // Only treat as an inline object-of-functions when the object actually
  2409. // HAS inline functions. A Pinia SETUP store `defineStore('id', () => {
  2410. // const foo = …; return { foo } })` returns an ALL-SHORTHAND object
  2411. // whose functions are body-local consts — it must fall through to a
  2412. // normal body walk (extracting those consts), not be skipped here.
  2413. const hasInlineFns = !!objectOfFns && this.objectHasInlineFunctions(objectOfFns);
  2414. const extractObjectMethods = isExported && !!objectOfFns && hasInlineFns;
  2415. // RTK Query: `createApi`/`injectEndpoints` define endpoints as
  2416. // object-literal properties whose values are `build.query/mutation(...)`
  2417. // calls — nested under an `endpoints` arrow, so neither the
  2418. // object-of-functions path above nor the normal walk extracts them.
  2419. // Extract each endpoint as a function node (named by its key), and skip
  2420. // walking the createApi call body (its handler arrows are extracted
  2421. // individually below, exactly like the store-factory case).
  2422. const rtkEndpoints =
  2423. valueNode?.type === 'call_expression' ? this.findRtkEndpointsObject(valueNode) : null;
  2424. // Pinia SETUP store: `defineStore('id', () => { const foo = …; return {…} })`.
  2425. // Its actions are body-local consts the generic walk can't reach.
  2426. const piniaSetup =
  2427. valueNode?.type === 'call_expression' ? this.findPiniaSetupFn(valueNode) : null;
  2428. // Vue store collections — make `actions`/`mutations`/`getters` findable
  2429. // function nodes (the foundation under any later dispatch-bridge synth).
  2430. // Two positions: INLINE in a store call (`defineStore({ actions: {…} })`
  2431. // / `createStore` / `new Vuex.Store`), and the non-exported Vuex-MODULE
  2432. // form (`const actions = {…}` at a store file's top level, wired via a
  2433. // `export default { actions }`). The Pinia SETUP form is handled by the
  2434. // body walk above (its actions are local consts).
  2435. const storeCollections: SyntaxNode[] = [];
  2436. if (valueNode?.type === 'call_expression' || valueNode?.type === 'new_expression') {
  2437. storeCollections.push(...this.findVueStoreCollectionObjects(valueNode));
  2438. }
  2439. if (objectOfFns && !extractObjectMethods &&
  2440. VUE_STORE_COLLECTION_NAMES.has(name) && this.looksLikeVueStoreFile()) {
  2441. storeCollections.push(objectOfFns);
  2442. }
  2443. // Visit the initializer body for calls — EXCEPT object literals (their
  2444. // function-valued properties are extracted below) and the store-factory
  2445. // / createApi / store-collection call whose nested objects we extract
  2446. // method-by-method below (walking the whole call would re-visit those
  2447. // method arrows and mis-attribute their inner calls to the file scope).
  2448. if (valueNode &&
  2449. valueNode.type !== 'object' &&
  2450. valueNode.type !== 'object_expression' &&
  2451. !(extractObjectMethods && valueNode.type === 'call_expression') &&
  2452. !rtkEndpoints &&
  2453. !piniaSetup &&
  2454. storeCollections.length === 0) {
  2455. this.visitFunctionBody(valueNode, '');
  2456. }
  2457. if (extractObjectMethods && objectOfFns) {
  2458. this.extractObjectLiteralFunctions(objectOfFns);
  2459. }
  2460. if (rtkEndpoints) {
  2461. this.extractRtkEndpoints(rtkEndpoints);
  2462. }
  2463. if (piniaSetup) {
  2464. this.extractPiniaSetupBody(piniaSetup);
  2465. }
  2466. for (const coll of storeCollections) {
  2467. this.extractObjectLiteralFunctions(coll);
  2468. }
  2469. }
  2470. }
  2471. }
  2472. } else if (this.language === 'python' || this.language === 'ruby') {
  2473. // Python/Ruby assignment: left = right
  2474. const left = getChildByField(node, 'left') || node.namedChild(0);
  2475. const right = getChildByField(node, 'right') || node.namedChild(1);
  2476. // Ruby constant assignments (`MAX = 3`) have a `constant`-typed LHS, not
  2477. // `identifier`; without this they were never extracted as symbols at all.
  2478. if (left && (left.type === 'identifier' || left.type === 'constant')) {
  2479. const name = getNodeText(left, this.source);
  2480. // Skip if name starts with lowercase and looks like a function call result
  2481. // Python constants are usually UPPER_CASE
  2482. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  2483. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2484. this.createNode(kind, name, node, {
  2485. docstring,
  2486. signature: initSignature,
  2487. });
  2488. }
  2489. } else if (this.language === 'go') {
  2490. // Go: var_declaration, short_var_declaration, const_declaration
  2491. // These can have multiple identifiers on the left
  2492. const specs = node.namedChildren.filter(c =>
  2493. c.type === 'var_spec' || c.type === 'const_spec'
  2494. );
  2495. for (const spec of specs) {
  2496. const nameNode = spec.namedChild(0);
  2497. let varNode: Node | null = null;
  2498. if (nameNode && nameNode.type === 'identifier') {
  2499. const name = getNodeText(nameNode, this.source);
  2500. const valueNode = spec.namedChildCount > 1 ? spec.namedChild(spec.namedChildCount - 1) : null;
  2501. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2502. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2503. varNode = this.createNode(node.type === 'const_declaration' ? 'constant' : 'variable', name, spec, {
  2504. docstring,
  2505. signature: initSignature,
  2506. });
  2507. }
  2508. // Walk the initializer so composite literals and calls in a
  2509. // package-level `var Query Binding = queryBinding{}` (a registry of
  2510. // implementations) or `var c = pkg.New()` are extracted as
  2511. // instantiates/calls dependencies — the body walker only covers
  2512. // initializers inside functions, not these top-level declarations.
  2513. // Scope the walk to the declared symbol so a call inside an anonymous
  2514. // func_literal initializer — a cobra `RunE: func(){…}` handler, a
  2515. // goroutine or callback closure — attributes to the var instead of
  2516. // leaking to the file node (which reads as "no caller"), issue #693.
  2517. const valueField = getChildByField(spec, 'value');
  2518. if (valueField) {
  2519. if (varNode) this.nodeStack.push(varNode.id);
  2520. this.visitFunctionBody(valueField, varNode?.id ?? '');
  2521. if (varNode) this.nodeStack.pop();
  2522. }
  2523. }
  2524. // Handle short_var_declaration (:=)
  2525. if (node.type === 'short_var_declaration') {
  2526. const left = getChildByField(node, 'left');
  2527. const right = getChildByField(node, 'right');
  2528. if (left) {
  2529. // Can be expression_list with multiple identifiers
  2530. const identifiers = left.type === 'expression_list'
  2531. ? left.namedChildren.filter(c => c.type === 'identifier')
  2532. : [left];
  2533. for (const id of identifiers) {
  2534. const name = getNodeText(id, this.source);
  2535. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  2536. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2537. this.createNode('variable', name, node, {
  2538. docstring,
  2539. signature: initSignature,
  2540. });
  2541. }
  2542. }
  2543. }
  2544. } else if (this.language === 'lua' || this.language === 'luau') {
  2545. // Lua/Luau: variable_declaration → assignment_statement → variable_list
  2546. // (name: identifier...) = expression_list. `local x, y = 1, 2`
  2547. // declares multiple names; only plain identifiers are locals.
  2548. const assign = node.namedChildren.find((c) => c.type === 'assignment_statement') ?? node;
  2549. const varList = assign.namedChildren.find((c) => c.type === 'variable_list');
  2550. const exprList = assign.namedChildren.find((c) => c.type === 'expression_list');
  2551. const values = exprList ? exprList.namedChildren : [];
  2552. const names = varList ? varList.namedChildren.filter((c) => c.type === 'identifier') : [];
  2553. names.forEach((nameNode, i) => {
  2554. const name = getNodeText(nameNode, this.source);
  2555. if (!name) return;
  2556. const valueNode = values[i];
  2557. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2558. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  2559. this.createNode(kind, name, nameNode, { docstring, signature: initSignature, isExported });
  2560. });
  2561. } else if (this.language === 'c') {
  2562. // C: a `declaration` node's name nests inside the `declarator` field —
  2563. // `init_declarator` (with value) or bare/pointer/array declarators (no
  2564. // value); a `function_declarator` is a prototype, not a variable. The
  2565. // generic fallback below only finds a *direct* identifier child, which C
  2566. // never has, so file-scope consts/globals went unextracted entirely (and
  2567. // so had no impact-radius edges). Only file-scope declarations are tracked
  2568. // — locals inside a function body are skipped (a `static const` table read
  2569. // by same-file functions is the value the impact graph wants, not every
  2570. // block-local). C allows several declarators per declaration
  2571. // (`int a = 1, b = 2;`), so iterate them.
  2572. if (!hasFunctionAncestor(node)) {
  2573. for (let i = 0; i < node.namedChildCount; i++) {
  2574. const child = node.namedChild(i);
  2575. if (!child) continue;
  2576. // Accept only `init_declarator` (has a value) and pointer/array
  2577. // declarators. A *bare* `identifier` declarator is deliberately
  2578. // skipped: an unknown leading macro (`CURL_EXTERN`, `XXH_PUBLIC_API`)
  2579. // makes tree-sitter-c misparse a prototype `MACRO RetType fn(args);`
  2580. // as a declaration whose "variable" is the bare return-type
  2581. // identifier, splitting `fn(args)` off as a bogus expression — minting
  2582. // a spurious type-named global for every macro-prefixed prototype in a
  2583. // header. Those misparses are always bare identifiers; real
  2584. // consts/tables always carry an initializer. The only legit loss is
  2585. // uninitialized scalar globals (`static int g;`).
  2586. if (
  2587. child.type !== 'init_declarator' &&
  2588. child.type !== 'pointer_declarator' &&
  2589. child.type !== 'array_declarator'
  2590. ) {
  2591. continue;
  2592. }
  2593. const nameNode = cDeclaratorIdentifier(child);
  2594. if (!nameNode) continue;
  2595. const name = getNodeText(nameNode, this.source);
  2596. if (!name) continue;
  2597. const valueNode =
  2598. child.type === 'init_declarator' ? getChildByField(child, 'value') : null;
  2599. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  2600. const initSignature = initValue
  2601. ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}`
  2602. : undefined;
  2603. this.createNode(kind, name, child, { docstring, signature: initSignature, isExported });
  2604. }
  2605. }
  2606. } else if (this.language === 'swift') {
  2607. // Swift top-level property (`let X = …` / `var Y = …`). The name nests in
  2608. // a `pattern`, which the generic fallback can't read, so top-level Swift
  2609. // constants/globals went unextracted. A top-level `let`→`constant`,
  2610. // `var`→`variable`; a computed property (getter, no value) is skipped.
  2611. const { nameNode, isLet, isComputed } = swiftPropertyInfo(node, this.source);
  2612. if (nameNode && !isComputed) {
  2613. this.createNode(isLet ? 'constant' : 'variable', getNodeText(nameNode, this.source), node, {
  2614. docstring,
  2615. isExported,
  2616. });
  2617. }
  2618. } else {
  2619. // Generic fallback for other languages
  2620. // Try to find identifier children
  2621. for (let i = 0; i < node.namedChildCount; i++) {
  2622. const child = node.namedChild(i);
  2623. if (child?.type === 'identifier' || child?.type === 'variable_declarator') {
  2624. const name = child.type === 'identifier'
  2625. ? getNodeText(child, this.source)
  2626. : extractName(child, this.source, this.extractor);
  2627. if (name && name !== '<anonymous>') {
  2628. this.createNode(kind, name, child, {
  2629. docstring,
  2630. isExported,
  2631. });
  2632. }
  2633. }
  2634. }
  2635. }
  2636. }
  2637. /**
  2638. * Extract a type alias (e.g. `export type X = ...` in TypeScript).
  2639. * For languages like Go, resolveTypeAliasKind detects when the type_spec
  2640. * wraps a struct or interface definition and creates the correct node kind.
  2641. * Returns true if children should be skipped (struct/interface handled body visiting).
  2642. */
  2643. private extractTypeAlias(node: SyntaxNode): boolean {
  2644. if (!this.extractor) return false;
  2645. const name = extractName(node, this.source, this.extractor);
  2646. if (name === '<anonymous>') return false;
  2647. const docstring = getPrecedingDocstring(node, this.source);
  2648. const isExported = this.extractor.isExported?.(node, this.source);
  2649. // Check if this type alias is actually a struct or interface definition
  2650. // (e.g. Go: `type Foo struct { ... }` is a type_spec wrapping struct_type)
  2651. const resolvedKind = this.extractor.resolveTypeAliasKind?.(node, this.source);
  2652. if (resolvedKind === 'struct') {
  2653. const structNode = this.createNode('struct', name, node, { docstring, isExported });
  2654. if (!structNode) return true;
  2655. // Visit body children for field extraction
  2656. this.nodeStack.push(structNode.id);
  2657. // Try Go-style 'type' field first, then find inner struct child (C typedef struct)
  2658. const typeChild = getChildByField(node, 'type')
  2659. || this.findChildByTypes(node, this.extractor.structTypes);
  2660. if (typeChild) {
  2661. // Extract struct embedding (e.g. Go: `type DB struct { *Head; Queryable }`)
  2662. this.extractInheritance(typeChild, structNode.id);
  2663. const body = getChildByField(typeChild, this.extractor.bodyField) || typeChild;
  2664. for (let i = 0; i < body.namedChildCount; i++) {
  2665. const child = body.namedChild(i);
  2666. if (child) this.visitNode(child);
  2667. }
  2668. }
  2669. this.nodeStack.pop();
  2670. return true;
  2671. }
  2672. if (resolvedKind === 'enum') {
  2673. const enumNode = this.createNode('enum', name, node, { docstring, isExported });
  2674. if (!enumNode) return true;
  2675. this.nodeStack.push(enumNode.id);
  2676. // Find the inner enum type child (e.g. C: typedef enum { ... } name)
  2677. const innerEnum = this.findChildByTypes(node, this.extractor.enumTypes);
  2678. if (innerEnum) {
  2679. this.extractInheritance(innerEnum, enumNode.id);
  2680. const body = this.extractor.resolveBody?.(innerEnum, this.extractor.bodyField)
  2681. ?? getChildByField(innerEnum, this.extractor.bodyField);
  2682. if (body) {
  2683. const memberTypes = this.extractor.enumMemberTypes;
  2684. for (let i = 0; i < body.namedChildCount; i++) {
  2685. const child = body.namedChild(i);
  2686. if (!child) continue;
  2687. if (memberTypes?.includes(child.type)) {
  2688. this.extractEnumMembers(child);
  2689. } else {
  2690. this.visitNode(child);
  2691. }
  2692. }
  2693. }
  2694. }
  2695. this.nodeStack.pop();
  2696. return true;
  2697. }
  2698. if (resolvedKind === 'interface') {
  2699. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  2700. const interfaceNode = this.createNode(kind, name, node, { docstring, isExported });
  2701. if (!interfaceNode) return true;
  2702. // Extract interface inheritance from the inner type node
  2703. const typeChild = getChildByField(node, 'type');
  2704. if (typeChild) this.extractInheritance(typeChild, interfaceNode.id);
  2705. // Go: extract the interface's method specs as `method` nodes so implicit
  2706. // interface satisfaction (a struct's method set ⊇ the interface's) and
  2707. // impl-navigation can see the contract. Go has no `implements` keyword, so
  2708. // without the interface's method set there's nothing to match against.
  2709. if (this.language === 'go' && typeChild) {
  2710. this.extractGoInterfaceMethods(typeChild, interfaceNode.id);
  2711. }
  2712. return true;
  2713. }
  2714. const typeAliasNode = this.createNode('type_alias', name, node, {
  2715. docstring,
  2716. isExported,
  2717. });
  2718. // Extract type references from the alias value (e.g., `type X = ITextModel | null`)
  2719. if (typeAliasNode && this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) {
  2720. // The value is everything after the `=`, which is typically the last named child
  2721. // In tree-sitter TS: type_alias_declaration has name + value children
  2722. const value = getChildByField(node, 'value');
  2723. if (value) {
  2724. this.extractTypeRefsFromSubtree(value, typeAliasNode.id);
  2725. // `type X = { foo: T; bar(): T }` — make the members first-class
  2726. // property/method nodes under the type alias so `recorder.stop()`
  2727. // can attach the call edge to `RecorderHandle.stop` instead of
  2728. // an unrelated class method picked by path-proximity (#359).
  2729. if (this.language === 'typescript' || this.language === 'tsx' || this.language === 'arkts') {
  2730. this.extractTsTypeAliasMembers(value, typeAliasNode);
  2731. // `type List = [ Service<'name', Req, Resp>, … ]` — surface each
  2732. // entry's string-literal name as a searchable member (issue #634).
  2733. this.extractTsTupleContractNames(value, typeAliasNode);
  2734. }
  2735. }
  2736. }
  2737. return false;
  2738. }
  2739. /**
  2740. * Extract the method specs of a Go `interface_type` body as `method` nodes
  2741. * contained by the interface (e.g. `Marshal`, `Unmarshal` of a `Core`
  2742. * interface). tree-sitter-go names these `method_elem` (newer) or
  2743. * `method_spec` (older). Embedded interfaces (`Reader` inside `ReadWriter`)
  2744. * are `type_identifier`s, not methods, and are left to inheritance extraction.
  2745. */
  2746. private extractGoInterfaceMethods(interfaceType: SyntaxNode, ifaceId: string): void {
  2747. this.nodeStack.push(ifaceId);
  2748. for (let i = 0; i < interfaceType.namedChildCount; i++) {
  2749. const m = interfaceType.namedChild(i);
  2750. if (!m || (m.type !== 'method_elem' && m.type !== 'method_spec')) continue;
  2751. const nameNode = getChildByField(m, 'name') ?? m.namedChild(0);
  2752. if (!nameNode) continue;
  2753. const mname = getNodeText(nameNode, this.source);
  2754. if (mname) {
  2755. this.createNode('method', mname, m, {
  2756. signature: this.extractor?.getSignature?.(m, this.source),
  2757. });
  2758. }
  2759. }
  2760. this.nodeStack.pop();
  2761. }
  2762. /**
  2763. * Surface the members of a TypeScript `type X = { ... }` (or intersection
  2764. * thereof) as `property` / `method` nodes under the type-alias node. Only
  2765. * walks the immediate object_type / intersection operands so anonymous
  2766. * nested object types inside generic arguments (`Promise<{ ok: true }>`)
  2767. * don't produce phantom members.
  2768. */
  2769. private extractTsTypeAliasMembers(value: SyntaxNode, typeAliasNode: Node): void {
  2770. const objectTypes: SyntaxNode[] = [];
  2771. if (value.type === 'object_type') {
  2772. objectTypes.push(value);
  2773. } else if (value.type === 'intersection_type') {
  2774. for (let i = 0; i < value.namedChildCount; i++) {
  2775. const op = value.namedChild(i);
  2776. if (op && op.type === 'object_type') objectTypes.push(op);
  2777. }
  2778. } else {
  2779. return;
  2780. }
  2781. this.nodeStack.push(typeAliasNode.id);
  2782. for (const objType of objectTypes) {
  2783. for (let i = 0; i < objType.namedChildCount; i++) {
  2784. const child = objType.namedChild(i);
  2785. if (!child) continue;
  2786. if (child.type !== 'property_signature' && child.type !== 'method_signature') continue;
  2787. const nameNode = getChildByField(child, 'name');
  2788. const memberName = nameNode ? getNodeText(nameNode, this.source) : '';
  2789. if (!memberName) continue;
  2790. // `foo: () => T` and `foo(): T` are functionally a method on the
  2791. // type contract. Treat the property_signature with a function-typed
  2792. // annotation as a method too so call sites can resolve to it.
  2793. const memberKind: NodeKind = child.type === 'method_signature'
  2794. ? 'method'
  2795. : this.isTsFunctionTypedProperty(child) ? 'method' : 'property';
  2796. const docstring = getPrecedingDocstring(child, this.source);
  2797. const signature = getNodeText(child, this.source);
  2798. this.createNode(memberKind, memberName, child, {
  2799. docstring,
  2800. signature,
  2801. qualifiedName: `${typeAliasNode.name}::${memberName}`,
  2802. });
  2803. // Emit `references` edges from the type alias to types named in the
  2804. // member's signature, matching the interface-member behavior added in
  2805. // #432. We attach refs to the type-alias parent (consistent with
  2806. // interface property_signature treatment).
  2807. this.extractTypeAnnotations(child, typeAliasNode.id);
  2808. }
  2809. }
  2810. this.nodeStack.pop();
  2811. }
  2812. /**
  2813. * Surface the string-literal "names" of a TypeScript service/contract
  2814. * registry written as a tuple of generic instantiations:
  2815. *
  2816. * type MyServiceList = [
  2817. * Service<'query_apply_record', Req, Resp>,
  2818. * Service<'apply_confirm', Req, Resp>,
  2819. * ];
  2820. *
  2821. * Each `Service<'name', …>` tags an entry with a string-literal name that a
  2822. * dynamic factory (`createService<MyServiceList>()`) turns into a callable
  2823. * property (`api.query_apply_record(…)`). Static extraction otherwise never
  2824. * sees that name — it's a type argument, not a declaration — so
  2825. * `codegraph query query_apply_record` returned nothing (issue #634). We emit
  2826. * each name as a `method` node under the type alias (qualifiedName
  2827. * `MyServiceList::query_apply_record`) so it's searchable and resolvable as a
  2828. * symbol. (A call through the proxy, `api.query_apply_record(…)`, still
  2829. * resolves to the imported `api` binding — the receiver's type isn't known —
  2830. * so this fixes discoverability, not the per-method call edge.)
  2831. *
  2832. * Scope is deliberately narrow to avoid noise: only a string literal that is
  2833. * a DIRECT type argument of a `generic_type` that is itself a DIRECT element
  2834. * of a `tuple_type`. This excludes utility types (`Pick`/`Omit`/`Record` are
  2835. * never written as tuples) and string args nested deeper
  2836. * (`Service<'a', Pick<U, 'id'>>` yields only `a`, never `id`). Names must be
  2837. * valid identifiers, which also rules out route paths / arbitrary strings.
  2838. */
  2839. private extractTsTupleContractNames(value: SyntaxNode, typeAliasNode: Node): void {
  2840. const tuples: SyntaxNode[] = [];
  2841. const collectTuples = (n: SyntaxNode, depth: number): void => {
  2842. if (depth > 6) return; // a type expression is shallow; cap defensively
  2843. if (n.type === 'tuple_type') tuples.push(n);
  2844. for (let i = 0; i < n.namedChildCount; i++) {
  2845. const c = n.namedChild(i);
  2846. if (c) collectTuples(c, depth + 1);
  2847. }
  2848. };
  2849. collectTuples(value, 0);
  2850. if (tuples.length === 0) return;
  2851. this.nodeStack.push(typeAliasNode.id);
  2852. for (const tuple of tuples) {
  2853. for (let i = 0; i < tuple.namedChildCount; i++) {
  2854. const entry = tuple.namedChild(i);
  2855. if (!entry || entry.type !== 'generic_type') continue;
  2856. const typeArgs = getChildByField(entry, 'type_arguments');
  2857. if (!typeArgs) continue;
  2858. for (let j = 0; j < typeArgs.namedChildCount; j++) {
  2859. const arg = typeArgs.namedChild(j);
  2860. if (!arg || arg.type !== 'literal_type') continue;
  2861. // literal_type wraps the actual literal; only a string is a name.
  2862. const strNode = arg.namedChild(0);
  2863. if (!strNode || strNode.type !== 'string') continue;
  2864. const name = getNodeText(strNode, this.source)
  2865. .trim()
  2866. .replace(/^['"`]/, '')
  2867. .replace(/['"`]$/, '');
  2868. if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) continue;
  2869. const signature = getNodeText(entry, this.source).replace(/\s+/g, ' ').trim().slice(0, 120);
  2870. this.createNode('method', name, entry, {
  2871. signature,
  2872. qualifiedName: `${typeAliasNode.name}::${name}`,
  2873. });
  2874. }
  2875. }
  2876. }
  2877. this.nodeStack.pop();
  2878. }
  2879. /**
  2880. * `foo: () => T` → property_signature whose type_annotation contains a
  2881. * `function_type`. Treat that as a method-shaped contract member, since
  2882. * the call site `obj.foo()` has identical semantics to `bar(): T`.
  2883. */
  2884. private isTsFunctionTypedProperty(propertySignature: SyntaxNode): boolean {
  2885. const typeAnno = getChildByField(propertySignature, 'type');
  2886. if (!typeAnno) return false;
  2887. for (let i = 0; i < typeAnno.namedChildCount; i++) {
  2888. const inner = typeAnno.namedChild(i);
  2889. if (inner && inner.type === 'function_type') return true;
  2890. }
  2891. return false;
  2892. }
  2893. // extractExportedVariables removed — the walker now descends into
  2894. // export_statement children and the inner declaration's dedicated
  2895. // extractor (extractVariable, extractFunction, extractClass, etc.)
  2896. // handles the symbol with isExported=true via parent-walk in the
  2897. // language extractor's isExported predicate.
  2898. /**
  2899. * Extract an import
  2900. *
  2901. * Creates an import node with the full import statement stored in signature for searchability.
  2902. * Also creates unresolved references for resolution purposes.
  2903. */
  2904. private extractImport(node: SyntaxNode): void {
  2905. if (!this.extractor) return;
  2906. const importText = getNodeText(node, this.source).trim();
  2907. // Try language-specific hook first
  2908. if (this.extractor.extractImport) {
  2909. const info = this.extractor.extractImport(node, this.source);
  2910. if (info) {
  2911. this.createNode('import', info.moduleName, node, {
  2912. signature: info.signature,
  2913. });
  2914. // Create unresolved reference unless the hook handled it
  2915. if (!info.handledRefs && info.moduleName && this.nodeStack.length > 0) {
  2916. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2917. if (parentId) {
  2918. this.unresolvedReferences.push({
  2919. fromNodeId: parentId,
  2920. referenceName: info.moduleName,
  2921. referenceKind: 'imports',
  2922. line: node.startPosition.row + 1,
  2923. column: node.startPosition.column,
  2924. });
  2925. }
  2926. }
  2927. // Link each imported binding to its definition so imported-but-not-
  2928. // called/typed symbols still record a cross-file dependency (TS/JS only).
  2929. if (
  2930. this.language === 'typescript' || this.language === 'tsx' ||
  2931. this.language === 'javascript' || this.language === 'jsx' ||
  2932. this.language === 'arkts'
  2933. ) {
  2934. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2935. if (parentId) this.emitImportBindingRefs(node, parentId);
  2936. }
  2937. // Python `from module import X, Y` — link each imported name to its
  2938. // definition (covers `__init__.py` re-export barrels, which are just
  2939. // `from .sub import X`). Same recall gap as TS: a name imported and
  2940. // used in a non-call position created no dependency edge.
  2941. if (this.language === 'python' && node.type === 'import_from_statement') {
  2942. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2943. if (parentId) this.emitPyFromImportRefs(node, parentId);
  2944. }
  2945. // Rust `use crate::m::Item;` / `pub use self::sub::Item;` — link each
  2946. // imported leaf to its definition. Covers `pub use` re-export hubs
  2947. // (a `mod.rs` re-exporting submodule items, e.g. tokio's `fs/mod.rs`)
  2948. // and items imported but used in non-call/non-type positions.
  2949. if (this.language === 'rust' && node.type === 'use_declaration') {
  2950. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2951. if (parentId) this.emitRustUseBindingRefs(node, parentId);
  2952. }
  2953. // PHP `use Foo\Bar\Baz;` — link to the namespace-qualified definition so
  2954. // an imported-but-DI-injected contract (Laravel's pattern) records a
  2955. // cross-file dependency. Grouped imports are handled in their own branch.
  2956. if (this.language === 'php' && node.type === 'namespace_use_declaration') {
  2957. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2958. if (parentId) this.emitPhpUseRefs(node, parentId);
  2959. }
  2960. // Ruby `require "lib/foo"` / `require_relative "../foo"` — resolve to the
  2961. // required FILE so a file pulled in only by `require` (config-loaded
  2962. // components, gems that don't autoload) records a cross-file dependency.
  2963. if (this.language === 'ruby' && node.type === 'call') {
  2964. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2965. if (parentId) this.emitRubyRequireRefs(node, parentId);
  2966. }
  2967. return;
  2968. }
  2969. // Hook returned null — fall through to multi-import inline handlers only
  2970. // (hook returning null means "I didn't handle this" for multi-import cases,
  2971. // NOT "use generic fallback" — the hook already declined)
  2972. }
  2973. // Multi-import cases that create multiple nodes (can't be expressed with single-return hook)
  2974. // Python import_statement: import os, sys (creates one import per module)
  2975. if (this.language === 'python' && node.type === 'import_statement') {
  2976. const importParentId = this.nodeStack[this.nodeStack.length - 1];
  2977. // A bare `import a.b.c` of an internal module (the standard Django
  2978. // `AppConfig.ready(): import myapp.signals` registration pattern, and any
  2979. // `import pkg.mod` used for its side effects) had no edge to the module
  2980. // file — only `from x import y` was linked. Push an `imports` ref (like
  2981. // Go) so the resolver maps the dotted path to its file. Stdlib/external
  2982. // modules naturally don't resolve (no `os.py` file node in the repo).
  2983. const pushModuleRef = (dotted: SyntaxNode): void => {
  2984. if (!importParentId) return;
  2985. this.unresolvedReferences.push({
  2986. fromNodeId: importParentId,
  2987. referenceName: getNodeText(dotted, this.source),
  2988. referenceKind: 'imports',
  2989. line: dotted.startPosition.row + 1,
  2990. column: dotted.startPosition.column,
  2991. });
  2992. };
  2993. for (let i = 0; i < node.namedChildCount; i++) {
  2994. const child = node.namedChild(i);
  2995. if (child?.type === 'dotted_name') {
  2996. this.createNode('import', getNodeText(child, this.source), node, {
  2997. signature: importText,
  2998. });
  2999. pushModuleRef(child);
  3000. } else if (child?.type === 'aliased_import') {
  3001. const dottedName = child.namedChildren.find(c => c.type === 'dotted_name');
  3002. if (dottedName) {
  3003. this.createNode('import', getNodeText(dottedName, this.source), node, {
  3004. signature: importText,
  3005. });
  3006. pushModuleRef(dottedName);
  3007. }
  3008. }
  3009. }
  3010. return;
  3011. }
  3012. // Go imports: single or grouped (creates one import per spec)
  3013. if (this.language === 'go') {
  3014. const parentId = this.nodeStack.length > 0 ? this.nodeStack[this.nodeStack.length - 1] : null;
  3015. const extractFromSpec = (spec: SyntaxNode): void => {
  3016. const stringLiteral = spec.namedChildren.find(c => c.type === 'interpreted_string_literal');
  3017. if (stringLiteral) {
  3018. const importPath = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  3019. if (importPath) {
  3020. this.createNode('import', importPath, spec, {
  3021. signature: getNodeText(spec, this.source).trim(),
  3022. });
  3023. // Create unresolved reference so the resolver can create imports edges
  3024. if (parentId) {
  3025. this.unresolvedReferences.push({
  3026. fromNodeId: parentId,
  3027. referenceName: importPath,
  3028. referenceKind: 'imports',
  3029. line: spec.startPosition.row + 1,
  3030. column: spec.startPosition.column,
  3031. });
  3032. }
  3033. }
  3034. }
  3035. };
  3036. const importSpecList = node.namedChildren.find(c => c.type === 'import_spec_list');
  3037. if (importSpecList) {
  3038. for (const spec of importSpecList.namedChildren.filter(c => c.type === 'import_spec')) {
  3039. extractFromSpec(spec);
  3040. }
  3041. } else {
  3042. const importSpec = node.namedChildren.find(c => c.type === 'import_spec');
  3043. if (importSpec) {
  3044. extractFromSpec(importSpec);
  3045. }
  3046. }
  3047. return;
  3048. }
  3049. // PHP grouped imports: use X\{A, B} (creates one import per item)
  3050. if (this.language === 'php') {
  3051. const namespacePrefix = node.namedChildren.find(c => c.type === 'namespace_name');
  3052. const useGroup = node.namedChildren.find(c => c.type === 'namespace_use_group');
  3053. if (namespacePrefix && useGroup) {
  3054. const prefix = getNodeText(namespacePrefix, this.source);
  3055. const useClauses = useGroup.namedChildren.filter((c: SyntaxNode) =>
  3056. c.type === 'namespace_use_group_clause' || c.type === 'namespace_use_clause'
  3057. );
  3058. for (const clause of useClauses) {
  3059. const nsName = clause.namedChildren.find((c: SyntaxNode) => c.type === 'namespace_name');
  3060. const name = nsName
  3061. ? nsName.namedChildren.find((c: SyntaxNode) => c.type === 'name')
  3062. : clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  3063. if (name) {
  3064. const fullPath = `${prefix}\\${getNodeText(name, this.source)}`;
  3065. this.createNode('import', fullPath, node, {
  3066. signature: importText,
  3067. });
  3068. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3069. if (parentId) this.pushPhpUseRef(fullPath, parentId, node);
  3070. }
  3071. }
  3072. return;
  3073. }
  3074. }
  3075. // If a hook exists but returned null, it intentionally declined this node — don't create fallback
  3076. if (this.extractor.extractImport) return;
  3077. // Generic fallback for languages without hooks
  3078. this.createNode('import', importText, node, {
  3079. signature: importText,
  3080. });
  3081. }
  3082. /**
  3083. * Emit one `imports` reference per named/default import binding (TS/JS family),
  3084. * attributed to the file node — so the resolver links each imported symbol to
  3085. * the file that DEFINES it.
  3086. *
  3087. * Importing a symbol IS a dependency, but extraction only emits references for
  3088. * calls, instantiations, type annotations, and inheritance. A symbol that's
  3089. * imported and then only re-exported (`export { X } from './x'`), placed in a
  3090. * registry array (`[expressResolver, …]`), passed as an argument, or used in
  3091. * JSX produced NO cross-file edge at all — so the providing file showed a
  3092. * false "0 dependents" and was invisible to blast-radius / `affected`. The
  3093. * resolver maps the local name (alias-aware) to the provider's definition and
  3094. * creates a cross-file `imports` edge; `getFileDependents` picks it up, while
  3095. * `getImpactRadius` keeps it as a bounded leaf (the importing file node).
  3096. *
  3097. * Namespace imports (`import * as NS`) bind a whole module: `NS.member` calls
  3098. * resolve on their own, but a namespace used ONLY via a value-member read
  3099. * (`NS.SOME_CONST`) would leave no edge — so we also emit the namespace local
  3100. * name, which the resolver links to the module FILE as a dependency backstop.
  3101. */
  3102. private emitImportBindingRefs(node: SyntaxNode, fromNodeId: string): void {
  3103. const clause = node.namedChildren.find((c) => c.type === 'import_clause');
  3104. if (!clause) return; // side-effect import (`import './x'`) — no bindings
  3105. const pushRef = (nameNode: SyntaxNode | null | undefined): void => {
  3106. if (!nameNode) return;
  3107. const name = getNodeText(nameNode, this.source);
  3108. if (!name) return;
  3109. this.unresolvedReferences.push({
  3110. fromNodeId,
  3111. referenceName: name,
  3112. referenceKind: 'imports',
  3113. line: nameNode.startPosition.row + 1,
  3114. column: nameNode.startPosition.column,
  3115. });
  3116. };
  3117. for (const child of clause.namedChildren) {
  3118. if (child.type === 'identifier') {
  3119. // default import: `import Foo from './x'`
  3120. pushRef(child);
  3121. } else if (child.type === 'named_imports') {
  3122. // `import { A, B as C } from './x'` — link the LOCAL name (alias if any)
  3123. for (const spec of child.namedChildren) {
  3124. if (spec.type !== 'import_specifier') continue;
  3125. pushRef(getChildByField(spec, 'alias') ?? getChildByField(spec, 'name') ?? spec.namedChild(0));
  3126. }
  3127. } else if (child.type === 'namespace_import') {
  3128. // `import * as NS from './x'` — emit NS so the module-import backstop can
  3129. // record the file dependency even if NS is only used by value-member read.
  3130. pushRef(child.namedChildren.find((c) => c.type === 'identifier') ?? child.namedChild(0));
  3131. }
  3132. }
  3133. }
  3134. /**
  3135. * Emit one `imports` reference per re-exported binding of a
  3136. * `export { A, B as C } from './y'` statement, attributed to the file node —
  3137. * so a barrel that re-exports from another module records a dependency on it.
  3138. *
  3139. * Links the SOURCE-side name (`A`, the `name` field — not the local alias
  3140. * `C`), since that is what the source module defines. `export * from './y'`
  3141. * has no named bindings to attribute and `export { default as X }` can't be
  3142. * name-matched, so both are skipped.
  3143. */
  3144. private emitReExportRefs(node: SyntaxNode, fromNodeId: string): void {
  3145. const clause = node.namedChildren.find((c) => c.type === 'export_clause');
  3146. if (!clause) return; // `export * from './y'` — no named bindings
  3147. for (const spec of clause.namedChildren) {
  3148. if (spec.type !== 'export_specifier') continue;
  3149. const nameNode = getChildByField(spec, 'name') ?? spec.namedChild(0);
  3150. if (!nameNode) continue;
  3151. const name = getNodeText(nameNode, this.source);
  3152. if (!name || name === 'default') continue;
  3153. this.unresolvedReferences.push({
  3154. fromNodeId,
  3155. referenceName: name,
  3156. referenceKind: 'imports',
  3157. line: nameNode.startPosition.row + 1,
  3158. column: nameNode.startPosition.column,
  3159. });
  3160. }
  3161. }
  3162. /**
  3163. * Emit one `imports` reference per binding of a Rust `use` declaration —
  3164. * `use crate::m::Item`, `use crate::m::{A, B as C}`, `pub use self::sub::Item`.
  3165. * Emits the FULL path (e.g. `self::sub::Item`, not just `Item`) so the resolver
  3166. * can resolve the module prefix to a file and find the leaf symbol there —
  3167. * disambiguating common-name re-exports (`pub use self::read::read`, where the
  3168. * leaf `read` collides with many same-named symbols). Falls back to name-match
  3169. * on the leaf when the path can't be resolved. `use ...::*` has no leaf binding.
  3170. */
  3171. private emitRustUseBindingRefs(node: SyntaxNode, fromNodeId: string): void {
  3172. const paths: { text: string; node: SyntaxNode }[] = [];
  3173. const join = (prefix: string, seg: string): string => (prefix ? `${prefix}::${seg}` : seg);
  3174. const collect = (n: SyntaxNode, prefix: string): void => {
  3175. switch (n.type) {
  3176. case 'identifier':
  3177. paths.push({ text: join(prefix, getNodeText(n, this.source)), node: n });
  3178. break;
  3179. case 'scoped_identifier': {
  3180. // Full scoped path (`a::b::C`); combine with any outer group prefix.
  3181. const full = getNodeText(n, this.source).trim();
  3182. paths.push({ text: prefix ? `${prefix}::${full}` : full, node: n });
  3183. break;
  3184. }
  3185. case 'scoped_use_list': {
  3186. // `path::{ ... }` — the group's path becomes the prefix for each item.
  3187. const pathNode = getChildByField(n, 'path');
  3188. const seg = pathNode ? getNodeText(pathNode, this.source).trim() : '';
  3189. const newPrefix = seg ? join(prefix, seg) : prefix;
  3190. const list = getChildByField(n, 'list') ?? n.namedChildren.find((c) => c.type === 'use_list');
  3191. if (list) collect(list, newPrefix);
  3192. break;
  3193. }
  3194. case 'use_list':
  3195. for (let i = 0; i < n.namedChildCount; i++) {
  3196. const c = n.namedChild(i);
  3197. if (c) collect(c, prefix);
  3198. }
  3199. break;
  3200. case 'use_as_clause': {
  3201. // `Path as Alias` → link the source path (the definition), not the alias.
  3202. const p = getChildByField(n, 'path') ?? n.namedChild(0);
  3203. if (p) collect(p, prefix);
  3204. break;
  3205. }
  3206. // use_wildcard → no specific binding to link.
  3207. }
  3208. };
  3209. for (let i = 0; i < node.namedChildCount; i++) {
  3210. const c = node.namedChild(i);
  3211. if (c) collect(c, '');
  3212. }
  3213. for (const p of paths) {
  3214. // The leaf must be a real name (skip a path that is only `self`/`super`/`crate`).
  3215. const leaf = p.text.split('::').pop();
  3216. if (!leaf || leaf === 'self' || leaf === 'super' || leaf === 'crate' || leaf === '*') continue;
  3217. this.unresolvedReferences.push({
  3218. fromNodeId,
  3219. referenceName: p.text,
  3220. referenceKind: 'imports',
  3221. line: p.node.startPosition.row + 1,
  3222. column: p.node.startPosition.column,
  3223. });
  3224. }
  3225. }
  3226. /**
  3227. * Emit an `imports` reference for a single PHP `use Foo\Bar\Baz;` (grouped
  3228. * imports `use Foo\{A, B}` are handled where their per-item nodes are created).
  3229. * The reference targets the namespace-qualified `Foo\Bar::Baz` form classes are
  3230. * stored under (see the PHP `namespace` capture), so it resolves to the RIGHT
  3231. * definition — Laravel has many same-named contracts (`Factory`, `Dispatcher`,
  3232. * `Guard`) across namespaces that a bare-name match can't disambiguate.
  3233. */
  3234. private emitPhpUseRefs(node: SyntaxNode, fromNodeId: string): void {
  3235. const clause = node.namedChildren.find((c: SyntaxNode) => c.type === 'namespace_use_clause');
  3236. if (!clause) return;
  3237. const qn = clause.namedChildren.find((c: SyntaxNode) => c.type === 'qualified_name')
  3238. ?? clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  3239. if (qn) this.pushPhpUseRef(getNodeText(qn, this.source), fromNodeId, node);
  3240. }
  3241. /**
  3242. * Ruby `require`/`require_relative` → an `imports` ref to the required FILE.
  3243. * `require "sidekiq/fetch"` is load-path-relative (matched by file-path suffix
  3244. * via {@link matchByFilePath}); `require_relative "../foo"` is resolved against
  3245. * this file's directory. Bare gem/stdlib requires (`require "json"`, no slash)
  3246. * are skipped — they're external. The path form (a `/` + `.rb`) makes the ref
  3247. * resolve to the file node, so a file pulled in only by `require` — not by a
  3248. * resolved constant/call — still records a cross-file dependency.
  3249. */
  3250. private emitRubyRequireRefs(node: SyntaxNode, fromNodeId: string): void {
  3251. const method = node.namedChildren.find((c: SyntaxNode) => c.type === 'identifier');
  3252. const mname = method ? getNodeText(method, this.source) : '';
  3253. if (mname !== 'require' && mname !== 'require_relative') return;
  3254. const argList = node.namedChildren.find((c: SyntaxNode) => c.type === 'argument_list');
  3255. const str = argList?.namedChildren.find((c: SyntaxNode) => c.type === 'string');
  3256. const content = str?.namedChildren.find((c: SyntaxNode) => c.type === 'string_content');
  3257. if (!content) return;
  3258. const req = getNodeText(content, this.source).trim();
  3259. if (!req) return;
  3260. let refPath: string;
  3261. if (mname === 'require_relative') {
  3262. const slash = this.filePath.lastIndexOf('/');
  3263. const dir = slash >= 0 ? this.filePath.slice(0, slash) : '';
  3264. refPath = path.posix.normalize(dir ? `${dir}/${req}` : req);
  3265. } else {
  3266. refPath = req; // load-path require — suffix-matched against the file path
  3267. }
  3268. if (!refPath.includes('/')) return; // bare gem/stdlib require — external
  3269. if (!refPath.endsWith('.rb')) refPath += '.rb';
  3270. this.unresolvedReferences.push({
  3271. fromNodeId,
  3272. referenceName: refPath,
  3273. referenceKind: 'imports',
  3274. line: node.startPosition.row + 1,
  3275. column: node.startPosition.column,
  3276. });
  3277. }
  3278. /** Convert a PHP FQN `Foo\Bar\Baz` to the stored `Foo\Bar::Baz` and emit an `imports` ref. */
  3279. private pushPhpUseRef(fqn: string, fromNodeId: string, node: SyntaxNode): void {
  3280. const clean = fqn.replace(/^\\/, '');
  3281. const lastSep = clean.lastIndexOf('\\');
  3282. if (lastSep < 0) return; // global-namespace class — already matches by simple name
  3283. this.unresolvedReferences.push({
  3284. fromNodeId,
  3285. referenceName: `${clean.slice(0, lastSep)}::${clean.slice(lastSep + 1)}`,
  3286. referenceKind: 'imports',
  3287. line: node.startPosition.row + 1,
  3288. column: node.startPosition.column,
  3289. });
  3290. }
  3291. /**
  3292. * Emit one `imports` reference per name imported in a Python
  3293. * `from module import A, B as C` statement, attributed to the file node — so
  3294. * the resolver links each imported name to the module that DEFINES it.
  3295. *
  3296. * Same recall gap as TS: extraction only emitted references for calls,
  3297. * instantiations, and inheritance, so a name imported and then used in a
  3298. * non-call position (a list/dict literal, a default argument, a decorator
  3299. * target, or simply re-exported through an `__init__.py` barrel) produced no
  3300. * cross-file edge — the providing module showed a false "0 dependents". Links
  3301. * the LOCAL name (alias when present, since that's what the resolver's import
  3302. * mapping keys on); `from module import *` has no names to attribute.
  3303. */
  3304. private emitPyFromImportRefs(node: SyntaxNode, fromNodeId: string): void {
  3305. const moduleNameNode = getChildByField(node, 'module_name');
  3306. for (const child of node.namedChildren) {
  3307. // Skip the `from <module>` part itself and `import *`.
  3308. if (moduleNameNode &&
  3309. child.startIndex === moduleNameNode.startIndex &&
  3310. child.endIndex === moduleNameNode.endIndex) continue;
  3311. if (child.type === 'wildcard_import') continue;
  3312. let nameNode: SyntaxNode | null | undefined = null;
  3313. if (child.type === 'aliased_import') {
  3314. nameNode = getChildByField(child, 'alias') ?? getChildByField(child, 'name') ?? child.namedChild(0);
  3315. } else if (child.type === 'dotted_name') {
  3316. nameNode = child;
  3317. }
  3318. if (!nameNode) continue;
  3319. const raw = getNodeText(nameNode, this.source);
  3320. // Imported names are simple identifiers; defensively take the last segment.
  3321. const local = raw.includes('.') ? raw.split('.').pop()! : raw;
  3322. if (!local) continue;
  3323. this.unresolvedReferences.push({
  3324. fromNodeId,
  3325. referenceName: local,
  3326. referenceKind: 'imports',
  3327. line: nameNode.startPosition.row + 1,
  3328. column: nameNode.startPosition.column,
  3329. });
  3330. }
  3331. }
  3332. /**
  3333. * Extract a function call
  3334. */
  3335. /**
  3336. * The module an Erlang gen_server target expression statically names, or
  3337. * null when it's dynamic (pid/var/tuple form). Static shapes:
  3338. * - a bare atom — either this module or another one; OTP's dominant
  3339. * registration convention (`{local, ?MODULE}`) names a server process
  3340. * after its module, so `gen_server:call(other_mod, …)` reaches
  3341. * `other_mod`'s handlers. A registered name that matches no module
  3342. * resolves to nothing downstream (the qualified ref just drops).
  3343. * - `?MODULE`, or a macro the file defines as `?MODULE`
  3344. * (`-define(SERVER, ?MODULE)` — the standard self idiom)
  3345. * - a macro the file defines as a bare atom
  3346. * (`-define(STORE, kv_store)` — the cross-module variant)
  3347. * The macro tables are memoized per file (single entry — extraction is
  3348. * file-sequential).
  3349. */
  3350. private erlangServerMacroFile = '';
  3351. private erlangSelfMacros = new Set<string>();
  3352. private erlangAtomMacros = new Map<string, string>();
  3353. private resolveErlangGenServerTarget(target: SyntaxNode): string | null {
  3354. const ownModule = (this.filePath.split('/').pop() ?? '').replace(/\.erl$/, '');
  3355. if (target.type === 'atom') {
  3356. const name = getNodeText(target, this.source).replace(/^'([\s\S]*)'$/, '$1');
  3357. return name || null;
  3358. }
  3359. if (target.type !== 'macro_call_expr') return null;
  3360. const nameNode = getChildByField(target, 'name');
  3361. if (!nameNode) return null;
  3362. const macroName = getNodeText(nameNode, this.source);
  3363. if (macroName === 'MODULE') return ownModule || null;
  3364. if (this.erlangServerMacroFile !== this.filePath) {
  3365. this.erlangServerMacroFile = this.filePath;
  3366. this.erlangSelfMacros = new Set<string>();
  3367. this.erlangAtomMacros = new Map<string, string>();
  3368. let root: SyntaxNode = target;
  3369. while (root.parent) root = root.parent;
  3370. for (let i = 0; i < root.namedChildCount; i++) {
  3371. const form = root.namedChild(i);
  3372. if (form?.type !== 'pp_define') continue;
  3373. const lhs = getChildByField(form, 'lhs');
  3374. const defName = lhs ? getChildByField(lhs, 'name') : null;
  3375. const replacement = getChildByField(form, 'replacement');
  3376. if (!defName || !replacement) continue;
  3377. if (
  3378. replacement.type === 'macro_call_expr' &&
  3379. getChildByField(replacement, 'name') &&
  3380. getNodeText(getChildByField(replacement, 'name')!, this.source) === 'MODULE'
  3381. ) {
  3382. this.erlangSelfMacros.add(getNodeText(defName, this.source));
  3383. } else if (replacement.type === 'atom') {
  3384. this.erlangAtomMacros.set(
  3385. getNodeText(defName, this.source),
  3386. getNodeText(replacement, this.source).replace(/^'([\s\S]*)'$/, '$1'),
  3387. );
  3388. }
  3389. }
  3390. }
  3391. if (this.erlangSelfMacros.has(macroName)) return ownModule || null;
  3392. return this.erlangAtomMacros.get(macroName) ?? null;
  3393. }
  3394. private extractCall(node: SyntaxNode): void {
  3395. if (this.nodeStack.length === 0) return;
  3396. const callerId = this.nodeStack[this.nodeStack.length - 1];
  3397. if (!callerId) return;
  3398. // VB.NET: `foo(args)` is syntactically ambiguous between a call and an
  3399. // index read, so the grammar parses non-empty parens as
  3400. // array_access_expression (field `array`, not `function`) — even Roslyn
  3401. // parses both as InvocationExpression and resolves during binding. Treat
  3402. // all three shapes as call sites: the callee is the member/identifier
  3403. // under the array/function field, qualified with a simple-identifier
  3404. // receiver for resolution. Index reads on collections simply never
  3405. // resolve to a callable, so they cost nothing.
  3406. if (
  3407. this.language === 'vbnet' &&
  3408. (node.type === 'array_access_expression' ||
  3409. node.type === 'invocation_expression' ||
  3410. node.type === 'generic_invocation_expression')
  3411. ) {
  3412. const fn = getChildByField(node, 'function') || getChildByField(node, 'array');
  3413. if (!fn) return;
  3414. let calleeName = '';
  3415. if (fn.type === 'member_access_expression') {
  3416. const member = getChildByField(fn, 'member');
  3417. const memberName = member ? getNodeText(member, this.source) : '';
  3418. if (!memberName) return;
  3419. const receiver = getChildByField(fn, 'object');
  3420. const SKIP = new Set(['me', 'mybase', 'myclass']);
  3421. if (receiver && receiver.type === 'identifier' && !SKIP.has(getNodeText(receiver, this.source).toLowerCase())) {
  3422. calleeName = `${getNodeText(receiver, this.source)}.${memberName}`;
  3423. } else {
  3424. calleeName = memberName;
  3425. }
  3426. } else if (fn.type === 'identifier') {
  3427. calleeName = getNodeText(fn, this.source);
  3428. } else {
  3429. return; // parenthesized/chained receivers: no static name to link
  3430. }
  3431. if (calleeName) {
  3432. this.unresolvedReferences.push({
  3433. fromNodeId: callerId,
  3434. referenceName: calleeName,
  3435. referenceKind: 'calls',
  3436. line: node.startPosition.row + 1,
  3437. column: node.startPosition.column,
  3438. });
  3439. }
  3440. return;
  3441. }
  3442. // Erlang: a local call is `call(expr: atom, args)`; a remote call nests it
  3443. // under `remote(module: remote_module, fun: call)` — the module qualifier
  3444. // lives on the PARENT. Remote calls are emitted as `mod::fn`, which is
  3445. // byte-identical to the qualifiedName the module namespace gives every
  3446. // function (see packageTypes in languages/erlang.ts), so they resolve via
  3447. // matchByQualifiedName. A var/macro callee or module (`F(X)`, `?M(X)`,
  3448. // `Mod:handle(X)`) has no static target — except `?MODULE:fn(X)`, which the
  3449. // bare name + same-file preference resolves correctly. `fun name/1` /
  3450. // `fun mod:name/1` values are function REFERENCES (callback registration),
  3451. // and record construction/update/index/field-access are `references` to the
  3452. // record's struct node.
  3453. if (this.language === 'erlang') {
  3454. const line = node.startPosition.row + 1;
  3455. const column = node.startPosition.column;
  3456. const erlAtom = (n: SyntaxNode): string => getNodeText(n, this.source).replace(/^'([\s\S]*)'$/, '$1');
  3457. if (node.type === 'call') {
  3458. let callee = getChildByField(node, 'expr');
  3459. let moduleNode: SyntaxNode | null = null;
  3460. // remote(module, fun: call) — the shape the grammar produces today; the
  3461. // node-types also permit call(expr: remote), so handle both nestings.
  3462. if (node.parent?.type === 'remote') {
  3463. moduleNode = getChildByField(node.parent, 'module');
  3464. } else if (callee?.type === 'remote') {
  3465. moduleNode = getChildByField(callee, 'module');
  3466. callee = getChildByField(callee, 'fun');
  3467. }
  3468. if (callee?.type === 'atom') {
  3469. const fnBare = erlAtom(callee);
  3470. let calleeName = fnBare;
  3471. const moduleExpr = moduleNode ? getChildByField(moduleNode, 'module') : null;
  3472. if (moduleExpr?.type === 'atom') {
  3473. calleeName = `${erlAtom(moduleExpr)}::${calleeName}`;
  3474. } else if (moduleExpr) {
  3475. // Non-atom module qualifier. `?MODULE:f(X)` targets THIS module —
  3476. // keep the bare name so same-file preference resolves it. Anything
  3477. // else (`Mod:f(X)`) is behaviour-style dynamic dispatch with no
  3478. // static target: emitting the bare name would link an arbitrary
  3479. // same-named function, so stay silent instead.
  3480. const macroName =
  3481. moduleExpr.type === 'macro_call_expr' ? getChildByField(moduleExpr, 'name') : null;
  3482. if (!macroName || getNodeText(macroName, this.source) !== 'MODULE') return;
  3483. }
  3484. this.unresolvedReferences.push({
  3485. fromNodeId: callerId,
  3486. referenceName: calleeName,
  3487. referenceKind: 'calls',
  3488. line,
  3489. column,
  3490. });
  3491. // gen_server dispatch: `gen_server:call(?SERVER, Msg)` /
  3492. // `gen_server:cast(other_mod, Msg)` — a request routes to the TARGET
  3493. // module's handle_call/handle_cast. The target is static when the
  3494. // first argument names a module: ?MODULE or a ?MODULE-defined macro
  3495. // (the self API-wrapper idiom), a bare atom (OTP's `{local, ?MODULE}`
  3496. // convention names a server after its module, so a cross-module
  3497. // registered name reaches that module's handlers — and a registered
  3498. // name matching no module resolves to nothing), or a macro defined
  3499. // as a bare atom. Pid/var/tuple targets stay silent.
  3500. if (
  3501. moduleExpr?.type === 'atom' &&
  3502. erlAtom(moduleExpr) === 'gen_server' &&
  3503. (fnBare === 'call' || fnBare === 'cast' || fnBare === 'send_request')
  3504. ) {
  3505. const argsNode = getChildByField(node, 'args');
  3506. const target = argsNode?.namedChild(0) ?? null;
  3507. const targetModule = target ? this.resolveErlangGenServerTarget(target) : null;
  3508. if (targetModule) {
  3509. this.unresolvedReferences.push({
  3510. fromNodeId: callerId,
  3511. referenceName: `${targetModule}::${fnBare === 'cast' ? 'handle_cast' : 'handle_call'}`,
  3512. referenceKind: 'calls',
  3513. line,
  3514. column,
  3515. });
  3516. }
  3517. }
  3518. // MFA-in-argument dispatch: the spawn/apply family names its real
  3519. // callee in ARGUMENT position — `proc_lib:spawn_link(?MODULE,
  3520. // request_process, [Req, Env, Middlewares])` — so the walker above
  3521. // sees only the spawn itself and the spawned function ends up with
  3522. // zero callers (measured on cowboy: request_process had no incoming
  3523. // edges and the agent Read the file to find it). When the (Module,
  3524. // Function) pair is static, lift it as a call edge. The pair is
  3525. // found positionally-agnostically (first adjacent module-atom/
  3526. // ?MODULE + atom pair) so every arity variant works: spawn/3,
  3527. // spawn(Node,M,F,A)/4, timer:apply_after(Time,M,F,A),
  3528. // rpc:call(Node,M,F,A). A var module or fun stays silent.
  3529. const familyKey = moduleExpr?.type === 'atom' ? `${erlAtom(moduleExpr)}:${fnBare}` : fnBare;
  3530. if (ERLANG_MFA_CALLS.has(familyKey)) {
  3531. const argsNode = getChildByField(node, 'args');
  3532. const argExprs = argsNode ? argsNode.namedChildren : [];
  3533. for (let i = 0; i + 1 < argExprs.length; i++) {
  3534. const m = argExprs[i]!;
  3535. const f = argExprs[i + 1]!;
  3536. if (f.type !== 'atom') continue;
  3537. const isLocalModule =
  3538. m.type === 'macro_call_expr' &&
  3539. getChildByField(m, 'name') !== null &&
  3540. getNodeText(getChildByField(m, 'name')!, this.source) === 'MODULE';
  3541. if (m.type !== 'atom' && !isLocalModule) continue;
  3542. this.unresolvedReferences.push({
  3543. fromNodeId: callerId,
  3544. referenceName: isLocalModule ? erlAtom(f) : `${erlAtom(m)}::${erlAtom(f)}`,
  3545. referenceKind: 'calls',
  3546. line: f.startPosition.row + 1,
  3547. column: f.startPosition.column,
  3548. });
  3549. break;
  3550. }
  3551. }
  3552. }
  3553. return;
  3554. }
  3555. if (node.type === 'internal_fun' || node.type === 'external_fun') {
  3556. const funNode = getChildByField(node, 'fun');
  3557. if (funNode?.type !== 'atom') return; // fun Mod:F/A with var parts — dynamic
  3558. let refName = erlAtom(funNode);
  3559. if (node.type === 'external_fun') {
  3560. const moduleWrapper = getChildByField(node, 'module');
  3561. const moduleAtom = moduleWrapper ? getChildByField(moduleWrapper, 'name') : null;
  3562. if (moduleAtom?.type !== 'atom') return;
  3563. refName = `${erlAtom(moduleAtom)}::${refName}`;
  3564. }
  3565. this.unresolvedReferences.push({
  3566. fromNodeId: callerId,
  3567. referenceName: refName,
  3568. referenceKind: 'references',
  3569. line,
  3570. column,
  3571. });
  3572. return;
  3573. }
  3574. if (node.type === 'macro_call_expr') {
  3575. // Macro use site → the `-define` constant node. Function-like uses
  3576. // (`?LOG_AUDIT(X)` — args present) are inlined code, so they join the
  3577. // call chain and connect through the macro node to the body's calls
  3578. // (attributed there by handlePpDefine); bare reads (`?TIMEOUT`) are
  3579. // `references`, answering "where is this macro used" without
  3580. // polluting call paths. Compiler-predefined macros carry no
  3581. // definition to link. The use site's ARGUMENTS are children and keep
  3582. // walking, so a call nested in `?assertEqual(ok, do_thing())` still
  3583. // attributes to the enclosing function.
  3584. const macroName = getChildByField(node, 'name');
  3585. if (!macroName) return;
  3586. const name = getNodeText(macroName, this.source);
  3587. if (ERLANG_PREDEFINED_MACROS.has(name)) return;
  3588. this.unresolvedReferences.push({
  3589. fromNodeId: callerId,
  3590. referenceName: name,
  3591. referenceKind: getChildByField(node, 'args') ? 'calls' : 'references',
  3592. line,
  3593. column,
  3594. });
  3595. return;
  3596. }
  3597. // record_expr / record_update_expr / record_index_expr / record_field_expr
  3598. const recordName = getChildByField(node, 'name');
  3599. const recordAtom = recordName?.type === 'record_name' ? getChildByField(recordName, 'name') : null;
  3600. if (recordAtom?.type === 'atom') {
  3601. this.unresolvedReferences.push({
  3602. fromNodeId: callerId,
  3603. referenceName: erlAtom(recordAtom),
  3604. referenceKind: 'references',
  3605. line,
  3606. column,
  3607. });
  3608. }
  3609. return;
  3610. }
  3611. // Ruby `call` nodes use `receiver` + `method` fields (tree-sitter-ruby), not
  3612. // the `object`/`name`/`function` fields the branches below expect — so
  3613. // without this they fell through to the generic path, which took the
  3614. // receiver as the callee and DROPPED the method name: `lg.log()` produced a
  3615. // `calls` ref to `lg` (unresolvable) and no method edge was ever recorded,
  3616. // so a Ruby method's callers/impact were invisible (#1108 follow-up). Build
  3617. // `receiver.method` so the resolver — and local-variable type inference —
  3618. // can link it; `Foo.new` stays an instantiation.
  3619. if (this.language === 'ruby' && (node.type === 'call' || node.type === 'method_call')) {
  3620. const methodNode = getChildByField(node, 'method');
  3621. const methodName = methodNode ? getNodeText(methodNode, this.source) : '';
  3622. if (!methodName) return; // operator/element-reference call with no method name
  3623. const receiverNode = getChildByField(node, 'receiver');
  3624. const line = node.startPosition.row + 1;
  3625. const column = node.startPosition.column;
  3626. if (!receiverNode) {
  3627. // Bare `foo(...)` — just the method name (unchanged behavior).
  3628. this.unresolvedReferences.push({ fromNodeId: callerId, referenceName: methodName, referenceKind: 'calls', line, column });
  3629. return;
  3630. }
  3631. const receiverName = getNodeText(receiverNode, this.source);
  3632. // `Foo.new` / `Foo::Bar.new` is construction — emit an `instantiates` ref to
  3633. // the class (last `::` segment), preserving the "what creates X" edge.
  3634. if (methodName === 'new') {
  3635. const className = receiverName.includes('::')
  3636. ? receiverName.slice(receiverName.lastIndexOf('::') + 2)
  3637. : receiverName;
  3638. if (/^[A-Z]/.test(className)) {
  3639. this.unresolvedReferences.push({ fromNodeId: callerId, referenceName: className, referenceKind: 'instantiates', line, column });
  3640. return;
  3641. }
  3642. }
  3643. const SKIP_RECEIVERS = new Set(['self', 'super']);
  3644. const skip = SKIP_RECEIVERS.has(receiverName);
  3645. this.unresolvedReferences.push({
  3646. fromNodeId: callerId,
  3647. referenceName: skip ? methodName : `${receiverName}.${methodName}`,
  3648. referenceKind: 'calls',
  3649. line,
  3650. column,
  3651. });
  3652. // A capitalized (constant) receiver — `Foo.bar`, a class/module method call
  3653. // — is itself a dependency on that constant; emit a `references` ref so a
  3654. // class used only via its class methods still records a dependent (the edge
  3655. // the old receiver-only callee happened to provide, now made explicit).
  3656. if (!skip && receiverNode.type === 'constant') {
  3657. this.unresolvedReferences.push({
  3658. fromNodeId: callerId,
  3659. referenceName: receiverName,
  3660. referenceKind: 'references',
  3661. line: receiverNode.startPosition.row + 1,
  3662. column: receiverNode.startPosition.column,
  3663. });
  3664. }
  3665. return;
  3666. }
  3667. // ArkTS build()-DSL handling. Three shapes carry UI-attribute chains, and
  3668. // all of their attribute names are emitted with a LEADING DOT
  3669. // (`.titleStyle`, `.width`) — an impossible identifier that routes them to
  3670. // a dedicated matcher strategy resolving ONLY to decorator-marked
  3671. // attribute helpers (`@Extend`/`@Styles`/`@AnimatableExtend`/`@Builder`
  3672. // functions). Bare names would go through global name matching, where
  3673. // framework attributes (`.width`, `.fontSize`, appearing on nearly every
  3674. // UI line) hit arbitrary same-named symbols — measured on the OpenHarmony
  3675. // samples monorepo, that produced 36k wrong edges (17% of all calls),
  3676. // including single properties with 3,400+ false callers.
  3677. //
  3678. // 1. `Column({space:8}) { … }.height('100%')` — ONE
  3679. // arkui_component_expression: `function:` = the component, chained
  3680. // attributes as repeated `property:`/`arguments:` field pairs.
  3681. // The component ref (`Column`, `TodoRow`) stays a PLAIN name — it
  3682. // resolves to the child `@Component struct`, giving the parent→child
  3683. // component-tree edge the way JSX children do for React.
  3684. // 2. `Image(x).width(10).onClick(this.f)` — ordinary nested
  3685. // call_expressions whose `function:` is a member_expression chained
  3686. // on a CALL RESULT (never a named receiver, so `svc.save()` /
  3687. // `this.vm.load()` are untouched and fall through to the generic
  3688. // paths below).
  3689. // 3. A nested component whose chain starts on the line AFTER its
  3690. // closing `}` inside arkui_children — the grammar detaches the chain
  3691. // into sibling `leading_dot_expression(identifier)` +
  3692. // `parenthesized_expression(args)` statement pairs; reassemble from
  3693. // the siblings.
  3694. //
  3695. // `.onXxx(this.handler)` METHOD-REFERENCE bindings (no call parens, so
  3696. // nothing else records them) additionally emit a call ref to the bare
  3697. // handler name — same-class resolution links the tap→handler hop.
  3698. // Arrow-function handlers need nothing: their bodies' calls already
  3699. // attribute to the enclosing build(). Children/argument subtrees are
  3700. // still walked by the caller, so nested components extract normally.
  3701. if (this.language === 'arkts') {
  3702. const emitAttr = (nameNode: SyntaxNode): void => {
  3703. const attrName = getNodeText(nameNode, this.source);
  3704. if (!attrName) return;
  3705. this.unresolvedReferences.push({
  3706. fromNodeId: callerId,
  3707. referenceName: '.' + attrName,
  3708. referenceKind: 'calls',
  3709. line: nameNode.startPosition.row + 1,
  3710. column: nameNode.startPosition.column,
  3711. });
  3712. };
  3713. // Emit `handler` for each bare `this.handler` among an on-attribute's
  3714. // arguments.
  3715. const emitThisHandlers = (args: SyntaxNode | null): void => {
  3716. if (!args) return;
  3717. for (let j = 0; j < args.namedChildCount; j++) {
  3718. const arg = args.namedChild(j);
  3719. if (arg?.type !== 'member_expression') continue;
  3720. const obj = getChildByField(arg, 'object');
  3721. const prop = getChildByField(arg, 'property');
  3722. if (obj?.type === 'this' && prop) {
  3723. this.unresolvedReferences.push({
  3724. fromNodeId: callerId,
  3725. referenceName: getNodeText(prop, this.source),
  3726. referenceKind: 'calls',
  3727. line: arg.startPosition.row + 1,
  3728. column: arg.startPosition.column,
  3729. });
  3730. }
  3731. }
  3732. };
  3733. // Shape 1: arkui_component_expression with property/arguments pairs.
  3734. if (node.type === 'arkui_component_expression') {
  3735. const componentField = getChildByField(node, 'function');
  3736. if (componentField && componentField.type === 'identifier') {
  3737. this.unresolvedReferences.push({
  3738. fromNodeId: callerId,
  3739. referenceName: getNodeText(componentField, this.source),
  3740. referenceKind: 'calls',
  3741. line: node.startPosition.row + 1,
  3742. column: node.startPosition.column,
  3743. });
  3744. }
  3745. for (let i = 0; i < node.childCount; i++) {
  3746. const child = node.child(i);
  3747. if (!child || child.type !== 'property_identifier') continue;
  3748. emitAttr(child);
  3749. if (/^on[A-Z]/.test(getNodeText(child, this.source))) {
  3750. // The attribute's arguments node is the next `arguments`-typed
  3751. // child before the following attribute name.
  3752. let args: SyntaxNode | null = null;
  3753. for (let k = i + 1; k < node.childCount; k++) {
  3754. const next = node.child(k);
  3755. if (!next) continue;
  3756. if (next.type === 'property_identifier') break;
  3757. if (next.type === 'arguments') {
  3758. args = next;
  3759. break;
  3760. }
  3761. }
  3762. emitThisHandlers(args);
  3763. }
  3764. }
  3765. return;
  3766. }
  3767. // Shape 2: fluent chain on a call result —
  3768. // call_expression(function: member_expression(object: <call>)), or the
  3769. // grammar's DSL-specific arkui_dsl_decorator_member_expression (same
  3770. // object/property fields; produced e.g. by `Column() { … }.alignItems(x)`
  3771. // in some chain positions — it ONLY occurs in attribute chains).
  3772. if (node.type === 'call_expression') {
  3773. const fn = getChildByField(node, 'function');
  3774. if (fn?.type === 'member_expression' || fn?.type === 'arkui_dsl_decorator_member_expression') {
  3775. const obj = getChildByField(fn, 'object');
  3776. const prop = getChildByField(fn, 'property');
  3777. if (
  3778. prop &&
  3779. (fn.type === 'arkui_dsl_decorator_member_expression' ||
  3780. obj?.type === 'call_expression' ||
  3781. obj?.type === 'arkui_component_expression')
  3782. ) {
  3783. emitAttr(prop);
  3784. if (/^on[A-Z]/.test(getNodeText(prop, this.source))) {
  3785. emitThisHandlers(getChildByField(node, 'arguments'));
  3786. }
  3787. return;
  3788. }
  3789. }
  3790. // The INNERMOST call of a proper-form detached chain
  3791. // (`.alignItems(x).layoutWeight(1)…` under a leading_dot_expression)
  3792. // has a BARE IDENTIFIER function — the leading dot was consumed by
  3793. // the wrapper, so it masquerades as a plain `alignItems(...)` call.
  3794. // Walk up the member/call alternation; topping out at
  3795. // leading_dot_expression means the dot belongs to this chain.
  3796. if (fn?.type === 'identifier') {
  3797. let p: SyntaxNode | null = node.parent;
  3798. while (p && (p.type === 'member_expression' || p.type === 'call_expression')) {
  3799. p = p.parent;
  3800. }
  3801. if (p?.type === 'leading_dot_expression') {
  3802. emitAttr(fn);
  3803. if (/^on[A-Z]/.test(getNodeText(fn, this.source))) {
  3804. emitThisHandlers(getChildByField(node, 'arguments'));
  3805. }
  3806. return;
  3807. }
  3808. }
  3809. // Not a chained attribute — fall through to the generic call paths.
  3810. }
  3811. // Shape 3: detached chain segment — leading_dot_expression whose only
  3812. // named child is a bare identifier; its arguments sit in the NEXT
  3813. // sibling statement as a parenthesized_expression.
  3814. if (node.type === 'leading_dot_expression') {
  3815. const only = node.namedChildCount === 1 ? node.namedChild(0) : null;
  3816. if (only && only.type === 'identifier') {
  3817. emitAttr(only);
  3818. if (/^on[A-Z]/.test(getNodeText(only, this.source))) {
  3819. const stmt = node.parent; // expression_statement
  3820. const nextStmt = stmt?.nextNamedSibling;
  3821. const paren = nextStmt?.namedChild(0);
  3822. if (paren?.type === 'parenthesized_expression') {
  3823. emitThisHandlers(paren);
  3824. }
  3825. }
  3826. }
  3827. // The proper form (child is a call_expression chain, as inside
  3828. // `@Extend` bodies) needs nothing here — the walker descends into it
  3829. // and the inner call_expressions take the paths above.
  3830. return;
  3831. }
  3832. }
  3833. // Get the function/method being called
  3834. let calleeName = '';
  3835. // Java/Kotlin method_invocation has 'object' + 'name' fields instead of 'function'
  3836. // PHP member_call_expression has 'object' + 'name', scoped_call_expression has 'scope' + 'name'
  3837. const nameField = getChildByField(node, 'name');
  3838. const objectField = getChildByField(node, 'object') || getChildByField(node, 'scope');
  3839. if (nameField && objectField && (node.type === 'method_invocation' || node.type === 'member_call_expression' || node.type === 'scoped_call_expression')) {
  3840. // Method call with explicit receiver: receiver.method() / $receiver->method() / ClassName::method()
  3841. const methodName = getNodeText(nameField, this.source);
  3842. // Java `this.userbo.toLogin2()` parses as method_invocation(object=field_access(this, userbo)).
  3843. // Without unwrapping, receiverName is `this.userbo` and the name-matcher's
  3844. // single-dot receiver regex fails. Pull out the immediate field after `this.`
  3845. // so the receiver is the field name (`userbo`), which the resolver can then
  3846. // look up in the enclosing class's field declarations.
  3847. // PHP static-factory fluent chain: `Cls::for($x)->method()` — the receiver
  3848. // is itself a static call, so resolution must infer the method's class
  3849. // from what `Cls::for` RETURNS (its `: self` / `: static` / `: Type`),
  3850. // #608 (mirrors the C++ chain fix in #645). Encode `<Cls::factory>().<method>`;
  3851. // the `().` marker lets the PHP resolver split it. The receiver text
  3852. // (`Cls::for('x')`) carries the args, so without this it degrades to an
  3853. // unresolvable string and the call edge is dropped.
  3854. if (methodName && this.language === 'php' && objectField.type === 'scoped_call_expression') {
  3855. const innerScope = getChildByField(objectField, 'scope');
  3856. const innerName = getChildByField(objectField, 'name');
  3857. if (innerScope && innerName) {
  3858. calleeName = `${getNodeText(innerScope, this.source)}::${getNodeText(innerName, this.source)}().${methodName}`;
  3859. } else {
  3860. calleeName = methodName;
  3861. }
  3862. if (calleeName) {
  3863. this.unresolvedReferences.push({
  3864. fromNodeId: callerId,
  3865. referenceName: calleeName,
  3866. referenceKind: 'calls',
  3867. line: node.startPosition.row + 1,
  3868. column: node.startPosition.column,
  3869. });
  3870. }
  3871. return;
  3872. }
  3873. // Java static-factory / fluent chain: `Foo.getInstance().bar()` — the
  3874. // receiver is itself a method call, so resolution must infer bar's class
  3875. // from what `Foo.getInstance` RETURNS (its declared return type), the
  3876. // #645/#608 mechanism. Encode `<inner-receiver>.<inner-method>().<method>`;
  3877. // the `().` marker lets the Java chain resolver split it, and normalizing to
  3878. // empty parens drops any factory args (`Foo.create(cfg).bar()`) that would
  3879. // otherwise leave a `(cfg)` in the receiver text and break the split.
  3880. if (
  3881. methodName &&
  3882. this.language === 'java' &&
  3883. objectField.type === 'method_invocation'
  3884. ) {
  3885. const innerObj = getChildByField(objectField, 'object');
  3886. const innerName = getChildByField(objectField, 'name');
  3887. if (innerObj && innerName) {
  3888. calleeName = `${getNodeText(innerObj, this.source)}.${getNodeText(innerName, this.source)}().${methodName}`;
  3889. this.unresolvedReferences.push({
  3890. fromNodeId: callerId,
  3891. referenceName: calleeName,
  3892. referenceKind: 'calls',
  3893. line: node.startPosition.row + 1,
  3894. column: node.startPosition.column,
  3895. });
  3896. return;
  3897. }
  3898. }
  3899. let receiverName: string;
  3900. if (objectField.type === 'field_access') {
  3901. const inner = getChildByField(objectField, 'object');
  3902. const fld = getChildByField(objectField, 'field');
  3903. if (inner && fld && (inner.type === 'this' || inner.type === 'this_expression')) {
  3904. receiverName = getNodeText(fld, this.source);
  3905. } else {
  3906. receiverName = getNodeText(objectField, this.source);
  3907. }
  3908. } else {
  3909. receiverName = getNodeText(objectField, this.source);
  3910. }
  3911. // Strip PHP $ prefix from variable names
  3912. receiverName = receiverName.replace(/^\$/, '');
  3913. if (methodName) {
  3914. // Skip self/this/parent/static receivers — they don't aid resolution
  3915. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super', 'parent', 'static']);
  3916. if (SKIP_RECEIVERS.has(receiverName)) {
  3917. calleeName = methodName;
  3918. } else {
  3919. calleeName = `${receiverName}.${methodName}`;
  3920. }
  3921. }
  3922. } else if (node.type === 'message_expression') {
  3923. // ObjC message expressions emit one `method` field child per selector
  3924. // keyword: `[obj a:1 b:2 c:3]` has three `method=identifier` siblings.
  3925. // Joining them with `:` reconstructs the full selector and matches the
  3926. // multi-part selector names produced by the ObjC method_definition
  3927. // extractor (`extractObjcMethodName` in languages/objc.ts). Without this
  3928. // join, multi-keyword call sites only emitted the first keyword and never
  3929. // resolved to their target methods (e.g. `GET:parameters:headers:...` had
  3930. // zero callers despite obviously being called).
  3931. const methodKeywords: string[] = [];
  3932. for (let i = 0; i < node.namedChildCount; i++) {
  3933. if (node.fieldNameForNamedChild(i) === 'method') {
  3934. const kw = node.namedChild(i);
  3935. if (kw) methodKeywords.push(getNodeText(kw, this.source));
  3936. }
  3937. }
  3938. if (methodKeywords.length > 0) {
  3939. // A selector keyword takes a `:` when it has an argument. A SINGLE
  3940. // keyword can be unary (`[c reset]` → `reset`) OR take one argument
  3941. // (`[c storeImage:k]` → `storeImage:`) — distinguished by whether the
  3942. // message has a `:` token. Without this, every single-argument message
  3943. // (the most common form: `addObject:`, `storeImage:`, …) was named
  3944. // without the colon and never matched its `storeImage:` method.
  3945. let hasColon = false;
  3946. for (let i = 0; i < node.childCount; i++) {
  3947. if (node.child(i)?.type === ':') { hasColon = true; break; }
  3948. }
  3949. const methodName: string = hasColon
  3950. ? methodKeywords.map((k) => `${k}:`).join('')
  3951. : (methodKeywords[0] as string);
  3952. const receiverField = getChildByField(node, 'receiver');
  3953. const SKIP_RECEIVERS = new Set(['self', 'super']);
  3954. if (receiverField && receiverField.type !== 'message_expression') {
  3955. const receiverName = getNodeText(receiverField, this.source);
  3956. if (receiverName && !SKIP_RECEIVERS.has(receiverName)) {
  3957. calleeName = `${receiverName}.${methodName}`;
  3958. // A CLASS-message receiver (`[SDImageCache alloc]`,
  3959. // `[SDImageCache sharedCache]`) is a capitalized class name. The
  3960. // call resolves the method (`alloc`/`sharedCache`), but the CLASS
  3961. // itself — whose @interface lives in the header — would otherwise
  3962. // never be referenced. Emit a `references` edge to it so a class
  3963. // used only via class messages (alloc/init, singletons, factories)
  3964. // and its header record a dependent.
  3965. if (/^[A-Z][A-Za-z0-9_]*$/.test(receiverName)) {
  3966. this.unresolvedReferences.push({
  3967. fromNodeId: callerId,
  3968. referenceName: receiverName,
  3969. referenceKind: 'references',
  3970. line: receiverField.startPosition.row + 1,
  3971. column: receiverField.startPosition.column,
  3972. });
  3973. }
  3974. } else {
  3975. calleeName = methodName;
  3976. }
  3977. } else if (receiverField && receiverField.type === 'message_expression' && /^\w+$/.test(methodName)) {
  3978. // Chained message send `[[Foo create] doIt]` — the receiver is itself a
  3979. // class message. Recover the inner `Class.selector` and encode
  3980. // `Class.selector().doIt` so resolution infers doIt's class from what
  3981. // `Class.selector` RETURNS (#645/#608). Only a CLASS-factory chain
  3982. // (capitalized inner receiver); a unary outer selector is required
  3983. // because the chain resolver's method part is `\w+` (no `:`). An
  3984. // instance chain (`[[obj foo] bar]`, lowercase inner) stays bare.
  3985. const innerRecv = getChildByField(receiverField, 'receiver');
  3986. const innerRecvName = innerRecv ? getNodeText(innerRecv, this.source) : '';
  3987. if (innerRecv?.type === 'identifier' && /^[A-Z]/.test(innerRecvName)) {
  3988. const innerKw: string[] = [];
  3989. for (let i = 0; i < receiverField.namedChildCount; i++) {
  3990. if (receiverField.fieldNameForNamedChild(i) === 'method') {
  3991. const kw = receiverField.namedChild(i);
  3992. if (kw) innerKw.push(getNodeText(kw, this.source));
  3993. }
  3994. }
  3995. let innerColon = false;
  3996. for (let i = 0; i < receiverField.childCount; i++) {
  3997. if (receiverField.child(i)?.type === ':') { innerColon = true; break; }
  3998. }
  3999. const innerSelector = innerColon ? innerKw.map((k) => `${k}:`).join('') : innerKw[0];
  4000. calleeName = innerSelector ? `${innerRecvName}.${innerSelector}().${methodName}` : methodName;
  4001. } else {
  4002. calleeName = methodName;
  4003. }
  4004. } else {
  4005. calleeName = methodName;
  4006. }
  4007. }
  4008. } else {
  4009. const func = getChildByField(node, 'function') || node.namedChild(0);
  4010. if (func) {
  4011. if (func.type === 'member_expression' || func.type === 'attribute' || func.type === 'selector_expression' || func.type === 'navigation_expression' || func.type === 'field_expression') {
  4012. // Method call: obj.method() or obj.field.method()
  4013. // Go uses selector_expression with 'field', JS/TS uses member_expression with 'property'
  4014. // Kotlin uses navigation_expression with navigation_suffix > simple_identifier
  4015. // C/C++ use field_expression for both `obj.method()` and `ptr->method()`
  4016. let property = getChildByField(func, 'property') || getChildByField(func, 'field');
  4017. if (!property) {
  4018. const child1 = func.namedChild(1);
  4019. // Kotlin: navigation_suffix wraps the method name — extract simple_identifier from it
  4020. if (child1?.type === 'navigation_suffix') {
  4021. property = child1.namedChildren.find((c: SyntaxNode) => c.type === 'simple_identifier') ?? child1;
  4022. } else {
  4023. property = child1;
  4024. }
  4025. }
  4026. if (property) {
  4027. const methodName = getNodeText(property, this.source);
  4028. // Include receiver name for qualified resolution (e.g., console.print → "console.print")
  4029. // This helps the resolver distinguish method calls from bare function calls
  4030. // (e.g., Python's console.print() vs builtin print())
  4031. // Skip self/this/cls as they don't aid resolution
  4032. const receiver =
  4033. getChildByField(func, 'object') ||
  4034. getChildByField(func, 'operand') ||
  4035. getChildByField(func, 'argument') ||
  4036. func.namedChild(0);
  4037. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super']);
  4038. if (receiver && (receiver.type === 'identifier' || receiver.type === 'simple_identifier' || receiver.type === 'field_identifier')) {
  4039. const receiverName = getNodeText(receiver, this.source);
  4040. if (!SKIP_RECEIVERS.has(receiverName)) {
  4041. calleeName = `${receiverName}.${methodName}`;
  4042. } else {
  4043. calleeName = methodName;
  4044. }
  4045. } else if (
  4046. (this.language === 'cpp' ||
  4047. this.language === 'c' ||
  4048. this.language === 'kotlin' ||
  4049. this.language === 'swift' ||
  4050. this.language === 'rust' ||
  4051. this.language === 'go' ||
  4052. this.language === 'scala') &&
  4053. receiver &&
  4054. receiver.type === 'call_expression'
  4055. ) {
  4056. // Receiver that is itself a call — `Foo::instance().bar()`,
  4057. // `openSession()->run()`, `mgr.view().render()` (C/C++),
  4058. // `Foo.getInstance().bar()` (Kotlin) / `Foo.make().draw()` (Swift),
  4059. // `Foo::new().bar()` (Rust), or `New().Method()` (Go). Keep the inner
  4060. // call so resolution can infer bar()'s class from what the inner call
  4061. // RETURNS (#645/#608). Encode as `<innerCallee>().<method>`; the `().`
  4062. // marker never appears in an ordinary ref, so the resolver can detect
  4063. // and split it. Other languages keep the bare-name behavior below.
  4064. let innerCallee: string;
  4065. let reencode: boolean;
  4066. if (this.language === 'kotlin' || this.language === 'swift') {
  4067. // tree-sitter-kotlin/swift expose the inner callee as the
  4068. // call_expression's first named child (a navigation_expression
  4069. // `Foo.getInstance`, or a bare identifier for a free/constructor call).
  4070. const innerNav = receiver.namedChild(0);
  4071. innerCallee = innerNav ? getNodeText(innerNav, this.source).replace(/\s+/g, '') : '';
  4072. // Only re-encode a CLASS / companion-factory / constructor chain,
  4073. // whose receiver chain starts with a capitalized type
  4074. // (`Foo.getInstance().bar()`, `Foo().bar()`). An instance chain
  4075. // (`list.filter{}.map{}`) has a lowercase receiver whose type we
  4076. // can't recover here — re-encoding it would only drop the edge (no
  4077. // chain resolution, no bare-name fallback), regressing recall in
  4078. // fluent codebases. Leave those to the bare-name path.
  4079. reencode = /^[A-Z]/.test(innerCallee);
  4080. } else {
  4081. const innerFn = getChildByField(receiver, 'function');
  4082. innerCallee = innerFn
  4083. ? getNodeText(innerFn, this.source).replace(/->/g, '.').replace(/\s+/g, '')
  4084. : '';
  4085. // Rust: only re-encode an associated-function chain
  4086. // (`Foo::new().bar()`), whose inner callee is a path/`scoped_identifier`.
  4087. // Go: only a bare package-level factory chain (`New().Method()`),
  4088. // whose inner callee is an `identifier`. An instance chain
  4089. // (`x.foo().bar()` Rust, `obj.Method().Other()` Go) keeps bare-name —
  4090. // the resolver can't recover a variable's type, so re-encoding would
  4091. // only drop the edge. C/C++ re-encode any inner.
  4092. if (this.language === 'rust') reencode = innerFn?.type === 'scoped_identifier';
  4093. else if (this.language === 'go') reencode = innerFn?.type === 'identifier';
  4094. // Scala: only a companion-factory / case-class-apply chain whose
  4095. // receiver chain starts with a capitalized type (`Foo.create().bar()`,
  4096. // `Foo(args).bar()`). An instance chain (`list.map().filter()`) has a
  4097. // lowercase receiver whose type we can't recover — leave it bare.
  4098. else if (this.language === 'scala') reencode = /^[A-Z]/.test(innerCallee);
  4099. else reencode = !!innerCallee;
  4100. }
  4101. calleeName = reencode ? `${innerCallee}().${methodName}` : methodName;
  4102. } else if (
  4103. this.language === 'cfscript' &&
  4104. receiver &&
  4105. receiver.type === 'member_expression' &&
  4106. /^(variables|this|local|arguments)\.[A-Za-z_][\w]*$/i.test(getNodeText(receiver, this.source))
  4107. ) {
  4108. // CFML scope-prefixed member call — `variables.svc.save()` /
  4109. // `arguments.svc.save()`: the receiver is a component field,
  4110. // injected property, or typed argument reached through one of
  4111. // CFML's file-local scopes. Keep the full receiver chain so
  4112. // resolution can strip the scope prefix and infer the field's
  4113. // component type from its declaration (#1108). Gated to these
  4114. // scope keywords: such calls previously emitted a bare method
  4115. // name, which either failed to resolve or resolved ambiguously.
  4116. calleeName = `${getNodeText(receiver, this.source)}.${methodName}`;
  4117. } else {
  4118. calleeName = methodName;
  4119. }
  4120. }
  4121. } else if (func.type === 'scoped_identifier' || func.type === 'scoped_call_expression') {
  4122. // Scoped call: Module::function()
  4123. calleeName = getNodeText(func, this.source);
  4124. } else if (this.language === 'csharp' && func.type === 'member_access_expression') {
  4125. // C# member call `recv.Method(...)`. When the receiver is itself a call
  4126. // — a chained factory `Foo.Create(args).Bar()` — encode `inner().Bar`
  4127. // with normalized empty parens so resolution can infer Bar's class from
  4128. // what `Foo.Create` RETURNS (#645/#608). A non-call receiver keeps the
  4129. // full member-access text (the existing `recv.Method` behavior).
  4130. const recv = getChildByField(func, 'expression');
  4131. const nameNode = getChildByField(func, 'name');
  4132. const methodName = nameNode ? getNodeText(nameNode, this.source) : '';
  4133. if (recv && recv.type === 'invocation_expression' && methodName) {
  4134. const innerFunc = getChildByField(recv, 'function');
  4135. const innerCallee = innerFunc ? getNodeText(innerFunc, this.source).replace(/\s+/g, '') : '';
  4136. calleeName = innerCallee ? `${innerCallee}().${methodName}` : methodName;
  4137. } else {
  4138. calleeName = getNodeText(func, this.source);
  4139. }
  4140. } else {
  4141. calleeName = getNodeText(func, this.source);
  4142. }
  4143. }
  4144. }
  4145. // Parenthesized type conversions — Go `(*T)(x)` / `(T)(x)` (and a
  4146. // parenthesized callee generally) parse as a call whose "function" is a
  4147. // parenthesized type/expression, so the callee text is the un-resolvable
  4148. // literal `(*T)`. Normalize to the inner name so it resolves to `T` (a real
  4149. // dependency on the converted-to type) instead of dropping on the floor.
  4150. if (calleeName) {
  4151. const conv = calleeName.match(/^\(\s*\*?\s*([A-Za-z_][\w.]*)\s*\)$/);
  4152. if (conv && conv[1]) calleeName = conv[1];
  4153. }
  4154. // C/C++ templated callees — a direct templated call (`fn<T, 256>(args)`,
  4155. // the shape every CUDA kernel-launch site takes once its `<<<…>>>` config
  4156. // is blanked) or a qualified one (`ns::fn<T>(args)`) — carry template
  4157. // arguments in the callee text, which can never match the bare name the
  4158. // function was DEFINED as, so the call edge silently never resolves. Strip
  4159. // them: the same normalization base-class `extends` refs already get
  4160. // (#1043). `operator<`/`operator<<` callees are excluded — their `<` is the
  4161. // operator itself, not a template-argument list.
  4162. if (
  4163. calleeName &&
  4164. calleeName.includes('<') &&
  4165. (this.language === 'cpp' || this.language === 'c') &&
  4166. !calleeName.includes('operator')
  4167. ) {
  4168. calleeName = stripCppTemplateArgs(calleeName);
  4169. }
  4170. // C++ call/launch through a local function pointer: `auto kernel =
  4171. // &flash_fwd_kernel<…>; … kernel<<<grid, block>>>(params);` — the callee
  4172. // is an unresolvable local name. When the same enclosing symbol bound the
  4173. // local from `&fn` (each branch assignment counts), emit the call against
  4174. // every recorded target instead of the local.
  4175. if (calleeName && this.language === 'cpp' && /^[A-Za-z_]\w*$/.test(calleeName)) {
  4176. const targets = this.cppLocalFnPtrs.get(callerId)?.get(calleeName);
  4177. if (targets && targets.size > 0) {
  4178. for (const target of targets) {
  4179. this.unresolvedReferences.push({
  4180. fromNodeId: callerId,
  4181. referenceName: target,
  4182. referenceKind: 'calls',
  4183. line: node.startPosition.row + 1,
  4184. column: node.startPosition.column,
  4185. });
  4186. }
  4187. return;
  4188. }
  4189. }
  4190. if (calleeName) {
  4191. this.unresolvedReferences.push({
  4192. fromNodeId: callerId,
  4193. referenceName: calleeName,
  4194. referenceKind: 'calls',
  4195. line: node.startPosition.row + 1,
  4196. column: node.startPosition.column,
  4197. });
  4198. }
  4199. }
  4200. /**
  4201. * `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  4202. * emit an `instantiates` reference to the class name. The resolver
  4203. * then links it to the class node, producing the `instantiates`
  4204. * edge that powers "what creates instances of X" queries.
  4205. *
  4206. * Children are still walked so nested calls inside the constructor
  4207. * arguments (`new Foo(bar())`) get their own `calls` references.
  4208. */
  4209. /**
  4210. * VB.NET `New Invoice(1)` is syntactically ambiguous between constructing
  4211. * Invoice with an argument and allocating an Invoice array of bound 1; the
  4212. * grammar parses the parenthesized form as array_creation_expression. A
  4213. * user-defined type with no `{...}` array initializer is overwhelmingly a
  4214. * constructor call, so treat it as an instantiation. Predefined element
  4215. * types (`New Byte(1023)`) and brace-initialized forms stay arrays.
  4216. */
  4217. private isVbnetConstructorShapedArrayCreation(node: SyntaxNode): boolean {
  4218. if (this.language !== 'vbnet' || node.type !== 'array_creation_expression') return false;
  4219. const typeNode = getChildByField(node, 'type');
  4220. if (!typeNode || typeNode.type === 'predefined_type' || typeNode.type === 'array_type') return false;
  4221. for (const child of node.namedChildren) {
  4222. if (child?.type === 'array_initializer') return false;
  4223. }
  4224. return true;
  4225. }
  4226. private extractInstantiation(node: SyntaxNode): void {
  4227. if (this.nodeStack.length === 0) return;
  4228. const fromId = this.nodeStack[this.nodeStack.length - 1];
  4229. if (!fromId) return;
  4230. // The class name is in the `constructor`/`type`/first-named-child
  4231. // depending on grammar.
  4232. const ctor =
  4233. getChildByField(node, 'constructor') ||
  4234. getChildByField(node, 'type') ||
  4235. getChildByField(node, 'name') ||
  4236. node.namedChild(0);
  4237. if (!ctor) return;
  4238. // Go composite literals: `Widget{...}` (same package) and `pkga.Widget{...}`
  4239. // (cross-package). Only a directly-named struct type is a meaningful
  4240. // instantiation target — skip slice/map/array literals (`[]T{}`,
  4241. // `map[K]V{}`) whose `type` field is a composite type, not a named type.
  4242. // Unlike `new ns.Foo()`, KEEP the package qualifier (`pkga.Widget`) so the
  4243. // Go cross-package resolver can disambiguate it to the right package's type.
  4244. if (node.type === 'composite_literal') {
  4245. if (ctor.type !== 'type_identifier' && ctor.type !== 'qualified_type') return;
  4246. let goType = getNodeText(ctor, this.source).trim();
  4247. const brIdx = goType.indexOf('['); // strip Go generic args: `Box[T]{}` -> `Box`
  4248. if (brIdx > 0) goType = goType.slice(0, brIdx).trim();
  4249. if (goType) {
  4250. this.unresolvedReferences.push({
  4251. fromNodeId: fromId,
  4252. referenceName: goType,
  4253. referenceKind: 'instantiates',
  4254. line: node.startPosition.row + 1,
  4255. column: node.startPosition.column,
  4256. });
  4257. }
  4258. return;
  4259. }
  4260. // Scala: `new Monoid[Int] { ... }` — the constructor is a `generic_type`
  4261. // (or qualified `stable_type_identifier`) using `[...]` type args, which the
  4262. // generic `<...>` strip below misses. Unwrap to the base type name.
  4263. if (node.type === 'instance_expression') {
  4264. const name = scalaBaseTypeName(ctor, this.source);
  4265. if (name) {
  4266. this.unresolvedReferences.push({
  4267. fromNodeId: fromId,
  4268. referenceName: name,
  4269. referenceKind: 'instantiates',
  4270. line: node.startPosition.row + 1,
  4271. column: node.startPosition.column,
  4272. });
  4273. }
  4274. return;
  4275. }
  4276. let className = getNodeText(ctor, this.source);
  4277. // Strip type-argument suffix first: `new Map<K, V>()` would
  4278. // otherwise produce className 'Map<K, V>' (the constructor
  4279. // field is a `generic_type` node) and resolution would fail
  4280. // because no class is named with the angle-bracket suffix.
  4281. const ltIdx = className.indexOf('<');
  4282. if (ltIdx > 0) className = className.slice(0, ltIdx);
  4283. // VB.NET spells generics with parentheses: `New List(Of String)` /
  4284. // `New Dictionary(Of K, V)(cap)` — strip from the `(` so the bare
  4285. // type name is what resolution matches.
  4286. if (this.language === 'vbnet') {
  4287. const parenIdx = className.indexOf('(');
  4288. if (parenIdx > 0) className = className.slice(0, parenIdx);
  4289. }
  4290. // For namespaced/qualified constructors (`new ns.Foo()`,
  4291. // `new ns::Foo()`) keep the trailing identifier — that's what
  4292. // matches a class node in the index.
  4293. const lastDot = Math.max(
  4294. className.lastIndexOf('.'),
  4295. className.lastIndexOf('::')
  4296. );
  4297. if (lastDot >= 0) className = className.slice(lastDot + 1).replace(/^[:.]/, '');
  4298. className = className.trim();
  4299. if (className) {
  4300. this.unresolvedReferences.push({
  4301. fromNodeId: fromId,
  4302. referenceName: className,
  4303. referenceKind: 'instantiates',
  4304. line: node.startPosition.row + 1,
  4305. column: node.startPosition.column,
  4306. });
  4307. }
  4308. }
  4309. /**
  4310. * Is this C++ `declaration` a stack/direct-initialization object construction
  4311. * that invokes a constructor — `Calculator calc(0)` (direct-init) or
  4312. * `Widget w{1, 2}` (brace-init) — as opposed to a plain variable or a
  4313. * function declaration? Used to emit an `instantiates` edge for the
  4314. * call-less construction syntax (#1035); heap `new T(...)` is handled
  4315. * separately by INSTANTIATION_KINDS.
  4316. *
  4317. * Two signals, both required:
  4318. * - the `type` field is a class-like NAMED type (`type_identifier`,
  4319. * `template_type`, or `qualified_identifier`). Primitives (`int x(0)`),
  4320. * `auto` (`placeholder_type_specifier` — that form always carries a real
  4321. * `call_expression`, already handled), and sized specifiers are excluded —
  4322. * they construct no class; and
  4323. * - a declarator carries constructor arguments: an `init_declarator` whose
  4324. * `value` is an `argument_list` (`(args)`) or `initializer_list` (`{args}`).
  4325. * This skips default construction `Calculator c;` (no value) and the
  4326. * most-vexing-parse `Calculator c();` (a bodyless `function_declarator`,
  4327. * a function decl — not a construction).
  4328. */
  4329. private isCppStackConstruction(node: SyntaxNode): boolean {
  4330. const typeNode = getChildByField(node, 'type');
  4331. if (
  4332. !typeNode ||
  4333. (typeNode.type !== 'type_identifier' &&
  4334. typeNode.type !== 'template_type' &&
  4335. typeNode.type !== 'qualified_identifier')
  4336. ) {
  4337. return false;
  4338. }
  4339. for (let i = 0; i < node.namedChildCount; i++) {
  4340. const child = node.namedChild(i);
  4341. if (child?.type !== 'init_declarator') continue;
  4342. const value = getChildByField(child, 'value');
  4343. if (value && (value.type === 'argument_list' || value.type === 'initializer_list')) {
  4344. return true;
  4345. }
  4346. }
  4347. return false;
  4348. }
  4349. /**
  4350. * Static-member / value-read pass. A type/enum/class used only via a member
  4351. * VALUE — `Enum.value`, `Type.CONST`, `Colors.red`, `Foo::BAR` — recorded no
  4352. * edge, because the body walker only handled CALLS (`Type.method()`). So a
  4353. * type referenced only by an enum value or a static field looked like nothing
  4354. * depended on it (the residual frontier across Dart/Java/C#/Swift/Kotlin/PHP).
  4355. * Emit a `references` edge to the capitalized receiver. Gated to languages
  4356. * where types are Capitalized by convention, and skipped when the access is a
  4357. * call's callee (the call extractor already links the method).
  4358. */
  4359. private extractStaticMemberRef(node: SyntaxNode): void {
  4360. if (!STATIC_MEMBER_LANGS.has(this.language)) return;
  4361. if (this.nodeStack.length === 0) return;
  4362. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  4363. if (!ownerId) return;
  4364. // Dart structures member access as an `identifier` + a sibling `selector`,
  4365. // not a single node. A value-read selector (no `argument_part`) whose
  4366. // previous sibling is a capitalized identifier is `Enum.value`.
  4367. if (this.language === 'dart') {
  4368. if (node.type !== 'selector') return;
  4369. if (node.namedChildren.some((c: SyntaxNode) => c.type === 'argument_part')) return;
  4370. const prev = node.previousNamedSibling;
  4371. if (prev?.type === 'identifier' && /^[A-Z][A-Za-z0-9_]*$/.test(prev.text)) {
  4372. this.pushStaticMemberRef(prev.text, ownerId, prev);
  4373. }
  4374. return;
  4375. }
  4376. if (!MEMBER_ACCESS_TYPES.has(node.type)) return;
  4377. // Skip `Type.method()` — the access is the callee of a call, already linked.
  4378. const parent = node.parent;
  4379. if (parent && this.extractor!.callTypes.includes(parent.type)) {
  4380. const callee =
  4381. getChildByField(parent, 'function') ??
  4382. getChildByField(parent, 'method') ??
  4383. parent.namedChild(0);
  4384. if (callee && callee.startIndex === node.startIndex) return;
  4385. }
  4386. // The receiver must be a SIMPLE capitalized identifier — `Type.X`, not the
  4387. // nested `a.B.c` (whose own head member-access is visited separately) nor a
  4388. // lowercase `obj.field` / `pkg.func`.
  4389. const recv =
  4390. getChildByField(node, 'object') ??
  4391. getChildByField(node, 'expression') ??
  4392. getChildByField(node, 'scope') ??
  4393. node.namedChild(0);
  4394. if (!recv) return;
  4395. const t = recv.type;
  4396. if (
  4397. t === 'identifier' || t === 'type_identifier' || t === 'simple_identifier' ||
  4398. t === 'name' || t === 'scoped_type_identifier'
  4399. ) {
  4400. const text = getNodeText(recv, this.source);
  4401. if (/^[A-Z][A-Za-z0-9_]*$/.test(text)) this.pushStaticMemberRef(text, ownerId, recv);
  4402. }
  4403. }
  4404. private pushStaticMemberRef(name: string, ownerId: string, node: SyntaxNode): void {
  4405. this.unresolvedReferences.push({
  4406. fromNodeId: ownerId,
  4407. referenceName: name,
  4408. referenceKind: 'references',
  4409. line: node.startPosition.row + 1,
  4410. column: node.startPosition.column,
  4411. });
  4412. }
  4413. /**
  4414. * Find a `class_body` child of an `object_creation_expression` — the
  4415. * marker for an anonymous class (`new T() { ... }`). Returns the body
  4416. * node so the caller can walk it as the anon class's members.
  4417. */
  4418. private findAnonymousClassBody(node: SyntaxNode): SyntaxNode | null {
  4419. for (let i = 0; i < node.namedChildCount; i++) {
  4420. const child = node.namedChild(i);
  4421. // Java: `class_body`. C# uses the same node kind.
  4422. if (child && (child.type === 'class_body' || child.type === 'declaration_list')) {
  4423. return child;
  4424. }
  4425. }
  4426. return null;
  4427. }
  4428. /**
  4429. * Extract a Java/C# anonymous class — `new T() { ...members }`. Emits a
  4430. * `class` node named `<T$anon@line>`, an `extends` reference to T (so
  4431. * Phase 5.5 interface-impl can bridge), and walks the body so its
  4432. * `method_declaration` members become method nodes under the anon class.
  4433. *
  4434. * Why this matters: without anon-class extraction, the overrides inside
  4435. * a lambda-returned `new T() { @Override int foo(){...} }` are not nodes,
  4436. * so a call through T.foo (the abstract parent method) has no static
  4437. * target — the agent has to Read the file to find the implementation.
  4438. */
  4439. private extractAnonymousClass(node: SyntaxNode, body: SyntaxNode): void {
  4440. if (!this.extractor) return;
  4441. // The instantiated type sits in the same field/position that
  4442. // extractInstantiation reads from. Use the same lookup so the anon
  4443. // class's `extends` target matches the `instantiates` edge.
  4444. const typeNode =
  4445. getChildByField(node, 'constructor') ||
  4446. getChildByField(node, 'type') ||
  4447. getChildByField(node, 'name') ||
  4448. node.namedChild(0);
  4449. let typeName = typeNode ? getNodeText(typeNode, this.source) : 'Object';
  4450. const ltIdx = typeName.indexOf('<');
  4451. if (ltIdx > 0) typeName = typeName.slice(0, ltIdx);
  4452. const lastDot = Math.max(typeName.lastIndexOf('.'), typeName.lastIndexOf('::'));
  4453. if (lastDot >= 0) typeName = typeName.slice(lastDot + 1).replace(/^[:.]/, '');
  4454. typeName = typeName.trim() || 'Object';
  4455. const anonName = `<${typeName}$anon@${node.startPosition.row + 1}>`;
  4456. const classNode = this.createNode('class', anonName, node, {});
  4457. if (!classNode) return;
  4458. // The anonymous class implicitly extends/implements the named type.
  4459. // We can't tell at extraction time whether T is a class or an interface,
  4460. // so emit `extends`. Resolution will still bind T to whatever it is, and
  4461. // Phase 5.5 (which already handles both `extends` and `implements`) will
  4462. // bridge T's methods to the override names found in the anon body.
  4463. this.unresolvedReferences.push({
  4464. fromNodeId: classNode.id,
  4465. referenceName: typeName,
  4466. referenceKind: 'extends',
  4467. line: typeNode?.startPosition.row ?? node.startPosition.row,
  4468. column: typeNode?.startPosition.column ?? node.startPosition.column,
  4469. });
  4470. // Walk the body's children so method_declaration nodes inside become
  4471. // method nodes scoped to the anon class.
  4472. this.nodeStack.push(classNode.id);
  4473. for (let i = 0; i < body.namedChildCount; i++) {
  4474. const child = body.namedChild(i);
  4475. if (child) this.visitNode(child);
  4476. }
  4477. this.nodeStack.pop();
  4478. }
  4479. /**
  4480. * Scan `declNode` and its preceding siblings (within the parent's
  4481. * named children) for decorator nodes, emitting a `decorates`
  4482. * reference from `decoratedId` to each decorator's function name.
  4483. *
  4484. * Why preceding siblings: in TypeScript, `@Foo class Bar {}` parses
  4485. * as an `export_statement` (or top-level wrapper) with the
  4486. * `decorator` as a child *before* the `class_declaration` — so the
  4487. * decorator isn't a child of the class itself. For methods/
  4488. * properties, the decorator IS a direct child of the declaration,
  4489. * so we also scan declNode.namedChildren.
  4490. *
  4491. * Idempotent across grammars: if neither location yields decorators
  4492. * (most non-decorator-using languages), the function is a no-op.
  4493. */
  4494. private extractDecoratorsFor(declNode: SyntaxNode, decoratedId: string): void {
  4495. const consider = (n: SyntaxNode | null): void => {
  4496. if (!n) return;
  4497. // Solidity `modifier_invocation` (unique to that grammar) sits
  4498. // decorator-position in the function header — OUTSIDE the `body:` field
  4499. // the call walker descends — but its body executes around the function
  4500. // via `_;`, so it is a real call-flow hop (`withdraw → onlyOwner →
  4501. // _checkRole` is the canonical audit trace). The same node type carries
  4502. // base-constructor invocations (`constructor() ERC20("T","TOK")`), the
  4503. // constructor-chain hop. Emit `calls`, not `decorates`, so flow
  4504. // traversal rides it.
  4505. if (n.type === 'modifier_invocation') {
  4506. const target = n.namedChild(0);
  4507. const name = target?.type === 'identifier' ? getNodeText(target, this.source) : undefined;
  4508. if (name) {
  4509. this.unresolvedReferences.push({
  4510. fromNodeId: decoratedId,
  4511. referenceName: name,
  4512. referenceKind: 'calls',
  4513. line: n.startPosition.row + 1,
  4514. column: n.startPosition.column,
  4515. });
  4516. }
  4517. return;
  4518. }
  4519. // `marker_annotation` is Java's grammar for arg-less annotations
  4520. // (`@Override`, `@Deprecated`); `attribute` is Swift's grammar for
  4521. // attributes and PROPERTY WRAPPERS (`@objc`, `@Argument`, `@Published`,
  4522. // `@State`). Without these, those usages would be silently skipped.
  4523. if (
  4524. n.type !== 'decorator' &&
  4525. n.type !== 'annotation' &&
  4526. n.type !== 'marker_annotation' &&
  4527. n.type !== 'attribute'
  4528. ) {
  4529. return;
  4530. }
  4531. // Find the leading identifier: skip the `@` punct, unwrap
  4532. // a call_expression if the decorator is invoked with args.
  4533. let target: SyntaxNode | null = null;
  4534. for (let i = 0; i < n.namedChildCount; i++) {
  4535. const child = n.namedChild(i);
  4536. if (!child) continue;
  4537. if (child.type === 'call_expression') {
  4538. const fn = getChildByField(child, 'function') ?? child.namedChild(0);
  4539. if (fn) target = fn;
  4540. if (target) break;
  4541. }
  4542. if (
  4543. child.type === 'identifier' ||
  4544. child.type === 'member_expression' ||
  4545. child.type === 'scoped_identifier' ||
  4546. child.type === 'navigation_expression' ||
  4547. child.type === 'user_type' || // swift attribute → user_type (`@Argument`)
  4548. child.type === 'type_identifier'
  4549. ) {
  4550. target = child;
  4551. break;
  4552. }
  4553. }
  4554. if (!target) return;
  4555. let name = getNodeText(target, this.source);
  4556. const lt = name.indexOf('<'); // strip generic args: `@Argument<T>` → `Argument`
  4557. if (lt > 0) name = name.slice(0, lt);
  4558. const lastDot = Math.max(name.lastIndexOf('.'), name.lastIndexOf('::'));
  4559. if (lastDot >= 0) name = name.slice(lastDot + 1).replace(/^[:.]/, '');
  4560. name = name.trim();
  4561. if (!name) return;
  4562. this.unresolvedReferences.push({
  4563. fromNodeId: decoratedId,
  4564. referenceName: name,
  4565. referenceKind: 'decorates',
  4566. line: n.startPosition.row + 1,
  4567. column: n.startPosition.column,
  4568. });
  4569. };
  4570. // 1. Decorators that are direct children of the declaration
  4571. // (method/property style, also some grammars for class).
  4572. for (let i = 0; i < declNode.namedChildCount; i++) {
  4573. const child = declNode.namedChild(i);
  4574. consider(child);
  4575. // Java/Kotlin/C# put annotations INSIDE a `modifiers` node
  4576. // (`@MyAnno public class X` → class_declaration → modifiers → annotation),
  4577. // so descend into it — otherwise every annotation usage is silently
  4578. // dropped and annotation types show zero dependents.
  4579. if (child && child.type === 'modifiers') {
  4580. for (let j = 0; j < child.namedChildCount; j++) {
  4581. consider(child.namedChild(j));
  4582. }
  4583. }
  4584. }
  4585. // 2. Decorators that are PRECEDING siblings of the declaration
  4586. // inside the parent's children (TypeScript class style).
  4587. // Walk BACKWARDS from the declaration and stop at the first
  4588. // non-decorator sibling — without that stop, decorators
  4589. // belonging to an EARLIER unrelated declaration leak in
  4590. // (e.g. `@A class Foo {} @B class Bar {}` would otherwise
  4591. // attribute @A to Bar).
  4592. //
  4593. // Note on identity: tree-sitter web bindings return fresh JS
  4594. // wrapper objects from `parent`/`namedChild` navigation, so
  4595. // `sibling === declNode` is unreliable — `startIndex` does
  4596. // the matching instead.
  4597. const parent = declNode.parent;
  4598. if (parent) {
  4599. const declStart = declNode.startIndex;
  4600. let declIdx = -1;
  4601. for (let i = 0; i < parent.namedChildCount; i++) {
  4602. const sibling = parent.namedChild(i);
  4603. if (sibling && sibling.startIndex === declStart) {
  4604. declIdx = i;
  4605. break;
  4606. }
  4607. }
  4608. if (declIdx > 0) {
  4609. for (let j = declIdx - 1; j >= 0; j--) {
  4610. const sibling = parent.namedChild(j);
  4611. if (!sibling) continue;
  4612. if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') {
  4613. break; // non-decorator separator → stop consuming
  4614. }
  4615. consider(sibling);
  4616. }
  4617. }
  4618. }
  4619. }
  4620. /**
  4621. * Visit function body and extract calls (and structural nodes).
  4622. *
  4623. * In addition to call expressions, this also detects class/struct/enum
  4624. * definitions inside function bodies. This handles two cases:
  4625. * 1. Local class/struct/enum definitions (valid in C++, Java, etc.)
  4626. * 2. C++ macro misparsing — macros like NLOHMANN_JSON_NAMESPACE_BEGIN cause
  4627. * tree-sitter to interpret the namespace block as a function_definition,
  4628. * hiding real class/struct/enum nodes inside the "function body".
  4629. */
  4630. /**
  4631. * Rocket route-registration macros — `routes![a::b::handler, c::d::other]`
  4632. * and `catchers![not_found]`. Tree-sitter leaves a macro body as a flat
  4633. * `token_tree` of raw tokens (`identifier`, `::`, `,`), so the handler paths
  4634. * are never seen as references and each handler fn looks like it has no caller
  4635. * — it's mounted by Rocket at runtime, not called by in-repo code, so its file
  4636. * shows 0 dependents. Walk the token tree, reconstruct each comma-separated
  4637. * path, and emit a `references` edge; the Rust path resolver
  4638. * (`resolveRustPathReference`) then links it to the handler fn. The handler
  4639. * names are explicit in source, so this is precise static extraction, not a
  4640. * heuristic — no false edges (resolution still validates each path).
  4641. */
  4642. private extractRustRouteMacro(node: SyntaxNode): void {
  4643. if (this.language !== 'rust') return;
  4644. const macroName = node.namedChild(0);
  4645. if (!macroName) return;
  4646. const name = getNodeText(macroName, this.source);
  4647. if (name !== 'routes' && name !== 'catchers') return;
  4648. const tokenTree = node.namedChildren.find((c: SyntaxNode) => c.type === 'token_tree');
  4649. if (!tokenTree) return;
  4650. const fromId = this.nodeStack[this.nodeStack.length - 1];
  4651. if (!fromId) return;
  4652. // The token tree is a flat stream: `[ id :: id :: id , id … ]`. Group runs
  4653. // of `identifier` tokens (the `::` joiners are anonymous) into one path; a
  4654. // `,` (or the closing `]`) ends a path.
  4655. let parts: string[] = [];
  4656. let line = 0;
  4657. let column = 0;
  4658. const flush = (): void => {
  4659. if (parts.length > 0) {
  4660. this.unresolvedReferences.push({
  4661. fromNodeId: fromId,
  4662. referenceName: parts.join('::'),
  4663. referenceKind: 'references',
  4664. line,
  4665. column,
  4666. });
  4667. parts = [];
  4668. }
  4669. };
  4670. for (let i = 0; i < tokenTree.childCount; i++) {
  4671. const t = tokenTree.child(i);
  4672. if (!t) continue;
  4673. if (t.type === 'identifier') {
  4674. if (parts.length === 0) {
  4675. line = t.startPosition.row + 1;
  4676. column = t.startPosition.column;
  4677. }
  4678. parts.push(getNodeText(t, this.source));
  4679. } else if (t.type === ',') {
  4680. flush();
  4681. }
  4682. }
  4683. flush();
  4684. }
  4685. /**
  4686. * Record a C++ local function-pointer binding (`local = &fn` / `&fn<…>` /
  4687. * `&ns::fn<…>`) for the CURRENT enclosing symbol, so calls through the local
  4688. * resolve to the real target (see cppLocalFnPtrs). Only the address-of shape
  4689. * is accepted — a bare-identifier RHS (`auto x = y;`) is any value copy, and
  4690. * linking through it would guess.
  4691. */
  4692. private recordCppFnPtrBinding(localName: string, value: SyntaxNode | null): void {
  4693. if (!value || value.type !== 'pointer_expression') return;
  4694. if (value.child(0)?.type !== '&') return; // `*p` dereference, not address-of
  4695. const arg = getChildByField(value, 'argument') ?? value.namedChild(0);
  4696. if (
  4697. !arg ||
  4698. (arg.type !== 'identifier' &&
  4699. arg.type !== 'template_function' &&
  4700. arg.type !== 'qualified_identifier')
  4701. ) {
  4702. return;
  4703. }
  4704. const callerId = this.nodeStack[this.nodeStack.length - 1];
  4705. if (!callerId) return;
  4706. const target = stripCppTemplateArgs(getNodeText(arg, this.source));
  4707. if (!target || target === localName) return;
  4708. let locals = this.cppLocalFnPtrs.get(callerId);
  4709. if (!locals) {
  4710. locals = new Map();
  4711. this.cppLocalFnPtrs.set(callerId, locals);
  4712. }
  4713. let targets = locals.get(localName);
  4714. if (!targets) {
  4715. targets = new Set();
  4716. locals.set(localName, targets);
  4717. }
  4718. targets.add(target);
  4719. }
  4720. private visitFunctionBody(body: SyntaxNode, _functionId: string): void {
  4721. if (!this.extractor) return;
  4722. const visitForCallsAndStructure = (node: SyntaxNode): void => {
  4723. const nodeType = node.type;
  4724. // Function-as-value capture (#756) — function bodies are walked here,
  4725. // not in visitNode, so the capture hook must fire in both walkers.
  4726. this.maybeCaptureFnRefs(node, nodeType);
  4727. // Rocket route-registration macros (`routes![…]` / `catchers![…]`): the
  4728. // handler paths live in a raw token tree the call walker can't see.
  4729. if (nodeType === 'macro_invocation') this.extractRustRouteMacro(node);
  4730. if (this.extractor!.callTypes.includes(nodeType)) {
  4731. this.extractCall(node);
  4732. } else if (INSTANTIATION_KINDS.has(nodeType) || this.isVbnetConstructorShapedArrayCreation(node)) {
  4733. // `new Foo()` inside a function body — emit an `instantiates`
  4734. // reference. Without this branch the body walker only knew
  4735. // about `call_expression`, so constructor invocations
  4736. // produced no graph edges at all.
  4737. this.extractInstantiation(node);
  4738. // Anonymous class with body: `new T() { ... }` (Java/C#). Extract as
  4739. // a class so interface-impl synthesis (Phase 5.5) can bridge T's
  4740. // methods to the overrides — same rationale as in visitNode.
  4741. const anonBody = this.findAnonymousClassBody(node);
  4742. if (anonBody) {
  4743. this.extractAnonymousClass(node, anonBody);
  4744. return;
  4745. }
  4746. } else if (this.extractor!.extractBareCall) {
  4747. const calleeName = this.extractor!.extractBareCall(node, this.source);
  4748. if (calleeName && this.nodeStack.length > 0) {
  4749. const callerId = this.nodeStack[this.nodeStack.length - 1];
  4750. if (callerId) {
  4751. this.unresolvedReferences.push({
  4752. fromNodeId: callerId,
  4753. referenceName: calleeName,
  4754. referenceKind: 'calls',
  4755. line: node.startPosition.row + 1,
  4756. column: node.startPosition.column,
  4757. });
  4758. }
  4759. }
  4760. }
  4761. // C++ stack / direct-initialization construction — `Calculator calc(0)`
  4762. // and `Widget w{1, 2}`. Unlike heap `new Calculator(0)` (a new_expression
  4763. // handled above), these carry the constructor arguments directly on the
  4764. // declarator with NO call/new node, so the body walker saw no constructor
  4765. // invocation and recorded no `instantiates` edge (#1035). A declaration's
  4766. // `type` field IS the constructed class name, so reuse extractInstantiation
  4767. // (which strips template args / namespace and emits the `instantiates`
  4768. // ref). Children still recurse below, so a nested ctor-arg call
  4769. // (`Calculator calc(make())`) keeps its own `calls` ref.
  4770. if (nodeType === 'declaration' && this.language === 'cpp' && this.isCppStackConstruction(node)) {
  4771. this.extractInstantiation(node);
  4772. }
  4773. // C++ local function-pointer bindings (see cppLocalFnPtrs): record
  4774. // `auto kernel = &fn<…>;` declarations and `kernel = &other_fn<…>;`
  4775. // branch reassignments so a call/launch through the local links to the
  4776. // real target(s). The body walker sees these in source order, and C++
  4777. // requires declaration-before-use, so the map is always populated before
  4778. // the call that consumes it.
  4779. if (this.language === 'cpp' && this.nodeStack.length > 0) {
  4780. if (nodeType === 'declaration') {
  4781. for (let i = 0; i < node.namedChildCount; i++) {
  4782. const child = node.namedChild(i);
  4783. if (child?.type !== 'init_declarator') continue;
  4784. const decl = getChildByField(child, 'declarator');
  4785. if (decl?.type !== 'identifier') continue;
  4786. this.recordCppFnPtrBinding(
  4787. getNodeText(decl, this.source),
  4788. getChildByField(child, 'value')
  4789. );
  4790. }
  4791. } else if (nodeType === 'assignment_expression') {
  4792. const left = getChildByField(node, 'left');
  4793. if (left?.type === 'identifier') {
  4794. this.recordCppFnPtrBinding(
  4795. getNodeText(left, this.source),
  4796. getChildByField(node, 'right')
  4797. );
  4798. }
  4799. }
  4800. }
  4801. // Static-member / value-read: `Enum.value`, `Type.CONST`, `Foo::BAR`.
  4802. this.extractStaticMemberRef(node);
  4803. // Local variable type annotations inside a body — `const items: Foo[] = []`,
  4804. // `const x: SomeType = svc.load()`. We deliberately do NOT create nodes for
  4805. // locals (that would explode the graph — the data-flow frontier we leave
  4806. // uncovered), but the TYPE a local is annotated with is a real dependency of
  4807. // the enclosing function, so attribute a `references` edge to it. Without
  4808. // this, a function that uses a type ONLY in its body (very common — e.g. a
  4809. // resolver building `const nodes: Node[] = []`) produced no edge to that
  4810. // type, so impact / `affected` missed the dependency entirely. We fall
  4811. // through to the default recursion below so the initializer's calls (and any
  4812. // nested declarators) are still walked.
  4813. if (
  4814. nodeType === 'variable_declarator' &&
  4815. this.TYPE_ANNOTATION_LANGUAGES.has(this.language)
  4816. ) {
  4817. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  4818. if (ownerId) this.extractVariableTypeAnnotation(node, ownerId);
  4819. }
  4820. // Nested NAMED functions inside a body — function declarations and named
  4821. // function expressions like `.on('mount', function onmount(){})` — become
  4822. // their own nodes so the graph can link to them (callback handlers, local
  4823. // helpers). Anonymous arrows/expressions fall through to the default
  4824. // recursion below, keeping their inner calls attributed to the enclosing
  4825. // function: this bounds the new nodes to NAMED functions only (no explosion,
  4826. // no lost edges). extractFunction walks the nested body itself, so we return.
  4827. if (this.extractor!.functionTypes.includes(nodeType)) {
  4828. const nestedName = extractName(node, this.source, this.extractor!);
  4829. if (nestedName && nestedName !== '<anonymous>') {
  4830. this.extractFunction(node);
  4831. return;
  4832. }
  4833. }
  4834. // Extract structural nodes found inside function bodies.
  4835. // Each extract method visits its own children, so we return after extracting.
  4836. if (this.extractor!.classTypes.includes(nodeType)) {
  4837. const classification = this.extractor!.classifyClassNode?.(node) ?? 'class';
  4838. if (classification === 'struct') this.extractStruct(node);
  4839. else if (classification === 'enum') this.extractEnum(node);
  4840. else if (classification === 'interface') this.extractInterface(node);
  4841. else if (classification === 'trait') this.extractClass(node, 'trait');
  4842. else this.extractClass(node);
  4843. return;
  4844. }
  4845. if (this.extractor!.structTypes.includes(nodeType)) {
  4846. this.extractStruct(node);
  4847. return;
  4848. }
  4849. if (this.extractor!.enumTypes.includes(nodeType)) {
  4850. this.extractEnum(node);
  4851. return;
  4852. }
  4853. if (this.extractor!.interfaceTypes.includes(nodeType)) {
  4854. this.extractInterface(node);
  4855. return;
  4856. }
  4857. for (let i = 0; i < node.namedChildCount; i++) {
  4858. const child = node.namedChild(i);
  4859. if (child) {
  4860. visitForCallsAndStructure(child);
  4861. }
  4862. }
  4863. };
  4864. visitForCallsAndStructure(body);
  4865. }
  4866. /**
  4867. * Extract inheritance relationships
  4868. */
  4869. private extractInheritance(node: SyntaxNode, classId: string): void {
  4870. // Objective-C @interface MyClass : NSObject <ProtoA, ProtoB>
  4871. if (node.type === 'class_interface') {
  4872. const superclass = getChildByField(node, 'superclass');
  4873. if (superclass) {
  4874. const name = getNodeText(superclass, this.source);
  4875. this.unresolvedReferences.push({
  4876. fromNodeId: classId,
  4877. referenceName: name,
  4878. referenceKind: 'extends',
  4879. line: superclass.startPosition.row + 1,
  4880. column: superclass.startPosition.column,
  4881. });
  4882. }
  4883. for (let j = 0; j < node.namedChildCount; j++) {
  4884. const argList = node.namedChild(j);
  4885. if (argList?.type !== 'parameterized_arguments') continue;
  4886. for (let k = 0; k < argList.namedChildCount; k++) {
  4887. const typeName = argList.namedChild(k);
  4888. if (!typeName) continue;
  4889. const typeId = typeName.namedChildren.find(
  4890. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'identifier'
  4891. );
  4892. if (!typeId) continue;
  4893. const protocolName = getNodeText(typeId, this.source);
  4894. this.unresolvedReferences.push({
  4895. fromNodeId: classId,
  4896. referenceName: protocolName,
  4897. referenceKind: 'implements',
  4898. line: typeId.startPosition.row + 1,
  4899. column: typeId.startPosition.column,
  4900. });
  4901. }
  4902. }
  4903. return;
  4904. }
  4905. // Look for extends/implements clauses
  4906. for (let i = 0; i < node.namedChildCount; i++) {
  4907. const child = node.namedChild(i);
  4908. if (!child) continue;
  4909. if (
  4910. child.type === 'extends_clause' ||
  4911. child.type === 'superclass' ||
  4912. child.type === 'base_clause' || // PHP class extends
  4913. child.type === 'extends_interfaces' // Java interface extends
  4914. ) {
  4915. // Scala: `extends A[X] with B with C` packs EVERY supertype into the
  4916. // one extends_clause (separated by `with`), each a `generic_type` /
  4917. // `type_identifier` / `stable_type_identifier`. The generic path below
  4918. // takes only namedChild(0) and keeps the full text (`A[X]`), so a
  4919. // parameterized supertype — every typeclass in cats/algebra — never
  4920. // matched and `with`-mixed traits past the first were dropped. Iterate
  4921. // all supertypes and unwrap each to its base type name.
  4922. if (this.language === 'scala') {
  4923. for (const target of child.namedChildren) {
  4924. const name = scalaBaseTypeName(target, this.source);
  4925. if (name) {
  4926. this.unresolvedReferences.push({
  4927. fromNodeId: classId,
  4928. referenceName: name,
  4929. referenceKind: 'extends',
  4930. line: target.startPosition.row + 1,
  4931. column: target.startPosition.column,
  4932. });
  4933. }
  4934. }
  4935. continue;
  4936. }
  4937. // Dart: `class C extends Base with M1, M2` — the `superclass` node holds
  4938. // the extends type as a direct `type_identifier` AND a `mixins` child
  4939. // listing the `with` mixins (and `class C with M` has ONLY mixins, no
  4940. // extends type). The generic `namedChild(0)` path would read the
  4941. // `mixins` node itself as the superclass and drop every mixin — yet
  4942. // mixins are Dart's core composition mechanism (Flutter is built on
  4943. // them). Emit `extends` for the base and `implements` for each mixin.
  4944. if (this.language === 'dart' && child.type === 'superclass') {
  4945. for (const t of child.namedChildren) {
  4946. if (t.type === 'mixins') {
  4947. for (const m of t.namedChildren) {
  4948. if (m.type === 'type_identifier') {
  4949. this.unresolvedReferences.push({
  4950. fromNodeId: classId,
  4951. referenceName: getNodeText(m, this.source),
  4952. referenceKind: 'implements',
  4953. line: m.startPosition.row + 1,
  4954. column: m.startPosition.column,
  4955. });
  4956. }
  4957. }
  4958. } else if (t.type === 'type_identifier') {
  4959. this.unresolvedReferences.push({
  4960. fromNodeId: classId,
  4961. referenceName: getNodeText(t, this.source),
  4962. referenceKind: 'extends',
  4963. line: t.startPosition.row + 1,
  4964. column: t.startPosition.column,
  4965. });
  4966. }
  4967. }
  4968. continue;
  4969. }
  4970. // Extract parent class/interface names
  4971. // Java uses type_list wrapper: superclass -> type_identifier, extends_interfaces -> type_list -> type_identifier
  4972. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  4973. const targets = typeList ? typeList.namedChildren : [child.namedChild(0)];
  4974. for (const target of targets) {
  4975. if (target) {
  4976. const name = getNodeText(target, this.source);
  4977. this.unresolvedReferences.push({
  4978. fromNodeId: classId,
  4979. referenceName: name,
  4980. referenceKind: 'extends',
  4981. line: target.startPosition.row + 1,
  4982. column: target.startPosition.column,
  4983. });
  4984. }
  4985. }
  4986. }
  4987. // C++ base classes: `class Derived : public Base, private Other` →
  4988. // base_class_clause holds access specifiers + base type(s). Emit an extends
  4989. // ref per base type (skip the public/private/protected keywords). A
  4990. // templated base (`Base<int>`, `ns::Tpl<int>`) arrives as a `template_type`
  4991. // or a `qualified_identifier` wrapping one; strip the `<…>` args so the ref
  4992. // matches the bare class the template was defined as — `Base`, `ns::Tpl` —
  4993. // instead of never resolving (#1043).
  4994. if (child.type === 'base_class_clause') {
  4995. for (const t of child.namedChildren) {
  4996. if (
  4997. t.type === 'type_identifier' ||
  4998. t.type === 'qualified_identifier' ||
  4999. t.type === 'template_type'
  5000. ) {
  5001. this.unresolvedReferences.push({
  5002. fromNodeId: classId,
  5003. referenceName: stripCppTemplateArgs(getNodeText(t, this.source)),
  5004. referenceKind: 'extends',
  5005. line: t.startPosition.row + 1,
  5006. column: t.startPosition.column,
  5007. });
  5008. }
  5009. }
  5010. }
  5011. if (
  5012. child.type === 'implements_clause' ||
  5013. child.type === 'class_interface_clause' ||
  5014. child.type === 'super_interfaces' || // Java class implements
  5015. child.type === 'interfaces' // Dart
  5016. ) {
  5017. // Extract implemented interfaces
  5018. // Java uses type_list wrapper: super_interfaces -> type_list -> type_identifier
  5019. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  5020. const targets = typeList ? typeList.namedChildren : child.namedChildren;
  5021. for (const iface of targets) {
  5022. if (iface) {
  5023. const name = getNodeText(iface, this.source);
  5024. this.unresolvedReferences.push({
  5025. fromNodeId: classId,
  5026. referenceName: name,
  5027. referenceKind: 'implements',
  5028. line: iface.startPosition.row + 1,
  5029. column: iface.startPosition.column,
  5030. });
  5031. }
  5032. }
  5033. }
  5034. // Python superclass list: `class Flask(Scaffold, Mixin):`
  5035. // argument_list contains identifier children for each parent class
  5036. if (child.type === 'argument_list' && node.type === 'class_definition') {
  5037. for (const arg of child.namedChildren) {
  5038. if (arg.type === 'identifier' || arg.type === 'attribute') {
  5039. const name = getNodeText(arg, this.source);
  5040. this.unresolvedReferences.push({
  5041. fromNodeId: classId,
  5042. referenceName: name,
  5043. referenceKind: 'extends',
  5044. line: arg.startPosition.row + 1,
  5045. column: arg.startPosition.column,
  5046. });
  5047. }
  5048. }
  5049. }
  5050. // Go interface embedding: `type Querier interface { LabelQuerier; ... }`
  5051. // constraint_elem wraps the embedded interface type identifier
  5052. if (child.type === 'constraint_elem') {
  5053. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5054. if (typeId) {
  5055. const name = getNodeText(typeId, this.source);
  5056. this.unresolvedReferences.push({
  5057. fromNodeId: classId,
  5058. referenceName: name,
  5059. referenceKind: 'extends',
  5060. line: typeId.startPosition.row + 1,
  5061. column: typeId.startPosition.column,
  5062. });
  5063. }
  5064. }
  5065. // Go struct embedding: field_declaration without field_identifier
  5066. // e.g. `type DB struct { *Head; Queryable }` — no field name means embedded type
  5067. if (child.type === 'field_declaration') {
  5068. const hasFieldIdentifier = child.namedChildren.some((c: SyntaxNode) => c.type === 'field_identifier');
  5069. if (!hasFieldIdentifier) {
  5070. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5071. if (typeId) {
  5072. const name = getNodeText(typeId, this.source);
  5073. this.unresolvedReferences.push({
  5074. fromNodeId: classId,
  5075. referenceName: name,
  5076. referenceKind: 'extends',
  5077. line: typeId.startPosition.row + 1,
  5078. column: typeId.startPosition.column,
  5079. });
  5080. }
  5081. }
  5082. }
  5083. // Rust trait supertraits: `trait SubTrait: SuperTrait + Display { ... }`
  5084. // trait_bounds contains type_identifier, generic_type, or higher_ranked_trait_bound children
  5085. if (child.type === 'trait_bounds') {
  5086. for (const bound of child.namedChildren) {
  5087. let typeName: string | undefined;
  5088. let posNode: SyntaxNode | undefined;
  5089. if (bound.type === 'type_identifier') {
  5090. typeName = getNodeText(bound, this.source);
  5091. posNode = bound;
  5092. } else if (bound.type === 'generic_type') {
  5093. // e.g. `Deserialize<'de>`
  5094. const inner = bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5095. if (inner) { typeName = getNodeText(inner, this.source); posNode = inner; }
  5096. } else if (bound.type === 'higher_ranked_trait_bound') {
  5097. // e.g. `for<'de> Deserialize<'de>`
  5098. const generic = bound.namedChildren.find((c: SyntaxNode) => c.type === 'generic_type');
  5099. const typeId = generic?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  5100. ?? bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5101. if (typeId) { typeName = getNodeText(typeId, this.source); posNode = typeId; }
  5102. }
  5103. if (typeName && posNode) {
  5104. this.unresolvedReferences.push({
  5105. fromNodeId: classId,
  5106. referenceName: typeName,
  5107. referenceKind: 'extends',
  5108. line: posNode.startPosition.row + 1,
  5109. column: posNode.startPosition.column,
  5110. });
  5111. }
  5112. }
  5113. }
  5114. // VB.NET: `Inherits Base` / `Implements IFoo, IBar(Of T)` are STATEMENTS
  5115. // inside the class body (children of the class node), not header clauses.
  5116. // Each name is a simple/qualified/generic reference; generics unwrap to
  5117. // the base identifier and dotted paths keep the trailing segment.
  5118. if (
  5119. this.language === 'vbnet' &&
  5120. (child.type === 'inherits_statement' || child.type === 'implements_statement')
  5121. ) {
  5122. const kind = child.type === 'inherits_statement' ? 'extends' : 'implements';
  5123. for (const ref of child.namedChildren) {
  5124. if (!ref || (ref.type !== 'simple_name' && ref.type !== 'qualified_name' && ref.type !== 'generic_name' && ref.type !== 'global_qualified_name')) continue;
  5125. let name = getNodeText(ref, this.source);
  5126. name = name.replace(/\(\s*Of\b[^)]*\)/gi, '');
  5127. const lastDot = name.lastIndexOf('.');
  5128. if (lastDot >= 0) name = name.slice(lastDot + 1);
  5129. name = name.trim();
  5130. if (!name) continue;
  5131. this.unresolvedReferences.push({
  5132. fromNodeId: classId,
  5133. referenceName: name,
  5134. referenceKind: kind,
  5135. line: ref.startPosition.row + 1,
  5136. column: ref.startPosition.column,
  5137. });
  5138. }
  5139. }
  5140. // C#: `class Movie : BaseItem, IPlugin` → base_list with identifier children
  5141. // base_list combines both base class and interfaces in a single colon-separated list.
  5142. // We emit all as 'extends' since the syntax doesn't distinguish them.
  5143. if (child.type === 'base_list') {
  5144. for (const baseType of child.namedChildren) {
  5145. if (baseType) {
  5146. // For generic base types like `ClientBase<T>`, extract just the type name
  5147. const name = baseType.type === 'generic_name'
  5148. ? getNodeText(baseType.namedChildren.find((c: SyntaxNode) => c.type === 'identifier') ?? baseType, this.source)
  5149. : getNodeText(baseType, this.source);
  5150. this.unresolvedReferences.push({
  5151. fromNodeId: classId,
  5152. referenceName: name,
  5153. referenceKind: 'extends',
  5154. line: baseType.startPosition.row + 1,
  5155. column: baseType.startPosition.column,
  5156. });
  5157. }
  5158. }
  5159. }
  5160. // Kotlin: `class Foo : Bar, Baz` → delegation_specifier > user_type > type_identifier
  5161. // Also handles `class Foo : Bar()` → delegation_specifier > constructor_invocation > user_type
  5162. if (child.type === 'delegation_specifier') {
  5163. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  5164. const constructorInvocation = child.namedChildren.find((c: SyntaxNode) => c.type === 'constructor_invocation');
  5165. const target = userType ?? constructorInvocation;
  5166. if (target) {
  5167. const typeId = target.type === 'user_type'
  5168. ? target.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier') ?? target
  5169. : target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type')?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  5170. ?? target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type') ?? target;
  5171. const name = getNodeText(typeId, this.source);
  5172. this.unresolvedReferences.push({
  5173. fromNodeId: classId,
  5174. referenceName: name,
  5175. referenceKind: 'extends',
  5176. line: typeId.startPosition.row + 1,
  5177. column: typeId.startPosition.column,
  5178. });
  5179. }
  5180. }
  5181. // Swift: inheritance_specifier > user_type > type_identifier
  5182. // Used for class inheritance, protocol conformance, and protocol inheritance
  5183. if (child.type === 'inheritance_specifier') {
  5184. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  5185. const typeId = userType?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  5186. if (typeId) {
  5187. const name = getNodeText(typeId, this.source);
  5188. this.unresolvedReferences.push({
  5189. fromNodeId: classId,
  5190. referenceName: name,
  5191. referenceKind: 'extends',
  5192. line: typeId.startPosition.row + 1,
  5193. column: typeId.startPosition.column,
  5194. });
  5195. }
  5196. }
  5197. // JavaScript class_heritage has bare identifier without extends_clause wrapper
  5198. // e.g. `class Foo extends Bar {}` → class_heritage → identifier("Bar")
  5199. if (
  5200. (child.type === 'identifier' || child.type === 'type_identifier') &&
  5201. node.type === 'class_heritage'
  5202. ) {
  5203. const name = getNodeText(child, this.source);
  5204. this.unresolvedReferences.push({
  5205. fromNodeId: classId,
  5206. referenceName: name,
  5207. referenceKind: 'extends',
  5208. line: child.startPosition.row + 1,
  5209. column: child.startPosition.column,
  5210. });
  5211. }
  5212. // Recurse into container nodes (e.g. field_declaration_list in Go structs,
  5213. // class_heritage in TypeScript which wraps extends_clause/implements_clause)
  5214. if (child.type === 'field_declaration_list' || child.type === 'class_heritage') {
  5215. this.extractInheritance(child, classId);
  5216. }
  5217. // CFML cfscript `component extends="Base" implements="IFoo,IBar" { ... }`
  5218. // (also covers `interface extends="IBase" { ... }`, which reuses the same
  5219. // component_attribute shape). Attributes are generic name=value pairs —
  5220. // (identifier label, expression value) — not a dedicated extends_clause,
  5221. // so filter by the label text. `implements` is a comma-separated list.
  5222. if (child.type === 'component_attribute' && node.type === 'component') {
  5223. const label = child.namedChildren.find((c: SyntaxNode) => c.type === 'identifier');
  5224. const value = child.namedChildren.find((c: SyntaxNode) => c.type !== 'identifier');
  5225. if (label && value) {
  5226. const labelText = getNodeText(label, this.source).toLowerCase();
  5227. if (labelText === 'extends' || labelText === 'implements') {
  5228. const valueText = getNodeText(value, this.source).replace(/^["']|["']$/g, '');
  5229. const names = labelText === 'implements'
  5230. ? valueText.split(',').map((s) => s.trim()).filter(Boolean)
  5231. : [valueText.trim()].filter(Boolean);
  5232. for (const name of names) {
  5233. this.unresolvedReferences.push({
  5234. fromNodeId: classId,
  5235. referenceName: name,
  5236. referenceKind: labelText === 'implements' ? 'implements' : 'extends',
  5237. line: value.startPosition.row + 1,
  5238. column: value.startPosition.column,
  5239. });
  5240. }
  5241. }
  5242. }
  5243. }
  5244. }
  5245. }
  5246. /**
  5247. * Rust `impl Trait for Type` — creates an implements edge from Type to Trait.
  5248. * For plain `impl Type { ... }` (no trait), no inheritance edge is needed.
  5249. */
  5250. private extractRustImplItem(node: SyntaxNode): void {
  5251. // Check if this is `impl Trait for Type` by looking for a `for` keyword
  5252. const hasFor = node.children.some(
  5253. (c: SyntaxNode) => c.type === 'for' && !c.isNamed
  5254. );
  5255. if (!hasFor) return;
  5256. // In `impl Trait for Type`, the type_identifiers are:
  5257. // first = Trait name, last = implementing Type name
  5258. // Also handle generic types like `impl<T> Trait for MyStruct<T>`
  5259. const typeIdents = node.namedChildren.filter(
  5260. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'generic_type' || c.type === 'scoped_type_identifier'
  5261. );
  5262. if (typeIdents.length < 2) return;
  5263. const traitNode = typeIdents[0]!;
  5264. const typeNode = typeIdents[typeIdents.length - 1]!;
  5265. // Get the trait name (handle scoped paths like std::fmt::Display)
  5266. const traitName = traitNode.type === 'scoped_type_identifier'
  5267. ? this.source.substring(traitNode.startIndex, traitNode.endIndex)
  5268. : getNodeText(traitNode, this.source);
  5269. // Get the implementing type name (extract inner type_identifier for generics)
  5270. let typeName: string;
  5271. if (typeNode.type === 'generic_type') {
  5272. const inner = typeNode.namedChildren.find(
  5273. (c: SyntaxNode) => c.type === 'type_identifier'
  5274. );
  5275. typeName = inner ? getNodeText(inner, this.source) : getNodeText(typeNode, this.source);
  5276. } else {
  5277. typeName = getNodeText(typeNode, this.source);
  5278. }
  5279. // Find the struct/type node for the implementing type
  5280. const typeNodeId = this.findNodeByName(typeName);
  5281. if (typeNodeId) {
  5282. this.unresolvedReferences.push({
  5283. fromNodeId: typeNodeId,
  5284. referenceName: traitName,
  5285. referenceKind: 'implements',
  5286. line: traitNode.startPosition.row + 1,
  5287. column: traitNode.startPosition.column,
  5288. });
  5289. }
  5290. }
  5291. /**
  5292. * Find a previously-extracted node by name (used for back-references like impl blocks)
  5293. */
  5294. private findNodeByName(name: string): string | undefined {
  5295. for (const node of this.nodes) {
  5296. if (node.name === name && (node.kind === 'struct' || node.kind === 'enum' || node.kind === 'class')) {
  5297. return node.id;
  5298. }
  5299. }
  5300. return undefined;
  5301. }
  5302. /**
  5303. * Languages that support type annotations (TypeScript, etc.)
  5304. */
  5305. private readonly TYPE_ANNOTATION_LANGUAGES = new Set([
  5306. 'typescript', 'tsx', 'arkts', 'dart', 'kotlin', 'swift', 'rust', 'go', 'java', 'csharp', 'scala', 'php',
  5307. ]);
  5308. /**
  5309. * PHP pseudo-types and `self`/`static`/`parent` that aren't project symbols.
  5310. * (Scalar primitives parse as `primitive_type` and are skipped structurally.)
  5311. */
  5312. private readonly PHP_PSEUDO_TYPES = new Set([
  5313. 'self', 'static', 'parent', 'mixed', 'object', 'iterable', 'callable', 'void',
  5314. 'null', 'false', 'true', 'never', 'array', 'int', 'float', 'string', 'bool',
  5315. ]);
  5316. /**
  5317. * Built-in/primitive type names that shouldn't create references
  5318. */
  5319. private readonly BUILTIN_TYPES = new Set([
  5320. 'string', 'number', 'boolean', 'void', 'null', 'undefined', 'never', 'any', 'unknown',
  5321. 'object', 'symbol', 'bigint', 'true', 'false',
  5322. // Rust
  5323. 'str', 'bool', 'i8', 'i16', 'i32', 'i64', 'i128', 'isize',
  5324. 'u8', 'u16', 'u32', 'u64', 'u128', 'usize', 'f32', 'f64', 'char',
  5325. // Java/C#
  5326. 'int', 'long', 'short', 'byte', 'float', 'double', 'char',
  5327. // Go
  5328. 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64',
  5329. 'float32', 'float64', 'complex64', 'complex128', 'rune', 'error',
  5330. // Scala (capitalized primitives + ubiquitous stdlib aliases)
  5331. 'Int', 'Long', 'Short', 'Byte', 'Float', 'Double', 'Boolean', 'Char', 'Unit',
  5332. 'String', 'Any', 'AnyRef', 'AnyVal', 'Nothing', 'Null',
  5333. ]);
  5334. /**
  5335. * Extract type references from type annotations on a function/method/field node.
  5336. * Creates 'references' edges for parameter types, return types, and field types.
  5337. */
  5338. private extractTypeAnnotations(node: SyntaxNode, nodeId: string): void {
  5339. if (!this.extractor) return;
  5340. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  5341. // C# tree-sitter doesn't produce `type_identifier` leaves — it uses
  5342. // `identifier`, `predefined_type`, `qualified_name`, `generic_name`,
  5343. // etc. — so the generic walker below emits zero references for it.
  5344. // Dispatch to a C#-aware path that only walks type-position subtrees
  5345. // (the `type` field of a parameter/method/property/field), so
  5346. // parameter NAMES never accidentally surface as type refs (#381).
  5347. if (this.language === 'csharp') {
  5348. this.extractCsharpTypeRefs(node, nodeId);
  5349. return;
  5350. }
  5351. // PHP type-hints are `named_type`/`optional_type`/`union_type` wrapping a
  5352. // `name`/`qualified_name` — never `type_identifier` — so the generic walker
  5353. // below emits nothing for them. Dispatch to a PHP-aware path that walks only
  5354. // type positions (parameter / return / property types), so type-hinted
  5355. // dependencies (the constructor-injected contracts that dominate Laravel) are
  5356. // recorded and a `variable_name` like `$events` never mis-emits as a ref.
  5357. if (this.language === 'php') {
  5358. this.extractPhpTypeRefs(node, nodeId);
  5359. return;
  5360. }
  5361. // Dart: a `method_signature` wraps the real `function_signature` (where the
  5362. // params and return type live), and the return type is a bare
  5363. // `type_identifier` child, not a `type` field — so getChildByField below
  5364. // finds neither. Walk the inner signature: param names / the method name are
  5365. // `identifier` (not `type_identifier`), so only types surface.
  5366. if (this.language === 'dart') {
  5367. let sig: SyntaxNode | undefined = node;
  5368. if (node.type === 'method_signature') {
  5369. sig = node.namedChildren.find(
  5370. (c: SyntaxNode) =>
  5371. c.type === 'function_signature' ||
  5372. c.type === 'getter_signature' ||
  5373. c.type === 'setter_signature' ||
  5374. c.type === 'constructor_signature' ||
  5375. c.type === 'factory_constructor_signature'
  5376. ) ?? node;
  5377. }
  5378. this.extractTypeRefsFromSubtree(sig, nodeId);
  5379. return;
  5380. }
  5381. // Extract parameter type annotations. Scala curries — `def f(a)(implicit
  5382. // M: TC)` has MULTIPLE `parameters` siblings, and the typeclass is almost
  5383. // always in the trailing implicit list — so walk every parameter list, not
  5384. // just getChildByField's first match.
  5385. if (this.language === 'scala') {
  5386. for (const pc of node.namedChildren) {
  5387. if (pc.type === 'parameters') this.extractTypeRefsFromSubtree(pc, nodeId);
  5388. }
  5389. } else {
  5390. const params = getChildByField(node, this.extractor.paramsField || 'parameters');
  5391. if (params) {
  5392. this.extractTypeRefsFromSubtree(params, nodeId);
  5393. }
  5394. }
  5395. // Extract return type annotation
  5396. const returnType = getChildByField(node, this.extractor.returnField || 'return_type');
  5397. if (returnType) {
  5398. this.extractTypeRefsFromSubtree(returnType, nodeId);
  5399. }
  5400. // Scala context bounds / type-parameter bounds: `def f[A: Monoid]`,
  5401. // `[F[_]: Monad]`, `[A <: Foo]` carry the bound type inside `type_parameters`.
  5402. // This is THE pervasive way a typeclass is required in Scala, yet the bound
  5403. // never appears in the value parameters. Param NAMES are `identifier` (not
  5404. // `type_identifier`), so only the bound types surface. Scala-only: in other
  5405. // languages a `type_parameters` child holds declaration names as
  5406. // `type_identifier` (TS `<T>`), which would wrongly surface as refs.
  5407. if (this.language === 'scala') {
  5408. const typeParams = node.namedChildren.find(
  5409. (c: SyntaxNode) => c.type === 'type_parameters'
  5410. );
  5411. if (typeParams) {
  5412. this.extractTypeRefsFromSubtree(typeParams, nodeId);
  5413. }
  5414. }
  5415. // Extract direct type annotation (for class fields like `model: ITextModel`)
  5416. const typeAnnotation = node.namedChildren.find(
  5417. (c: SyntaxNode) => c.type === 'type_annotation'
  5418. );
  5419. if (typeAnnotation) {
  5420. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  5421. }
  5422. }
  5423. /**
  5424. * Extract C# type references from a node that owns a type position —
  5425. * a method/constructor declaration, a property declaration, or a
  5426. * field declaration (which wraps `variable_declaration → type`).
  5427. *
  5428. * Walks ONLY into known type fields, so parameter names like
  5429. * `request` in `Build(UserDto request)` are never mis-emitted as
  5430. * type references. Once inside a type subtree, `walkCsharpTypePosition`
  5431. * recognizes C#'s actual type-leaf node kinds (`identifier`,
  5432. * `qualified_name`, `generic_name`, `array_type`, `nullable_type`,
  5433. * `tuple_type`, …) — none of which are `type_identifier`. Closes #381.
  5434. */
  5435. private extractCsharpTypeRefs(node: SyntaxNode, nodeId: string): void {
  5436. // A property's type is under the `type` field; a method/constructor's RETURN
  5437. // type is under `returns` (tree-sitter-c-sharp 0.23.x — older builds used
  5438. // `type` for both). A node carries only one of the two, so checking both
  5439. // covers return types and property types without conflating them.
  5440. const directType = getChildByField(node, 'type') ?? getChildByField(node, 'returns');
  5441. if (directType) this.walkCsharpTypePosition(directType, nodeId);
  5442. // Field declarations wrap declarators in a `variable_declaration`
  5443. // whose `type` field carries the type. The outer `field_declaration`
  5444. // has no `type` field of its own, so the call above is a no-op here
  5445. // and we descend one level.
  5446. const varDecl = node.namedChildren.find((c: SyntaxNode) => c.type === 'variable_declaration');
  5447. if (varDecl) {
  5448. const vdType = getChildByField(varDecl, 'type');
  5449. if (vdType) this.walkCsharpTypePosition(vdType, nodeId);
  5450. }
  5451. // Method / constructor parameters. The field name on
  5452. // `method_declaration` is `parameters`; it points at a
  5453. // `parameter_list` whose `parameter` children each have their own
  5454. // `type` field. Walking ONLY the type field skips parameter NAMES,
  5455. // which would otherwise mis-emit as type references.
  5456. const params = getChildByField(node, 'parameters');
  5457. if (params) {
  5458. for (let i = 0; i < params.namedChildCount; i++) {
  5459. const child = params.namedChild(i);
  5460. if (!child || child.type !== 'parameter') continue;
  5461. const paramType = getChildByField(child, 'type');
  5462. if (paramType) this.walkCsharpTypePosition(paramType, nodeId);
  5463. }
  5464. }
  5465. }
  5466. /**
  5467. * Record the dependencies declared by a C# PRIMARY CONSTRUCTOR
  5468. * (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache) { … }`,
  5469. * C# 12+). The parameter list hangs off the class/struct/record declaration
  5470. * as an unnamed-field `parameter_list` child (not the `parameters` field a
  5471. * method uses), so it's found by node type. Each parameter's declared type
  5472. * becomes a `references` edge from the owning type — these are exactly the
  5473. * services a DI-registered type depends on, so impact/blast-radius and
  5474. * "who depends on this contract" now see them. No-op when there's no primary
  5475. * constructor. (#237)
  5476. */
  5477. private extractCsharpPrimaryCtorParamRefs(node: SyntaxNode, ownerId: string): void {
  5478. if (this.language !== 'csharp') return;
  5479. const paramList = node.namedChildren.find((c: SyntaxNode) => c.type === 'parameter_list');
  5480. if (!paramList) return;
  5481. for (let i = 0; i < paramList.namedChildCount; i++) {
  5482. const param = paramList.namedChild(i);
  5483. if (!param || param.type !== 'parameter') continue;
  5484. const paramType = getChildByField(param, 'type');
  5485. if (paramType) this.walkCsharpTypePosition(paramType, ownerId);
  5486. }
  5487. }
  5488. /**
  5489. * Walk a C# subtree that is KNOWN to be in a type position
  5490. * (return type, parameter type, property type, field type, generic
  5491. * argument). Identifiers here are type names, not parameter names.
  5492. */
  5493. private walkCsharpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  5494. // `predefined_type` is int/string/bool/etc. — never a project ref.
  5495. if (node.type === 'predefined_type') return;
  5496. // Bare type name: `Foo` in `Foo bar`, or the `Foo` inside `List<Foo>`.
  5497. if (node.type === 'identifier') {
  5498. const name = getNodeText(node, this.source);
  5499. if (name && !this.BUILTIN_TYPES.has(name)) {
  5500. this.unresolvedReferences.push({
  5501. fromNodeId,
  5502. referenceName: name,
  5503. referenceKind: 'references',
  5504. line: node.startPosition.row + 1,
  5505. column: node.startPosition.column,
  5506. });
  5507. }
  5508. return;
  5509. }
  5510. // `Namespace.Foo` → the rightmost identifier is the type. Emit the
  5511. // full qualified name as the reference; the resolver can still match
  5512. // on the trailing simple name when needed.
  5513. if (node.type === 'qualified_name') {
  5514. const text = getNodeText(node, this.source);
  5515. const last = text.split('.').pop() ?? text;
  5516. if (last && !this.BUILTIN_TYPES.has(last)) {
  5517. this.unresolvedReferences.push({
  5518. fromNodeId,
  5519. referenceName: last,
  5520. referenceKind: 'references',
  5521. line: node.startPosition.row + 1,
  5522. column: node.startPosition.column,
  5523. });
  5524. }
  5525. return;
  5526. }
  5527. // `(int Code, Foo Payload)` — tuple element has BOTH a `type` and a
  5528. // `name` field; descending into all named children would mis-emit
  5529. // the element name (`Code`, `Payload`) as a type ref. Walk only the
  5530. // type field.
  5531. if (node.type === 'tuple_element') {
  5532. const t = getChildByField(node, 'type');
  5533. if (t) this.walkCsharpTypePosition(t, fromNodeId);
  5534. return;
  5535. }
  5536. // Composite type nodes — recurse into named children. Covers
  5537. // `generic_name` (head identifier + `type_argument_list`),
  5538. // `nullable_type`, `array_type`, `pointer_type`, `tuple_type`,
  5539. // `ref_type`, and any newer wrapping shapes the grammar adds.
  5540. // Identifiers reached here are all type-positional (parameter/field
  5541. // names are gated out before we descend).
  5542. for (let i = 0; i < node.namedChildCount; i++) {
  5543. const child = node.namedChild(i);
  5544. if (child) this.walkCsharpTypePosition(child, fromNodeId);
  5545. }
  5546. }
  5547. /**
  5548. * Extract PHP type references from a method/function/property declaration.
  5549. * Walks ONLY type positions: each parameter's type child (inside
  5550. * `formal_parameters`), the return type, and a property's type — all
  5551. * `named_type` / `optional_type` / `union_type` / … direct children. Parameter
  5552. * and property NAMES are `variable_name` (`$x`), never type nodes, so they
  5553. * can't be mis-emitted.
  5554. */
  5555. private extractPhpTypeRefs(node: SyntaxNode, nodeId: string): void {
  5556. const params = node.namedChildren.find((c: SyntaxNode) => c.type === 'formal_parameters');
  5557. if (params) {
  5558. for (const p of params.namedChildren) {
  5559. // simple_parameter / property_promotion_parameter / variadic_parameter
  5560. for (const c of p.namedChildren) {
  5561. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  5562. }
  5563. }
  5564. }
  5565. // Return type (method/function) and property type are TYPE nodes that are
  5566. // DIRECT children of the declaration.
  5567. for (const c of node.namedChildren) {
  5568. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  5569. }
  5570. }
  5571. /** Walk a PHP subtree KNOWN to be in a type position; emit class/interface refs. */
  5572. private walkPhpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  5573. if (node.type === 'primitive_type') return; // int/string/void/…
  5574. if (node.type === 'name') {
  5575. const name = getNodeText(node, this.source);
  5576. if (name && !this.PHP_PSEUDO_TYPES.has(name)) {
  5577. this.unresolvedReferences.push({
  5578. fromNodeId, referenceName: name, referenceKind: 'references',
  5579. line: node.startPosition.row + 1, column: node.startPosition.column,
  5580. });
  5581. }
  5582. return;
  5583. }
  5584. if (node.type === 'qualified_name') {
  5585. // `App\Contracts\Logger` → match on the trailing simple name (what the
  5586. // class node is stored as, and what a `use` import brings into scope).
  5587. const last = getNodeText(node, this.source).split('\\').pop() ?? '';
  5588. if (last && !this.PHP_PSEUDO_TYPES.has(last)) {
  5589. this.unresolvedReferences.push({
  5590. fromNodeId, referenceName: last, referenceKind: 'references',
  5591. line: node.startPosition.row + 1, column: node.startPosition.column,
  5592. });
  5593. }
  5594. return;
  5595. }
  5596. // optional_type / nullable_type / union_type / intersection_type / named_type → recurse
  5597. for (let i = 0; i < node.namedChildCount; i++) {
  5598. const child = node.namedChild(i);
  5599. if (child) this.walkPhpTypePosition(child, fromNodeId);
  5600. }
  5601. }
  5602. /**
  5603. * Extract type references from a variable's type annotation.
  5604. */
  5605. private extractVariableTypeAnnotation(node: SyntaxNode, nodeId: string): void {
  5606. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  5607. // Find type_annotation child (covers TS `: Type`, Rust `: Type`, etc.)
  5608. const typeAnnotation = node.namedChildren.find(
  5609. (c: SyntaxNode) => c.type === 'type_annotation'
  5610. );
  5611. if (typeAnnotation) {
  5612. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  5613. }
  5614. }
  5615. /**
  5616. * Recursively walk a subtree and extract all type_identifier references.
  5617. * Handles unions, intersections, generics, arrays, etc.
  5618. */
  5619. private extractTypeRefsFromSubtree(node: SyntaxNode, fromNodeId: string): void {
  5620. if (node.type === 'type_identifier') {
  5621. const typeName = getNodeText(node, this.source);
  5622. if (typeName && !this.BUILTIN_TYPES.has(typeName)) {
  5623. this.unresolvedReferences.push({
  5624. fromNodeId,
  5625. referenceName: typeName,
  5626. referenceKind: 'references',
  5627. line: node.startPosition.row + 1,
  5628. column: node.startPosition.column,
  5629. });
  5630. }
  5631. return; // type_identifier is a leaf
  5632. }
  5633. // Recurse into children (handles union_type, intersection_type, generic_type, etc.)
  5634. for (let i = 0; i < node.namedChildCount; i++) {
  5635. const child = node.namedChild(i);
  5636. if (child) {
  5637. this.extractTypeRefsFromSubtree(child, fromNodeId);
  5638. }
  5639. }
  5640. }
  5641. /**
  5642. * Handle Pascal-specific AST structures.
  5643. * Returns true if the node was fully handled and children should be skipped.
  5644. */
  5645. private visitPascalNode(node: SyntaxNode): boolean {
  5646. const nodeType = node.type;
  5647. // Unit/Program/Library → module node
  5648. if (nodeType === 'unit' || nodeType === 'program' || nodeType === 'library') {
  5649. const moduleNameNode = node.namedChildren.find(
  5650. (c: SyntaxNode) => c.type === 'moduleName'
  5651. );
  5652. const name = moduleNameNode ? getNodeText(moduleNameNode, this.source) : '';
  5653. // Fallback to filename without extension if module name is empty
  5654. const moduleName = name || path.basename(this.filePath).replace(/\.[^.]+$/, '');
  5655. this.createNode('module', moduleName, node);
  5656. // Continue visiting children (interface/implementation sections)
  5657. for (let i = 0; i < node.namedChildCount; i++) {
  5658. const child = node.namedChild(i);
  5659. if (child) this.visitNode(child);
  5660. }
  5661. return true;
  5662. }
  5663. // declType wraps declClass/declIntf/declEnum/type-alias
  5664. // The name lives on declType, the inner node determines the kind
  5665. if (nodeType === 'declType') {
  5666. this.extractPascalDeclType(node);
  5667. return true;
  5668. }
  5669. // declUses → import nodes for each unit name
  5670. if (nodeType === 'declUses') {
  5671. this.extractPascalUses(node);
  5672. return true;
  5673. }
  5674. // declConsts → container; visit children for individual declConst
  5675. if (nodeType === 'declConsts') {
  5676. for (let i = 0; i < node.namedChildCount; i++) {
  5677. const child = node.namedChild(i);
  5678. if (child?.type === 'declConst') {
  5679. this.extractPascalConst(child);
  5680. }
  5681. }
  5682. return true;
  5683. }
  5684. // declConst at top level (outside declConsts)
  5685. if (nodeType === 'declConst') {
  5686. this.extractPascalConst(node);
  5687. return true;
  5688. }
  5689. // declTypes → container for type declarations
  5690. if (nodeType === 'declTypes') {
  5691. for (let i = 0; i < node.namedChildCount; i++) {
  5692. const child = node.namedChild(i);
  5693. if (child) this.visitNode(child);
  5694. }
  5695. return true;
  5696. }
  5697. // declVars → container for variable declarations
  5698. if (nodeType === 'declVars') {
  5699. for (let i = 0; i < node.namedChildCount; i++) {
  5700. const child = node.namedChild(i);
  5701. if (child?.type === 'declVar') {
  5702. const nameNode = getChildByField(child, 'name');
  5703. if (nameNode) {
  5704. const name = getNodeText(nameNode, this.source);
  5705. this.createNode('variable', name, child);
  5706. }
  5707. }
  5708. }
  5709. return true;
  5710. }
  5711. // defProc in implementation section → extract calls but don't create duplicate nodes
  5712. if (nodeType === 'defProc') {
  5713. this.extractPascalDefProc(node);
  5714. return true;
  5715. }
  5716. // declProp → property node
  5717. if (nodeType === 'declProp') {
  5718. const nameNode = getChildByField(node, 'name');
  5719. if (nameNode) {
  5720. const name = getNodeText(nameNode, this.source);
  5721. const visibility = this.extractor!.getVisibility?.(node);
  5722. this.createNode('property', name, node, { visibility });
  5723. }
  5724. return true;
  5725. }
  5726. // declField → field node
  5727. if (nodeType === 'declField') {
  5728. const nameNode = getChildByField(node, 'name');
  5729. if (nameNode) {
  5730. const name = getNodeText(nameNode, this.source);
  5731. const visibility = this.extractor!.getVisibility?.(node);
  5732. this.createNode('field', name, node, { visibility });
  5733. }
  5734. return true;
  5735. }
  5736. // declSection → visit children (propagates visibility via getVisibility)
  5737. if (nodeType === 'declSection') {
  5738. for (let i = 0; i < node.namedChildCount; i++) {
  5739. const child = node.namedChild(i);
  5740. if (child) this.visitNode(child);
  5741. }
  5742. return true;
  5743. }
  5744. // exprCall → extract function call reference
  5745. if (nodeType === 'exprCall') {
  5746. this.extractPascalCall(node);
  5747. return true;
  5748. }
  5749. // interface/implementation sections → visit children
  5750. if (nodeType === 'interface' || nodeType === 'implementation') {
  5751. for (let i = 0; i < node.namedChildCount; i++) {
  5752. const child = node.namedChild(i);
  5753. if (child) this.visitNode(child);
  5754. }
  5755. return true;
  5756. }
  5757. // block (begin..end) → visit for calls
  5758. if (nodeType === 'block') {
  5759. this.visitPascalBlock(node);
  5760. return true;
  5761. }
  5762. return false;
  5763. }
  5764. /**
  5765. * Extract a Pascal declType node (class, interface, enum, or type alias)
  5766. */
  5767. private extractPascalDeclType(node: SyntaxNode): void {
  5768. const nameNode = getChildByField(node, 'name');
  5769. if (!nameNode) return;
  5770. const name = getNodeText(nameNode, this.source);
  5771. // Find the inner type declaration
  5772. const declClass = node.namedChildren.find(
  5773. (c: SyntaxNode) => c.type === 'declClass'
  5774. );
  5775. const declIntf = node.namedChildren.find(
  5776. (c: SyntaxNode) => c.type === 'declIntf'
  5777. );
  5778. const typeChild = node.namedChildren.find(
  5779. (c: SyntaxNode) => c.type === 'type'
  5780. );
  5781. if (declClass) {
  5782. const classNode = this.createNode('class', name, node);
  5783. if (classNode) {
  5784. // Extract inheritance from typeref children of declClass
  5785. this.extractPascalInheritance(declClass, classNode.id);
  5786. // Visit class body
  5787. this.nodeStack.push(classNode.id);
  5788. for (let i = 0; i < declClass.namedChildCount; i++) {
  5789. const child = declClass.namedChild(i);
  5790. if (child) this.visitNode(child);
  5791. }
  5792. this.nodeStack.pop();
  5793. }
  5794. } else if (declIntf) {
  5795. const ifaceNode = this.createNode('interface', name, node);
  5796. if (ifaceNode) {
  5797. // Visit interface members
  5798. this.nodeStack.push(ifaceNode.id);
  5799. for (let i = 0; i < declIntf.namedChildCount; i++) {
  5800. const child = declIntf.namedChild(i);
  5801. if (child) this.visitNode(child);
  5802. }
  5803. this.nodeStack.pop();
  5804. }
  5805. } else if (typeChild) {
  5806. // Check if it contains a declEnum
  5807. const declEnum = typeChild.namedChildren.find(
  5808. (c: SyntaxNode) => c.type === 'declEnum'
  5809. );
  5810. if (declEnum) {
  5811. const enumNode = this.createNode('enum', name, node);
  5812. if (enumNode) {
  5813. // Extract enum members
  5814. this.nodeStack.push(enumNode.id);
  5815. for (let i = 0; i < declEnum.namedChildCount; i++) {
  5816. const child = declEnum.namedChild(i);
  5817. if (child?.type === 'declEnumValue') {
  5818. const memberName = getChildByField(child, 'name');
  5819. if (memberName) {
  5820. this.createNode('enum_member', getNodeText(memberName, this.source), child);
  5821. }
  5822. }
  5823. }
  5824. this.nodeStack.pop();
  5825. }
  5826. } else {
  5827. // Simple type alias: type TFoo = string / type TFoo = Integer
  5828. this.createNode('type_alias', name, node);
  5829. }
  5830. } else {
  5831. // Fallback: could be a forward declaration or simple alias
  5832. this.createNode('type_alias', name, node);
  5833. }
  5834. }
  5835. /**
  5836. * Extract Pascal uses clause into individual import nodes
  5837. */
  5838. private extractPascalUses(node: SyntaxNode): void {
  5839. const importText = getNodeText(node, this.source).trim();
  5840. for (let i = 0; i < node.namedChildCount; i++) {
  5841. const child = node.namedChild(i);
  5842. if (child?.type === 'moduleName') {
  5843. const unitName = getNodeText(child, this.source);
  5844. this.createNode('import', unitName, child, {
  5845. signature: importText,
  5846. });
  5847. // Create unresolved reference for resolution
  5848. if (this.nodeStack.length > 0) {
  5849. const parentId = this.nodeStack[this.nodeStack.length - 1];
  5850. if (parentId) {
  5851. this.unresolvedReferences.push({
  5852. fromNodeId: parentId,
  5853. referenceName: unitName,
  5854. referenceKind: 'imports',
  5855. line: child.startPosition.row + 1,
  5856. column: child.startPosition.column,
  5857. });
  5858. }
  5859. }
  5860. }
  5861. }
  5862. }
  5863. /**
  5864. * Extract a Pascal constant declaration
  5865. */
  5866. private extractPascalConst(node: SyntaxNode): void {
  5867. const nameNode = getChildByField(node, 'name');
  5868. if (!nameNode) return;
  5869. const name = getNodeText(nameNode, this.source);
  5870. const defaultValue = node.namedChildren.find(
  5871. (c: SyntaxNode) => c.type === 'defaultValue'
  5872. );
  5873. const sig = defaultValue ? getNodeText(defaultValue, this.source) : undefined;
  5874. this.createNode('constant', name, node, { signature: sig });
  5875. }
  5876. /**
  5877. * Extract Pascal inheritance (extends/implements) from declClass typeref children
  5878. */
  5879. private extractPascalInheritance(declClass: SyntaxNode, classId: string): void {
  5880. const typerefs = declClass.namedChildren.filter(
  5881. (c: SyntaxNode) => c.type === 'typeref'
  5882. );
  5883. for (let i = 0; i < typerefs.length; i++) {
  5884. const ref = typerefs[i]!;
  5885. const name = getNodeText(ref, this.source);
  5886. this.unresolvedReferences.push({
  5887. fromNodeId: classId,
  5888. referenceName: name,
  5889. referenceKind: i === 0 ? 'extends' : 'implements',
  5890. line: ref.startPosition.row + 1,
  5891. column: ref.startPosition.column,
  5892. });
  5893. }
  5894. }
  5895. /**
  5896. * Extract calls and resolve method context from a Pascal defProc (implementation body).
  5897. * Does not create a new node — the declaration was already captured from the interface section.
  5898. */
  5899. private extractPascalDefProc(node: SyntaxNode): void {
  5900. // Find the matching declaration node by name to use as call parent
  5901. const declProc = node.namedChildren.find(
  5902. (c: SyntaxNode) => c.type === 'declProc'
  5903. );
  5904. if (!declProc) return;
  5905. const nameNode = getChildByField(declProc, 'name');
  5906. if (!nameNode) return;
  5907. const fullName = getNodeText(nameNode, this.source).trim();
  5908. // fullName is like "TAuthService.Create"
  5909. const shortName = fullName.includes('.') ? fullName.split('.').pop()! : fullName;
  5910. const fullNameKey = fullName.toLowerCase();
  5911. const shortNameKey = shortName.toLowerCase();
  5912. // Build method index on first use (O(n) once, then O(1) per lookup)
  5913. if (!this.methodIndex) {
  5914. this.methodIndex = new Map();
  5915. for (const n of this.nodes) {
  5916. if (n.kind === 'method' || n.kind === 'function') {
  5917. const nameKey = n.name.toLowerCase();
  5918. // Keep first seen short-name mapping to avoid silently overwriting earlier entries.
  5919. if (!this.methodIndex.has(nameKey)) {
  5920. this.methodIndex.set(nameKey, n.id);
  5921. }
  5922. // For Pascal methods, also index qualified forms (e.g. TAuthService.Create).
  5923. if (n.kind === 'method') {
  5924. const qualifiedParts = n.qualifiedName.split('::');
  5925. if (qualifiedParts.length >= 2) {
  5926. // Create suffix keys so both "Module.Class.Method" and "Class.Method" can resolve.
  5927. for (let i = 0; i < qualifiedParts.length - 1; i++) {
  5928. const scopedName = qualifiedParts.slice(i).join('.').toLowerCase();
  5929. this.methodIndex.set(scopedName, n.id);
  5930. }
  5931. }
  5932. }
  5933. }
  5934. }
  5935. }
  5936. let parentId =
  5937. this.methodIndex.get(fullNameKey) ||
  5938. this.methodIndex.get(shortNameKey);
  5939. // No existing node? This is an implementation-only **free** procedure/function
  5940. // (`procedure Helper; begin … end;` with no interface declaration and not a
  5941. // class method). Create a function node so its body's calls attribute to it,
  5942. // not to the enclosing file/module. A method (`TClass.Method`, a dotted name)
  5943. // always has a node from its class declaration, so this only fires for free
  5944. // routines — and the methodIndex lookup above already covers interface-declared
  5945. // free routines, so there's no duplicate.
  5946. if (!parentId && !fullName.includes('.')) {
  5947. const fnNode = this.createNode('function', fullName, declProc, {
  5948. signature: this.extractor?.getSignature?.(declProc, this.source),
  5949. visibility: this.extractor?.getVisibility?.(declProc),
  5950. });
  5951. if (fnNode) {
  5952. parentId = fnNode.id;
  5953. this.methodIndex.set(fullNameKey, fnNode.id);
  5954. if (!this.methodIndex.has(shortNameKey)) this.methodIndex.set(shortNameKey, fnNode.id);
  5955. }
  5956. }
  5957. if (!parentId) parentId = this.nodeStack[this.nodeStack.length - 1];
  5958. if (!parentId) return;
  5959. // Visit the block for calls
  5960. const block = node.namedChildren.find(
  5961. (c: SyntaxNode) => c.type === 'block'
  5962. );
  5963. if (block) {
  5964. this.nodeStack.push(parentId);
  5965. this.visitPascalBlock(block);
  5966. this.nodeStack.pop();
  5967. }
  5968. }
  5969. /**
  5970. * Extract function calls from a Pascal expression
  5971. */
  5972. private extractPascalCall(node: SyntaxNode): void {
  5973. if (this.nodeStack.length === 0) return;
  5974. const callerId = this.nodeStack[this.nodeStack.length - 1];
  5975. if (!callerId) return;
  5976. // Get the callee name — first child is typically the identifier or exprDot
  5977. const firstChild = node.namedChild(0);
  5978. if (!firstChild) return;
  5979. let calleeName = '';
  5980. if (firstChild.type === 'exprDot') {
  5981. // Chained static-factory call: `TFoo.GetInstance().DoIt()` — the exprDot's
  5982. // receiver is itself an `exprCall`, so the bare identifier list would
  5983. // collapse to just `DoIt` and mis-resolve to a same-named method on an
  5984. // unrelated class. Encode `TFoo.GetInstance().DoIt` so resolution infers
  5985. // DoIt's class from what `TFoo.GetInstance` RETURNS (#645/#608). Only a
  5986. // capitalized class-factory chain; a unary outer method.
  5987. const innerCall = firstChild.namedChildren.find((c: SyntaxNode) => c.type === 'exprCall');
  5988. const outerId = firstChild.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  5989. const method = outerId ? getNodeText(outerId, this.source) : '';
  5990. if (innerCall && method && /^\w+$/.test(method)) {
  5991. const innerFirst = innerCall.namedChild(0);
  5992. let innerCallee = '';
  5993. if (innerFirst?.type === 'exprDot') {
  5994. innerCallee = innerFirst.namedChildren
  5995. .filter((c: SyntaxNode) => c.type === 'identifier')
  5996. .map((id: SyntaxNode) => getNodeText(id, this.source))
  5997. .join('.');
  5998. } else if (innerFirst?.type === 'identifier') {
  5999. innerCallee = getNodeText(innerFirst, this.source);
  6000. }
  6001. // Gate on the Delphi type-naming convention — `TFoo` classes / `IFoo`
  6002. // interfaces — so a class-factory chain re-encodes but a capitalized
  6003. // VARIABLE/parameter chain (Pascal capitalizes locals too: `Curve.X().Y()`,
  6004. // `Self.X().Y()`) stays bare and keeps its existing bare-name resolution.
  6005. calleeName = innerCallee && /^[TI][A-Z]/.test(innerCallee)
  6006. ? `${innerCallee}().${method}`
  6007. : method;
  6008. } else {
  6009. // Qualified call: Obj.Method(...)
  6010. const identifiers = firstChild.namedChildren.filter(
  6011. (c: SyntaxNode) => c.type === 'identifier'
  6012. );
  6013. if (identifiers.length > 0) {
  6014. calleeName = identifiers.map((id: SyntaxNode) => getNodeText(id, this.source)).join('.');
  6015. }
  6016. }
  6017. } else if (firstChild.type === 'identifier') {
  6018. calleeName = getNodeText(firstChild, this.source);
  6019. }
  6020. if (calleeName) {
  6021. this.unresolvedReferences.push({
  6022. fromNodeId: callerId,
  6023. referenceName: calleeName,
  6024. referenceKind: 'calls',
  6025. line: node.startPosition.row + 1,
  6026. column: node.startPosition.column,
  6027. });
  6028. }
  6029. // Also visit arguments for nested calls
  6030. const args = node.namedChildren.find(
  6031. (c: SyntaxNode) => c.type === 'exprArgs'
  6032. );
  6033. if (args) {
  6034. this.visitPascalBlock(args);
  6035. }
  6036. }
  6037. /**
  6038. * Extract a PAREN-LESS Pascal method/procedure call (`Obj.Method;`,
  6039. * `TFoo.GetInstance.DoIt;`). Pascal lets a no-arg method drop its parens, so it
  6040. * parses as a bare `exprDot` (not an `exprCall`). A bare `exprDot` is
  6041. * syntactically identical to a field/property access, so this is only ever
  6042. * called for a STATEMENT-level exprDot (caller-gated): a bare `Obj.Field;`
  6043. * statement is a no-op, so a statement-level dot expression is a call. (An
  6044. * exprDot in assignment LHS/RHS or a condition is left alone — there it really
  6045. * can be a field/property read.)
  6046. */
  6047. private extractPascalParenlessCall(node: SyntaxNode): void {
  6048. if (this.nodeStack.length === 0) return;
  6049. const callerId = this.nodeStack[this.nodeStack.length - 1];
  6050. if (!callerId) return;
  6051. const receiver = node.namedChild(0);
  6052. const outerId = node.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  6053. const method = outerId ? getNodeText(outerId, this.source) : '';
  6054. if (!method) return;
  6055. let calleeName = '';
  6056. // Chained: the receiver is itself a call — a paren-less `TFoo.GetInstance` (an
  6057. // inner exprDot) or a paren'd `TFoo.GetInstance()` (an exprCall). Encode the
  6058. // chain `TFoo.GetInstance().DoIt` so resolution infers DoIt's class from what
  6059. // the factory RETURNS (#645/#608), gated on the Delphi `TFoo`/`IFoo` type
  6060. // convention; a capitalized VARIABLE chain stays a bare method name.
  6061. if ((receiver?.type === 'exprDot' || receiver?.type === 'exprCall') && /^\w+$/.test(method)) {
  6062. const innerCalleeNode = receiver.type === 'exprCall' ? receiver.namedChild(0) : receiver;
  6063. const innerCallee = !innerCalleeNode
  6064. ? ''
  6065. : innerCalleeNode.type === 'identifier'
  6066. ? getNodeText(innerCalleeNode, this.source)
  6067. : innerCalleeNode.namedChildren
  6068. .filter((c: SyntaxNode) => c.type === 'identifier')
  6069. .map((id: SyntaxNode) => getNodeText(id, this.source))
  6070. .join('.');
  6071. if (innerCallee && /^[TI][A-Z]/.test(innerCallee)) {
  6072. calleeName = `${innerCallee}().${method}`;
  6073. // The T/I-prefixed inner is itself a real call — record it too.
  6074. if (receiver.type === 'exprCall') this.extractPascalCall(receiver);
  6075. else this.extractPascalParenlessCall(receiver);
  6076. } else {
  6077. calleeName = method; // non-class receiver: a bare method ref (no field-access ref)
  6078. }
  6079. } else {
  6080. // Simple: `Obj.Method` → the dotted name (resolves via the receiver / bare name).
  6081. calleeName = node.namedChildren
  6082. .filter((c: SyntaxNode) => c.type === 'identifier')
  6083. .map((id: SyntaxNode) => getNodeText(id, this.source))
  6084. .join('.');
  6085. }
  6086. if (calleeName) {
  6087. this.unresolvedReferences.push({
  6088. fromNodeId: callerId,
  6089. referenceName: calleeName,
  6090. referenceKind: 'calls',
  6091. line: node.startPosition.row + 1,
  6092. column: node.startPosition.column,
  6093. });
  6094. }
  6095. }
  6096. /**
  6097. * Recursively visit a Pascal block/statement tree for call expressions
  6098. */
  6099. private visitPascalBlock(node: SyntaxNode): void {
  6100. for (let i = 0; i < node.namedChildCount; i++) {
  6101. const child = node.namedChild(i);
  6102. if (!child) continue;
  6103. // Function-as-value capture (#756): Pascal bodies are walked here, not
  6104. // in visitNode/visitForCallsAndStructure, so the capture hook fires here
  6105. // — assignment RHS is the Delphi event-wiring idiom (`OnFire := Handler`).
  6106. this.maybeCaptureFnRefs(child, child.type);
  6107. if (child.type === 'exprCall') {
  6108. this.extractPascalCall(child);
  6109. // The walker doesn't descend into a call's arguments — dispatch the
  6110. // argument container directly (`RegisterHandler(TargetCb)` / `(@Cb)`).
  6111. const args = child.namedChildren.find((c: SyntaxNode) => c.type === 'exprArgs');
  6112. if (args) this.maybeCaptureFnRefs(args, 'exprArgs');
  6113. } else if (child.type === 'exprDot') {
  6114. // A STATEMENT-level bare exprDot is a paren-less call (`Obj.Free;`,
  6115. // `TFoo.GetInstance.DoIt;`). Anywhere else (assignment side, condition,
  6116. // expression) a bare exprDot is ambiguous with a field/property access,
  6117. // so there we only descend for paren'd inner calls.
  6118. if (node.type === 'statement') {
  6119. this.extractPascalParenlessCall(child);
  6120. } else {
  6121. for (let j = 0; j < child.namedChildCount; j++) {
  6122. const grandchild = child.namedChild(j);
  6123. if (grandchild?.type === 'exprCall') {
  6124. this.extractPascalCall(grandchild);
  6125. }
  6126. }
  6127. }
  6128. } else {
  6129. this.visitPascalBlock(child);
  6130. }
  6131. }
  6132. }
  6133. }
  6134. /**
  6135. * Extract nodes and edges from source code.
  6136. *
  6137. * If `frameworkNames` is provided, framework-specific extractors matching
  6138. * those names and the file's language are run after the tree-sitter pass.
  6139. * Their nodes/references/errors are merged into the returned result.
  6140. */
  6141. export function extractFromSource(
  6142. filePath: string,
  6143. source: string,
  6144. language?: Language,
  6145. frameworkNames?: string[]
  6146. ): ExtractionResult {
  6147. const detectedLanguage = language || detectLanguage(filePath, source);
  6148. const fileExtension = path.extname(filePath).toLowerCase();
  6149. let result: ExtractionResult;
  6150. // Use custom extractor for Svelte
  6151. if (detectedLanguage === 'svelte') {
  6152. const extractor = new SvelteExtractor(filePath, source);
  6153. result = extractor.extract();
  6154. } else if (detectedLanguage === 'vue') {
  6155. // Use custom extractor for Vue
  6156. const extractor = new VueExtractor(filePath, source);
  6157. result = extractor.extract();
  6158. } else if (detectedLanguage === 'astro') {
  6159. // Use custom extractor for Astro (frontmatter + template delegation)
  6160. const extractor = new AstroExtractor(filePath, source);
  6161. result = extractor.extract();
  6162. } else if (detectedLanguage === 'liquid') {
  6163. // Use custom extractor for Liquid
  6164. const extractor = new LiquidExtractor(filePath, source);
  6165. result = extractor.extract();
  6166. } else if (detectedLanguage === 'razor') {
  6167. // Use custom extractor for ASP.NET Razor (.cshtml) / Blazor (.razor) markup
  6168. const extractor = new RazorExtractor(filePath, source);
  6169. result = extractor.extract();
  6170. } else if (detectedLanguage === 'xml') {
  6171. // Custom extractor for MyBatis mapper XML. Non-mapper XML returns just a
  6172. // file node so the watcher tracks it without emitting symbols.
  6173. const extractor = new MyBatisExtractor(filePath, source);
  6174. result = extractor.extract();
  6175. } else if (detectedLanguage === 'cfml' || detectedLanguage === 'cfscript') {
  6176. // Custom extractor for CFML (.cfc/.cfm) — dialect-switches between the
  6177. // tag-based cfml grammar and the bare-script cfscript grammar. Standalone
  6178. // `.cfs` files (language 'cfscript') are always pure script (never `<`-led),
  6179. // so routing them through here too gets them the same anonymous-component
  6180. // filename fallback as a bare-script `.cfc` — without it a `.cfs` whose
  6181. // `component { ... }` declares no name (the grammar has no `name` field;
  6182. // CFML never spells one in source) stays `<anonymous>`.
  6183. const extractor = new CfmlExtractor(filePath, source, detectedLanguage);
  6184. result = extractor.extract();
  6185. } else if (isFileLevelOnlyLanguage(detectedLanguage)) {
  6186. // No symbol extraction at this stage — files are tracked at the file-record
  6187. // level only. Framework extractors (Drupal routing yml, Spring `@Value`
  6188. // resolution against application.yml/application.properties) run later and
  6189. // add per-file nodes/references when they apply.
  6190. result = { nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: 0 };
  6191. } else if (
  6192. detectedLanguage === 'pascal' &&
  6193. (fileExtension === '.dfm' || fileExtension === '.fmx')
  6194. ) {
  6195. // Use custom extractor for DFM/FMX form files
  6196. const extractor = new DfmExtractor(filePath, source);
  6197. result = extractor.extract();
  6198. } else {
  6199. const extractor = new TreeSitterExtractor(filePath, source, detectedLanguage);
  6200. result = extractor.extract();
  6201. }
  6202. // Framework-specific extraction (routes, middleware, etc.)
  6203. if (frameworkNames && frameworkNames.length > 0) {
  6204. const allResolvers = getAllFrameworkResolvers();
  6205. const applicable = getApplicableFrameworks(
  6206. allResolvers.filter((r) => frameworkNames.includes(r.name)),
  6207. detectedLanguage
  6208. );
  6209. for (const fw of applicable) {
  6210. if (!fw.extract) continue;
  6211. try {
  6212. const fwResult = fw.extract(filePath, source);
  6213. result.nodes.push(...fwResult.nodes);
  6214. result.unresolvedReferences.push(...fwResult.references);
  6215. } catch (err) {
  6216. result.errors.push({
  6217. message: `Framework extractor '${fw.name}' failed: ${
  6218. err instanceof Error ? err.message : String(err)
  6219. }`,
  6220. filePath,
  6221. severity: 'warning',
  6222. });
  6223. }
  6224. }
  6225. }
  6226. return result;
  6227. }