tree-sitter.ts 204 KB

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