tree-sitter.ts 259 KB

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