tree-sitter.ts 302 KB

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