tree-sitter.ts 277 KB

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