tree-sitter.ts 302 KB

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