tree-sitter.ts 262 KB

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