tree-sitter.ts 210 KB

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