tree-sitter.ts 184 KB

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