tree-sitter.ts 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552
  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 if (receiverField && receiverField.type === 'message_expression' && /^\w+$/.test(methodName)) {
  2299. // Chained message send `[[Foo create] doIt]` — the receiver is itself a
  2300. // class message. Recover the inner `Class.selector` and encode
  2301. // `Class.selector().doIt` so resolution infers doIt's class from what
  2302. // `Class.selector` RETURNS (#645/#608). Only a CLASS-factory chain
  2303. // (capitalized inner receiver); a unary outer selector is required
  2304. // because the chain resolver's method part is `\w+` (no `:`). An
  2305. // instance chain (`[[obj foo] bar]`, lowercase inner) stays bare.
  2306. const innerRecv = getChildByField(receiverField, 'receiver');
  2307. const innerRecvName = innerRecv ? getNodeText(innerRecv, this.source) : '';
  2308. if (innerRecv?.type === 'identifier' && /^[A-Z]/.test(innerRecvName)) {
  2309. const innerKw: string[] = [];
  2310. for (let i = 0; i < receiverField.namedChildCount; i++) {
  2311. if (receiverField.fieldNameForNamedChild(i) === 'method') {
  2312. const kw = receiverField.namedChild(i);
  2313. if (kw) innerKw.push(getNodeText(kw, this.source));
  2314. }
  2315. }
  2316. let innerColon = false;
  2317. for (let i = 0; i < receiverField.childCount; i++) {
  2318. if (receiverField.child(i)?.type === ':') { innerColon = true; break; }
  2319. }
  2320. const innerSelector = innerColon ? innerKw.map((k) => `${k}:`).join('') : innerKw[0];
  2321. calleeName = innerSelector ? `${innerRecvName}.${innerSelector}().${methodName}` : methodName;
  2322. } else {
  2323. calleeName = methodName;
  2324. }
  2325. } else {
  2326. calleeName = methodName;
  2327. }
  2328. }
  2329. } else {
  2330. const func = getChildByField(node, 'function') || node.namedChild(0);
  2331. if (func) {
  2332. if (func.type === 'member_expression' || func.type === 'attribute' || func.type === 'selector_expression' || func.type === 'navigation_expression' || func.type === 'field_expression') {
  2333. // Method call: obj.method() or obj.field.method()
  2334. // Go uses selector_expression with 'field', JS/TS uses member_expression with 'property'
  2335. // Kotlin uses navigation_expression with navigation_suffix > simple_identifier
  2336. // C/C++ use field_expression for both `obj.method()` and `ptr->method()`
  2337. let property = getChildByField(func, 'property') || getChildByField(func, 'field');
  2338. if (!property) {
  2339. const child1 = func.namedChild(1);
  2340. // Kotlin: navigation_suffix wraps the method name — extract simple_identifier from it
  2341. if (child1?.type === 'navigation_suffix') {
  2342. property = child1.namedChildren.find((c: SyntaxNode) => c.type === 'simple_identifier') ?? child1;
  2343. } else {
  2344. property = child1;
  2345. }
  2346. }
  2347. if (property) {
  2348. const methodName = getNodeText(property, this.source);
  2349. // Include receiver name for qualified resolution (e.g., console.print → "console.print")
  2350. // This helps the resolver distinguish method calls from bare function calls
  2351. // (e.g., Python's console.print() vs builtin print())
  2352. // Skip self/this/cls as they don't aid resolution
  2353. const receiver =
  2354. getChildByField(func, 'object') ||
  2355. getChildByField(func, 'operand') ||
  2356. getChildByField(func, 'argument') ||
  2357. func.namedChild(0);
  2358. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super']);
  2359. if (receiver && (receiver.type === 'identifier' || receiver.type === 'simple_identifier' || receiver.type === 'field_identifier')) {
  2360. const receiverName = getNodeText(receiver, this.source);
  2361. if (!SKIP_RECEIVERS.has(receiverName)) {
  2362. calleeName = `${receiverName}.${methodName}`;
  2363. } else {
  2364. calleeName = methodName;
  2365. }
  2366. } else if (
  2367. (this.language === 'cpp' ||
  2368. this.language === 'c' ||
  2369. this.language === 'kotlin' ||
  2370. this.language === 'swift' ||
  2371. this.language === 'rust' ||
  2372. this.language === 'go' ||
  2373. this.language === 'scala') &&
  2374. receiver &&
  2375. receiver.type === 'call_expression'
  2376. ) {
  2377. // Receiver that is itself a call — `Foo::instance().bar()`,
  2378. // `openSession()->run()`, `mgr.view().render()` (C/C++),
  2379. // `Foo.getInstance().bar()` (Kotlin) / `Foo.make().draw()` (Swift),
  2380. // `Foo::new().bar()` (Rust), or `New().Method()` (Go). Keep the inner
  2381. // call so resolution can infer bar()'s class from what the inner call
  2382. // RETURNS (#645/#608). Encode as `<innerCallee>().<method>`; the `().`
  2383. // marker never appears in an ordinary ref, so the resolver can detect
  2384. // and split it. Other languages keep the bare-name behavior below.
  2385. let innerCallee: string;
  2386. let reencode: boolean;
  2387. if (this.language === 'kotlin' || this.language === 'swift') {
  2388. // tree-sitter-kotlin/swift expose the inner callee as the
  2389. // call_expression's first named child (a navigation_expression
  2390. // `Foo.getInstance`, or a bare identifier for a free/constructor call).
  2391. const innerNav = receiver.namedChild(0);
  2392. innerCallee = innerNav ? getNodeText(innerNav, this.source).replace(/\s+/g, '') : '';
  2393. // Only re-encode a CLASS / companion-factory / constructor chain,
  2394. // whose receiver chain starts with a capitalized type
  2395. // (`Foo.getInstance().bar()`, `Foo().bar()`). An instance chain
  2396. // (`list.filter{}.map{}`) has a lowercase receiver whose type we
  2397. // can't recover here — re-encoding it would only drop the edge (no
  2398. // chain resolution, no bare-name fallback), regressing recall in
  2399. // fluent codebases. Leave those to the bare-name path.
  2400. reencode = /^[A-Z]/.test(innerCallee);
  2401. } else {
  2402. const innerFn = getChildByField(receiver, 'function');
  2403. innerCallee = innerFn
  2404. ? getNodeText(innerFn, this.source).replace(/->/g, '.').replace(/\s+/g, '')
  2405. : '';
  2406. // Rust: only re-encode an associated-function chain
  2407. // (`Foo::new().bar()`), whose inner callee is a path/`scoped_identifier`.
  2408. // Go: only a bare package-level factory chain (`New().Method()`),
  2409. // whose inner callee is an `identifier`. An instance chain
  2410. // (`x.foo().bar()` Rust, `obj.Method().Other()` Go) keeps bare-name —
  2411. // the resolver can't recover a variable's type, so re-encoding would
  2412. // only drop the edge. C/C++ re-encode any inner.
  2413. if (this.language === 'rust') reencode = innerFn?.type === 'scoped_identifier';
  2414. else if (this.language === 'go') reencode = innerFn?.type === 'identifier';
  2415. // Scala: only a companion-factory / case-class-apply chain whose
  2416. // receiver chain starts with a capitalized type (`Foo.create().bar()`,
  2417. // `Foo(args).bar()`). An instance chain (`list.map().filter()`) has a
  2418. // lowercase receiver whose type we can't recover — leave it bare.
  2419. else if (this.language === 'scala') reencode = /^[A-Z]/.test(innerCallee);
  2420. else reencode = !!innerCallee;
  2421. }
  2422. calleeName = reencode ? `${innerCallee}().${methodName}` : methodName;
  2423. } else {
  2424. calleeName = methodName;
  2425. }
  2426. }
  2427. } else if (func.type === 'scoped_identifier' || func.type === 'scoped_call_expression') {
  2428. // Scoped call: Module::function()
  2429. calleeName = getNodeText(func, this.source);
  2430. } else if (this.language === 'csharp' && func.type === 'member_access_expression') {
  2431. // C# member call `recv.Method(...)`. When the receiver is itself a call
  2432. // — a chained factory `Foo.Create(args).Bar()` — encode `inner().Bar`
  2433. // with normalized empty parens so resolution can infer Bar's class from
  2434. // what `Foo.Create` RETURNS (#645/#608). A non-call receiver keeps the
  2435. // full member-access text (the existing `recv.Method` behavior).
  2436. const recv = getChildByField(func, 'expression');
  2437. const nameNode = getChildByField(func, 'name');
  2438. const methodName = nameNode ? getNodeText(nameNode, this.source) : '';
  2439. if (recv && recv.type === 'invocation_expression' && methodName) {
  2440. const innerFunc = getChildByField(recv, 'function');
  2441. const innerCallee = innerFunc ? getNodeText(innerFunc, this.source).replace(/\s+/g, '') : '';
  2442. calleeName = innerCallee ? `${innerCallee}().${methodName}` : methodName;
  2443. } else {
  2444. calleeName = getNodeText(func, this.source);
  2445. }
  2446. } else {
  2447. calleeName = getNodeText(func, this.source);
  2448. }
  2449. }
  2450. }
  2451. // Parenthesized type conversions — Go `(*T)(x)` / `(T)(x)` (and a
  2452. // parenthesized callee generally) parse as a call whose "function" is a
  2453. // parenthesized type/expression, so the callee text is the un-resolvable
  2454. // literal `(*T)`. Normalize to the inner name so it resolves to `T` (a real
  2455. // dependency on the converted-to type) instead of dropping on the floor.
  2456. if (calleeName) {
  2457. const conv = calleeName.match(/^\(\s*\*?\s*([A-Za-z_][\w.]*)\s*\)$/);
  2458. if (conv && conv[1]) calleeName = conv[1];
  2459. }
  2460. if (calleeName) {
  2461. this.unresolvedReferences.push({
  2462. fromNodeId: callerId,
  2463. referenceName: calleeName,
  2464. referenceKind: 'calls',
  2465. line: node.startPosition.row + 1,
  2466. column: node.startPosition.column,
  2467. });
  2468. }
  2469. }
  2470. /**
  2471. * `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  2472. * emit an `instantiates` reference to the class name. The resolver
  2473. * then links it to the class node, producing the `instantiates`
  2474. * edge that powers "what creates instances of X" queries.
  2475. *
  2476. * Children are still walked so nested calls inside the constructor
  2477. * arguments (`new Foo(bar())`) get their own `calls` references.
  2478. */
  2479. private extractInstantiation(node: SyntaxNode): void {
  2480. if (this.nodeStack.length === 0) return;
  2481. const fromId = this.nodeStack[this.nodeStack.length - 1];
  2482. if (!fromId) return;
  2483. // The class name is in the `constructor`/`type`/first-named-child
  2484. // depending on grammar.
  2485. const ctor =
  2486. getChildByField(node, 'constructor') ||
  2487. getChildByField(node, 'type') ||
  2488. getChildByField(node, 'name') ||
  2489. node.namedChild(0);
  2490. if (!ctor) return;
  2491. // Go composite literals: `Widget{...}` (same package) and `pkga.Widget{...}`
  2492. // (cross-package). Only a directly-named struct type is a meaningful
  2493. // instantiation target — skip slice/map/array literals (`[]T{}`,
  2494. // `map[K]V{}`) whose `type` field is a composite type, not a named type.
  2495. // Unlike `new ns.Foo()`, KEEP the package qualifier (`pkga.Widget`) so the
  2496. // Go cross-package resolver can disambiguate it to the right package's type.
  2497. if (node.type === 'composite_literal') {
  2498. if (ctor.type !== 'type_identifier' && ctor.type !== 'qualified_type') return;
  2499. let goType = getNodeText(ctor, this.source).trim();
  2500. const brIdx = goType.indexOf('['); // strip Go generic args: `Box[T]{}` -> `Box`
  2501. if (brIdx > 0) goType = goType.slice(0, brIdx).trim();
  2502. if (goType) {
  2503. this.unresolvedReferences.push({
  2504. fromNodeId: fromId,
  2505. referenceName: goType,
  2506. referenceKind: 'instantiates',
  2507. line: node.startPosition.row + 1,
  2508. column: node.startPosition.column,
  2509. });
  2510. }
  2511. return;
  2512. }
  2513. // Scala: `new Monoid[Int] { ... }` — the constructor is a `generic_type`
  2514. // (or qualified `stable_type_identifier`) using `[...]` type args, which the
  2515. // generic `<...>` strip below misses. Unwrap to the base type name.
  2516. if (node.type === 'instance_expression') {
  2517. const name = scalaBaseTypeName(ctor, this.source);
  2518. if (name) {
  2519. this.unresolvedReferences.push({
  2520. fromNodeId: fromId,
  2521. referenceName: name,
  2522. referenceKind: 'instantiates',
  2523. line: node.startPosition.row + 1,
  2524. column: node.startPosition.column,
  2525. });
  2526. }
  2527. return;
  2528. }
  2529. let className = getNodeText(ctor, this.source);
  2530. // Strip type-argument suffix first: `new Map<K, V>()` would
  2531. // otherwise produce className 'Map<K, V>' (the constructor
  2532. // field is a `generic_type` node) and resolution would fail
  2533. // because no class is named with the angle-bracket suffix.
  2534. const ltIdx = className.indexOf('<');
  2535. if (ltIdx > 0) className = className.slice(0, ltIdx);
  2536. // For namespaced/qualified constructors (`new ns.Foo()`,
  2537. // `new ns::Foo()`) keep the trailing identifier — that's what
  2538. // matches a class node in the index.
  2539. const lastDot = Math.max(
  2540. className.lastIndexOf('.'),
  2541. className.lastIndexOf('::')
  2542. );
  2543. if (lastDot >= 0) className = className.slice(lastDot + 1).replace(/^[:.]/, '');
  2544. className = className.trim();
  2545. if (className) {
  2546. this.unresolvedReferences.push({
  2547. fromNodeId: fromId,
  2548. referenceName: className,
  2549. referenceKind: 'instantiates',
  2550. line: node.startPosition.row + 1,
  2551. column: node.startPosition.column,
  2552. });
  2553. }
  2554. }
  2555. /**
  2556. * Static-member / value-read pass. A type/enum/class used only via a member
  2557. * VALUE — `Enum.value`, `Type.CONST`, `Colors.red`, `Foo::BAR` — recorded no
  2558. * edge, because the body walker only handled CALLS (`Type.method()`). So a
  2559. * type referenced only by an enum value or a static field looked like nothing
  2560. * depended on it (the residual frontier across Dart/Java/C#/Swift/Kotlin/PHP).
  2561. * Emit a `references` edge to the capitalized receiver. Gated to languages
  2562. * where types are Capitalized by convention, and skipped when the access is a
  2563. * call's callee (the call extractor already links the method).
  2564. */
  2565. private extractStaticMemberRef(node: SyntaxNode): void {
  2566. if (!STATIC_MEMBER_LANGS.has(this.language)) return;
  2567. if (this.nodeStack.length === 0) return;
  2568. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  2569. if (!ownerId) return;
  2570. // Dart structures member access as an `identifier` + a sibling `selector`,
  2571. // not a single node. A value-read selector (no `argument_part`) whose
  2572. // previous sibling is a capitalized identifier is `Enum.value`.
  2573. if (this.language === 'dart') {
  2574. if (node.type !== 'selector') return;
  2575. if (node.namedChildren.some((c: SyntaxNode) => c.type === 'argument_part')) return;
  2576. const prev = node.previousNamedSibling;
  2577. if (prev?.type === 'identifier' && /^[A-Z][A-Za-z0-9_]*$/.test(prev.text)) {
  2578. this.pushStaticMemberRef(prev.text, ownerId, prev);
  2579. }
  2580. return;
  2581. }
  2582. if (!MEMBER_ACCESS_TYPES.has(node.type)) return;
  2583. // Skip `Type.method()` — the access is the callee of a call, already linked.
  2584. const parent = node.parent;
  2585. if (parent && this.extractor!.callTypes.includes(parent.type)) {
  2586. const callee =
  2587. getChildByField(parent, 'function') ??
  2588. getChildByField(parent, 'method') ??
  2589. parent.namedChild(0);
  2590. if (callee && callee.startIndex === node.startIndex) return;
  2591. }
  2592. // The receiver must be a SIMPLE capitalized identifier — `Type.X`, not the
  2593. // nested `a.B.c` (whose own head member-access is visited separately) nor a
  2594. // lowercase `obj.field` / `pkg.func`.
  2595. const recv =
  2596. getChildByField(node, 'object') ??
  2597. getChildByField(node, 'expression') ??
  2598. getChildByField(node, 'scope') ??
  2599. node.namedChild(0);
  2600. if (!recv) return;
  2601. const t = recv.type;
  2602. if (
  2603. t === 'identifier' || t === 'type_identifier' || t === 'simple_identifier' ||
  2604. t === 'name' || t === 'scoped_type_identifier'
  2605. ) {
  2606. const text = getNodeText(recv, this.source);
  2607. if (/^[A-Z][A-Za-z0-9_]*$/.test(text)) this.pushStaticMemberRef(text, ownerId, recv);
  2608. }
  2609. }
  2610. private pushStaticMemberRef(name: string, ownerId: string, node: SyntaxNode): void {
  2611. this.unresolvedReferences.push({
  2612. fromNodeId: ownerId,
  2613. referenceName: name,
  2614. referenceKind: 'references',
  2615. line: node.startPosition.row + 1,
  2616. column: node.startPosition.column,
  2617. });
  2618. }
  2619. /**
  2620. * Find a `class_body` child of an `object_creation_expression` — the
  2621. * marker for an anonymous class (`new T() { ... }`). Returns the body
  2622. * node so the caller can walk it as the anon class's members.
  2623. */
  2624. private findAnonymousClassBody(node: SyntaxNode): SyntaxNode | null {
  2625. for (let i = 0; i < node.namedChildCount; i++) {
  2626. const child = node.namedChild(i);
  2627. // Java: `class_body`. C# uses the same node kind.
  2628. if (child && (child.type === 'class_body' || child.type === 'declaration_list')) {
  2629. return child;
  2630. }
  2631. }
  2632. return null;
  2633. }
  2634. /**
  2635. * Extract a Java/C# anonymous class — `new T() { ...members }`. Emits a
  2636. * `class` node named `<T$anon@line>`, an `extends` reference to T (so
  2637. * Phase 5.5 interface-impl can bridge), and walks the body so its
  2638. * `method_declaration` members become method nodes under the anon class.
  2639. *
  2640. * Why this matters: without anon-class extraction, the overrides inside
  2641. * a lambda-returned `new T() { @Override int foo(){...} }` are not nodes,
  2642. * so a call through T.foo (the abstract parent method) has no static
  2643. * target — the agent has to Read the file to find the implementation.
  2644. */
  2645. private extractAnonymousClass(node: SyntaxNode, body: SyntaxNode): void {
  2646. if (!this.extractor) return;
  2647. // The instantiated type sits in the same field/position that
  2648. // extractInstantiation reads from. Use the same lookup so the anon
  2649. // class's `extends` target matches the `instantiates` edge.
  2650. const typeNode =
  2651. getChildByField(node, 'constructor') ||
  2652. getChildByField(node, 'type') ||
  2653. getChildByField(node, 'name') ||
  2654. node.namedChild(0);
  2655. let typeName = typeNode ? getNodeText(typeNode, this.source) : 'Object';
  2656. const ltIdx = typeName.indexOf('<');
  2657. if (ltIdx > 0) typeName = typeName.slice(0, ltIdx);
  2658. const lastDot = Math.max(typeName.lastIndexOf('.'), typeName.lastIndexOf('::'));
  2659. if (lastDot >= 0) typeName = typeName.slice(lastDot + 1).replace(/^[:.]/, '');
  2660. typeName = typeName.trim() || 'Object';
  2661. const anonName = `<${typeName}$anon@${node.startPosition.row + 1}>`;
  2662. const classNode = this.createNode('class', anonName, node, {});
  2663. if (!classNode) return;
  2664. // The anonymous class implicitly extends/implements the named type.
  2665. // We can't tell at extraction time whether T is a class or an interface,
  2666. // so emit `extends`. Resolution will still bind T to whatever it is, and
  2667. // Phase 5.5 (which already handles both `extends` and `implements`) will
  2668. // bridge T's methods to the override names found in the anon body.
  2669. this.unresolvedReferences.push({
  2670. fromNodeId: classNode.id,
  2671. referenceName: typeName,
  2672. referenceKind: 'extends',
  2673. line: typeNode?.startPosition.row ?? node.startPosition.row,
  2674. column: typeNode?.startPosition.column ?? node.startPosition.column,
  2675. });
  2676. // Walk the body's children so method_declaration nodes inside become
  2677. // method nodes scoped to the anon class.
  2678. this.nodeStack.push(classNode.id);
  2679. for (let i = 0; i < body.namedChildCount; i++) {
  2680. const child = body.namedChild(i);
  2681. if (child) this.visitNode(child);
  2682. }
  2683. this.nodeStack.pop();
  2684. }
  2685. /**
  2686. * Scan `declNode` and its preceding siblings (within the parent's
  2687. * named children) for decorator nodes, emitting a `decorates`
  2688. * reference from `decoratedId` to each decorator's function name.
  2689. *
  2690. * Why preceding siblings: in TypeScript, `@Foo class Bar {}` parses
  2691. * as an `export_statement` (or top-level wrapper) with the
  2692. * `decorator` as a child *before* the `class_declaration` — so the
  2693. * decorator isn't a child of the class itself. For methods/
  2694. * properties, the decorator IS a direct child of the declaration,
  2695. * so we also scan declNode.namedChildren.
  2696. *
  2697. * Idempotent across grammars: if neither location yields decorators
  2698. * (most non-decorator-using languages), the function is a no-op.
  2699. */
  2700. private extractDecoratorsFor(declNode: SyntaxNode, decoratedId: string): void {
  2701. const consider = (n: SyntaxNode | null): void => {
  2702. if (!n) return;
  2703. // `marker_annotation` is Java's grammar for arg-less annotations
  2704. // (`@Override`, `@Deprecated`); `attribute` is Swift's grammar for
  2705. // attributes and PROPERTY WRAPPERS (`@objc`, `@Argument`, `@Published`,
  2706. // `@State`). Without these, those usages would be silently skipped.
  2707. if (
  2708. n.type !== 'decorator' &&
  2709. n.type !== 'annotation' &&
  2710. n.type !== 'marker_annotation' &&
  2711. n.type !== 'attribute'
  2712. ) {
  2713. return;
  2714. }
  2715. // Find the leading identifier: skip the `@` punct, unwrap
  2716. // a call_expression if the decorator is invoked with args.
  2717. let target: SyntaxNode | null = null;
  2718. for (let i = 0; i < n.namedChildCount; i++) {
  2719. const child = n.namedChild(i);
  2720. if (!child) continue;
  2721. if (child.type === 'call_expression') {
  2722. const fn = getChildByField(child, 'function') ?? child.namedChild(0);
  2723. if (fn) target = fn;
  2724. if (target) break;
  2725. }
  2726. if (
  2727. child.type === 'identifier' ||
  2728. child.type === 'member_expression' ||
  2729. child.type === 'scoped_identifier' ||
  2730. child.type === 'navigation_expression' ||
  2731. child.type === 'user_type' || // swift attribute → user_type (`@Argument`)
  2732. child.type === 'type_identifier'
  2733. ) {
  2734. target = child;
  2735. break;
  2736. }
  2737. }
  2738. if (!target) return;
  2739. let name = getNodeText(target, this.source);
  2740. const lt = name.indexOf('<'); // strip generic args: `@Argument<T>` → `Argument`
  2741. if (lt > 0) name = name.slice(0, lt);
  2742. const lastDot = Math.max(name.lastIndexOf('.'), name.lastIndexOf('::'));
  2743. if (lastDot >= 0) name = name.slice(lastDot + 1).replace(/^[:.]/, '');
  2744. name = name.trim();
  2745. if (!name) return;
  2746. this.unresolvedReferences.push({
  2747. fromNodeId: decoratedId,
  2748. referenceName: name,
  2749. referenceKind: 'decorates',
  2750. line: n.startPosition.row + 1,
  2751. column: n.startPosition.column,
  2752. });
  2753. };
  2754. // 1. Decorators that are direct children of the declaration
  2755. // (method/property style, also some grammars for class).
  2756. for (let i = 0; i < declNode.namedChildCount; i++) {
  2757. const child = declNode.namedChild(i);
  2758. consider(child);
  2759. // Java/Kotlin/C# put annotations INSIDE a `modifiers` node
  2760. // (`@MyAnno public class X` → class_declaration → modifiers → annotation),
  2761. // so descend into it — otherwise every annotation usage is silently
  2762. // dropped and annotation types show zero dependents.
  2763. if (child && child.type === 'modifiers') {
  2764. for (let j = 0; j < child.namedChildCount; j++) {
  2765. consider(child.namedChild(j));
  2766. }
  2767. }
  2768. }
  2769. // 2. Decorators that are PRECEDING siblings of the declaration
  2770. // inside the parent's children (TypeScript class style).
  2771. // Walk BACKWARDS from the declaration and stop at the first
  2772. // non-decorator sibling — without that stop, decorators
  2773. // belonging to an EARLIER unrelated declaration leak in
  2774. // (e.g. `@A class Foo {} @B class Bar {}` would otherwise
  2775. // attribute @A to Bar).
  2776. //
  2777. // Note on identity: tree-sitter web bindings return fresh JS
  2778. // wrapper objects from `parent`/`namedChild` navigation, so
  2779. // `sibling === declNode` is unreliable — `startIndex` does
  2780. // the matching instead.
  2781. const parent = declNode.parent;
  2782. if (parent) {
  2783. const declStart = declNode.startIndex;
  2784. let declIdx = -1;
  2785. for (let i = 0; i < parent.namedChildCount; i++) {
  2786. const sibling = parent.namedChild(i);
  2787. if (sibling && sibling.startIndex === declStart) {
  2788. declIdx = i;
  2789. break;
  2790. }
  2791. }
  2792. if (declIdx > 0) {
  2793. for (let j = declIdx - 1; j >= 0; j--) {
  2794. const sibling = parent.namedChild(j);
  2795. if (!sibling) continue;
  2796. if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') {
  2797. break; // non-decorator separator → stop consuming
  2798. }
  2799. consider(sibling);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. /**
  2805. * Visit function body and extract calls (and structural nodes).
  2806. *
  2807. * In addition to call expressions, this also detects class/struct/enum
  2808. * definitions inside function bodies. This handles two cases:
  2809. * 1. Local class/struct/enum definitions (valid in C++, Java, etc.)
  2810. * 2. C++ macro misparsing — macros like NLOHMANN_JSON_NAMESPACE_BEGIN cause
  2811. * tree-sitter to interpret the namespace block as a function_definition,
  2812. * hiding real class/struct/enum nodes inside the "function body".
  2813. */
  2814. /**
  2815. * Rocket route-registration macros — `routes![a::b::handler, c::d::other]`
  2816. * and `catchers![not_found]`. Tree-sitter leaves a macro body as a flat
  2817. * `token_tree` of raw tokens (`identifier`, `::`, `,`), so the handler paths
  2818. * are never seen as references and each handler fn looks like it has no caller
  2819. * — it's mounted by Rocket at runtime, not called by in-repo code, so its file
  2820. * shows 0 dependents. Walk the token tree, reconstruct each comma-separated
  2821. * path, and emit a `references` edge; the Rust path resolver
  2822. * (`resolveRustPathReference`) then links it to the handler fn. The handler
  2823. * names are explicit in source, so this is precise static extraction, not a
  2824. * heuristic — no false edges (resolution still validates each path).
  2825. */
  2826. private extractRustRouteMacro(node: SyntaxNode): void {
  2827. if (this.language !== 'rust') return;
  2828. const macroName = node.namedChild(0);
  2829. if (!macroName) return;
  2830. const name = getNodeText(macroName, this.source);
  2831. if (name !== 'routes' && name !== 'catchers') return;
  2832. const tokenTree = node.namedChildren.find((c: SyntaxNode) => c.type === 'token_tree');
  2833. if (!tokenTree) return;
  2834. const fromId = this.nodeStack[this.nodeStack.length - 1];
  2835. if (!fromId) return;
  2836. // The token tree is a flat stream: `[ id :: id :: id , id … ]`. Group runs
  2837. // of `identifier` tokens (the `::` joiners are anonymous) into one path; a
  2838. // `,` (or the closing `]`) ends a path.
  2839. let parts: string[] = [];
  2840. let line = 0;
  2841. let column = 0;
  2842. const flush = (): void => {
  2843. if (parts.length > 0) {
  2844. this.unresolvedReferences.push({
  2845. fromNodeId: fromId,
  2846. referenceName: parts.join('::'),
  2847. referenceKind: 'references',
  2848. line,
  2849. column,
  2850. });
  2851. parts = [];
  2852. }
  2853. };
  2854. for (let i = 0; i < tokenTree.childCount; i++) {
  2855. const t = tokenTree.child(i);
  2856. if (!t) continue;
  2857. if (t.type === 'identifier') {
  2858. if (parts.length === 0) {
  2859. line = t.startPosition.row + 1;
  2860. column = t.startPosition.column;
  2861. }
  2862. parts.push(getNodeText(t, this.source));
  2863. } else if (t.type === ',') {
  2864. flush();
  2865. }
  2866. }
  2867. flush();
  2868. }
  2869. private visitFunctionBody(body: SyntaxNode, _functionId: string): void {
  2870. if (!this.extractor) return;
  2871. const visitForCallsAndStructure = (node: SyntaxNode): void => {
  2872. const nodeType = node.type;
  2873. // Rocket route-registration macros (`routes![…]` / `catchers![…]`): the
  2874. // handler paths live in a raw token tree the call walker can't see.
  2875. if (nodeType === 'macro_invocation') this.extractRustRouteMacro(node);
  2876. if (this.extractor!.callTypes.includes(nodeType)) {
  2877. this.extractCall(node);
  2878. } else if (INSTANTIATION_KINDS.has(nodeType)) {
  2879. // `new Foo()` inside a function body — emit an `instantiates`
  2880. // reference. Without this branch the body walker only knew
  2881. // about `call_expression`, so constructor invocations
  2882. // produced no graph edges at all.
  2883. this.extractInstantiation(node);
  2884. // Anonymous class with body: `new T() { ... }` (Java/C#). Extract as
  2885. // a class so interface-impl synthesis (Phase 5.5) can bridge T's
  2886. // methods to the overrides — same rationale as in visitNode.
  2887. const anonBody = this.findAnonymousClassBody(node);
  2888. if (anonBody) {
  2889. this.extractAnonymousClass(node, anonBody);
  2890. return;
  2891. }
  2892. } else if (this.extractor!.extractBareCall) {
  2893. const calleeName = this.extractor!.extractBareCall(node, this.source);
  2894. if (calleeName && this.nodeStack.length > 0) {
  2895. const callerId = this.nodeStack[this.nodeStack.length - 1];
  2896. if (callerId) {
  2897. this.unresolvedReferences.push({
  2898. fromNodeId: callerId,
  2899. referenceName: calleeName,
  2900. referenceKind: 'calls',
  2901. line: node.startPosition.row + 1,
  2902. column: node.startPosition.column,
  2903. });
  2904. }
  2905. }
  2906. }
  2907. // Static-member / value-read: `Enum.value`, `Type.CONST`, `Foo::BAR`.
  2908. this.extractStaticMemberRef(node);
  2909. // Local variable type annotations inside a body — `const items: Foo[] = []`,
  2910. // `const x: SomeType = svc.load()`. We deliberately do NOT create nodes for
  2911. // locals (that would explode the graph — the data-flow frontier we leave
  2912. // uncovered), but the TYPE a local is annotated with is a real dependency of
  2913. // the enclosing function, so attribute a `references` edge to it. Without
  2914. // this, a function that uses a type ONLY in its body (very common — e.g. a
  2915. // resolver building `const nodes: Node[] = []`) produced no edge to that
  2916. // type, so impact / `affected` missed the dependency entirely. We fall
  2917. // through to the default recursion below so the initializer's calls (and any
  2918. // nested declarators) are still walked.
  2919. if (
  2920. nodeType === 'variable_declarator' &&
  2921. this.TYPE_ANNOTATION_LANGUAGES.has(this.language)
  2922. ) {
  2923. const ownerId = this.nodeStack[this.nodeStack.length - 1];
  2924. if (ownerId) this.extractVariableTypeAnnotation(node, ownerId);
  2925. }
  2926. // Nested NAMED functions inside a body — function declarations and named
  2927. // function expressions like `.on('mount', function onmount(){})` — become
  2928. // their own nodes so the graph can link to them (callback handlers, local
  2929. // helpers). Anonymous arrows/expressions fall through to the default
  2930. // recursion below, keeping their inner calls attributed to the enclosing
  2931. // function: this bounds the new nodes to NAMED functions only (no explosion,
  2932. // no lost edges). extractFunction walks the nested body itself, so we return.
  2933. if (this.extractor!.functionTypes.includes(nodeType)) {
  2934. const nestedName = extractName(node, this.source, this.extractor!);
  2935. if (nestedName && nestedName !== '<anonymous>') {
  2936. this.extractFunction(node);
  2937. return;
  2938. }
  2939. }
  2940. // Extract structural nodes found inside function bodies.
  2941. // Each extract method visits its own children, so we return after extracting.
  2942. if (this.extractor!.classTypes.includes(nodeType)) {
  2943. const classification = this.extractor!.classifyClassNode?.(node) ?? 'class';
  2944. if (classification === 'struct') this.extractStruct(node);
  2945. else if (classification === 'enum') this.extractEnum(node);
  2946. else if (classification === 'interface') this.extractInterface(node);
  2947. else if (classification === 'trait') this.extractClass(node, 'trait');
  2948. else this.extractClass(node);
  2949. return;
  2950. }
  2951. if (this.extractor!.structTypes.includes(nodeType)) {
  2952. this.extractStruct(node);
  2953. return;
  2954. }
  2955. if (this.extractor!.enumTypes.includes(nodeType)) {
  2956. this.extractEnum(node);
  2957. return;
  2958. }
  2959. if (this.extractor!.interfaceTypes.includes(nodeType)) {
  2960. this.extractInterface(node);
  2961. return;
  2962. }
  2963. for (let i = 0; i < node.namedChildCount; i++) {
  2964. const child = node.namedChild(i);
  2965. if (child) {
  2966. visitForCallsAndStructure(child);
  2967. }
  2968. }
  2969. };
  2970. visitForCallsAndStructure(body);
  2971. }
  2972. /**
  2973. * Extract inheritance relationships
  2974. */
  2975. private extractInheritance(node: SyntaxNode, classId: string): void {
  2976. // Objective-C @interface MyClass : NSObject <ProtoA, ProtoB>
  2977. if (node.type === 'class_interface') {
  2978. const superclass = getChildByField(node, 'superclass');
  2979. if (superclass) {
  2980. const name = getNodeText(superclass, this.source);
  2981. this.unresolvedReferences.push({
  2982. fromNodeId: classId,
  2983. referenceName: name,
  2984. referenceKind: 'extends',
  2985. line: superclass.startPosition.row + 1,
  2986. column: superclass.startPosition.column,
  2987. });
  2988. }
  2989. for (let j = 0; j < node.namedChildCount; j++) {
  2990. const argList = node.namedChild(j);
  2991. if (argList?.type !== 'parameterized_arguments') continue;
  2992. for (let k = 0; k < argList.namedChildCount; k++) {
  2993. const typeName = argList.namedChild(k);
  2994. if (!typeName) continue;
  2995. const typeId = typeName.namedChildren.find(
  2996. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'identifier'
  2997. );
  2998. if (!typeId) continue;
  2999. const protocolName = getNodeText(typeId, this.source);
  3000. this.unresolvedReferences.push({
  3001. fromNodeId: classId,
  3002. referenceName: protocolName,
  3003. referenceKind: 'implements',
  3004. line: typeId.startPosition.row + 1,
  3005. column: typeId.startPosition.column,
  3006. });
  3007. }
  3008. }
  3009. return;
  3010. }
  3011. // Look for extends/implements clauses
  3012. for (let i = 0; i < node.namedChildCount; i++) {
  3013. const child = node.namedChild(i);
  3014. if (!child) continue;
  3015. if (
  3016. child.type === 'extends_clause' ||
  3017. child.type === 'superclass' ||
  3018. child.type === 'base_clause' || // PHP class extends
  3019. child.type === 'extends_interfaces' // Java interface extends
  3020. ) {
  3021. // Scala: `extends A[X] with B with C` packs EVERY supertype into the
  3022. // one extends_clause (separated by `with`), each a `generic_type` /
  3023. // `type_identifier` / `stable_type_identifier`. The generic path below
  3024. // takes only namedChild(0) and keeps the full text (`A[X]`), so a
  3025. // parameterized supertype — every typeclass in cats/algebra — never
  3026. // matched and `with`-mixed traits past the first were dropped. Iterate
  3027. // all supertypes and unwrap each to its base type name.
  3028. if (this.language === 'scala') {
  3029. for (const target of child.namedChildren) {
  3030. const name = scalaBaseTypeName(target, this.source);
  3031. if (name) {
  3032. this.unresolvedReferences.push({
  3033. fromNodeId: classId,
  3034. referenceName: name,
  3035. referenceKind: 'extends',
  3036. line: target.startPosition.row + 1,
  3037. column: target.startPosition.column,
  3038. });
  3039. }
  3040. }
  3041. continue;
  3042. }
  3043. // Dart: `class C extends Base with M1, M2` — the `superclass` node holds
  3044. // the extends type as a direct `type_identifier` AND a `mixins` child
  3045. // listing the `with` mixins (and `class C with M` has ONLY mixins, no
  3046. // extends type). The generic `namedChild(0)` path would read the
  3047. // `mixins` node itself as the superclass and drop every mixin — yet
  3048. // mixins are Dart's core composition mechanism (Flutter is built on
  3049. // them). Emit `extends` for the base and `implements` for each mixin.
  3050. if (this.language === 'dart' && child.type === 'superclass') {
  3051. for (const t of child.namedChildren) {
  3052. if (t.type === 'mixins') {
  3053. for (const m of t.namedChildren) {
  3054. if (m.type === 'type_identifier') {
  3055. this.unresolvedReferences.push({
  3056. fromNodeId: classId,
  3057. referenceName: getNodeText(m, this.source),
  3058. referenceKind: 'implements',
  3059. line: m.startPosition.row + 1,
  3060. column: m.startPosition.column,
  3061. });
  3062. }
  3063. }
  3064. } else if (t.type === 'type_identifier') {
  3065. this.unresolvedReferences.push({
  3066. fromNodeId: classId,
  3067. referenceName: getNodeText(t, this.source),
  3068. referenceKind: 'extends',
  3069. line: t.startPosition.row + 1,
  3070. column: t.startPosition.column,
  3071. });
  3072. }
  3073. }
  3074. continue;
  3075. }
  3076. // Extract parent class/interface names
  3077. // Java uses type_list wrapper: superclass -> type_identifier, extends_interfaces -> type_list -> type_identifier
  3078. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  3079. const targets = typeList ? typeList.namedChildren : [child.namedChild(0)];
  3080. for (const target of targets) {
  3081. if (target) {
  3082. const name = getNodeText(target, this.source);
  3083. this.unresolvedReferences.push({
  3084. fromNodeId: classId,
  3085. referenceName: name,
  3086. referenceKind: 'extends',
  3087. line: target.startPosition.row + 1,
  3088. column: target.startPosition.column,
  3089. });
  3090. }
  3091. }
  3092. }
  3093. // C++ base classes: `class Derived : public Base, private Other` →
  3094. // base_class_clause holds access specifiers + base type(s). Emit an extends
  3095. // ref per base type (skip the public/private/protected keywords).
  3096. if (child.type === 'base_class_clause') {
  3097. for (const t of child.namedChildren) {
  3098. if (
  3099. t.type === 'type_identifier' ||
  3100. t.type === 'qualified_identifier' ||
  3101. t.type === 'template_type'
  3102. ) {
  3103. this.unresolvedReferences.push({
  3104. fromNodeId: classId,
  3105. referenceName: getNodeText(t, this.source),
  3106. referenceKind: 'extends',
  3107. line: t.startPosition.row + 1,
  3108. column: t.startPosition.column,
  3109. });
  3110. }
  3111. }
  3112. }
  3113. if (
  3114. child.type === 'implements_clause' ||
  3115. child.type === 'class_interface_clause' ||
  3116. child.type === 'super_interfaces' || // Java class implements
  3117. child.type === 'interfaces' // Dart
  3118. ) {
  3119. // Extract implemented interfaces
  3120. // Java uses type_list wrapper: super_interfaces -> type_list -> type_identifier
  3121. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  3122. const targets = typeList ? typeList.namedChildren : child.namedChildren;
  3123. for (const iface of targets) {
  3124. if (iface) {
  3125. const name = getNodeText(iface, this.source);
  3126. this.unresolvedReferences.push({
  3127. fromNodeId: classId,
  3128. referenceName: name,
  3129. referenceKind: 'implements',
  3130. line: iface.startPosition.row + 1,
  3131. column: iface.startPosition.column,
  3132. });
  3133. }
  3134. }
  3135. }
  3136. // Python superclass list: `class Flask(Scaffold, Mixin):`
  3137. // argument_list contains identifier children for each parent class
  3138. if (child.type === 'argument_list' && node.type === 'class_definition') {
  3139. for (const arg of child.namedChildren) {
  3140. if (arg.type === 'identifier' || arg.type === 'attribute') {
  3141. const name = getNodeText(arg, this.source);
  3142. this.unresolvedReferences.push({
  3143. fromNodeId: classId,
  3144. referenceName: name,
  3145. referenceKind: 'extends',
  3146. line: arg.startPosition.row + 1,
  3147. column: arg.startPosition.column,
  3148. });
  3149. }
  3150. }
  3151. }
  3152. // Go interface embedding: `type Querier interface { LabelQuerier; ... }`
  3153. // constraint_elem wraps the embedded interface type identifier
  3154. if (child.type === 'constraint_elem') {
  3155. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  3156. if (typeId) {
  3157. const name = getNodeText(typeId, this.source);
  3158. this.unresolvedReferences.push({
  3159. fromNodeId: classId,
  3160. referenceName: name,
  3161. referenceKind: 'extends',
  3162. line: typeId.startPosition.row + 1,
  3163. column: typeId.startPosition.column,
  3164. });
  3165. }
  3166. }
  3167. // Go struct embedding: field_declaration without field_identifier
  3168. // e.g. `type DB struct { *Head; Queryable }` — no field name means embedded type
  3169. if (child.type === 'field_declaration') {
  3170. const hasFieldIdentifier = child.namedChildren.some((c: SyntaxNode) => c.type === 'field_identifier');
  3171. if (!hasFieldIdentifier) {
  3172. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  3173. if (typeId) {
  3174. const name = getNodeText(typeId, this.source);
  3175. this.unresolvedReferences.push({
  3176. fromNodeId: classId,
  3177. referenceName: name,
  3178. referenceKind: 'extends',
  3179. line: typeId.startPosition.row + 1,
  3180. column: typeId.startPosition.column,
  3181. });
  3182. }
  3183. }
  3184. }
  3185. // Rust trait supertraits: `trait SubTrait: SuperTrait + Display { ... }`
  3186. // trait_bounds contains type_identifier, generic_type, or higher_ranked_trait_bound children
  3187. if (child.type === 'trait_bounds') {
  3188. for (const bound of child.namedChildren) {
  3189. let typeName: string | undefined;
  3190. let posNode: SyntaxNode | undefined;
  3191. if (bound.type === 'type_identifier') {
  3192. typeName = getNodeText(bound, this.source);
  3193. posNode = bound;
  3194. } else if (bound.type === 'generic_type') {
  3195. // e.g. `Deserialize<'de>`
  3196. const inner = bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  3197. if (inner) { typeName = getNodeText(inner, this.source); posNode = inner; }
  3198. } else if (bound.type === 'higher_ranked_trait_bound') {
  3199. // e.g. `for<'de> Deserialize<'de>`
  3200. const generic = bound.namedChildren.find((c: SyntaxNode) => c.type === 'generic_type');
  3201. const typeId = generic?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  3202. ?? bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  3203. if (typeId) { typeName = getNodeText(typeId, this.source); posNode = typeId; }
  3204. }
  3205. if (typeName && posNode) {
  3206. this.unresolvedReferences.push({
  3207. fromNodeId: classId,
  3208. referenceName: typeName,
  3209. referenceKind: 'extends',
  3210. line: posNode.startPosition.row + 1,
  3211. column: posNode.startPosition.column,
  3212. });
  3213. }
  3214. }
  3215. }
  3216. // C#: `class Movie : BaseItem, IPlugin` → base_list with identifier children
  3217. // base_list combines both base class and interfaces in a single colon-separated list.
  3218. // We emit all as 'extends' since the syntax doesn't distinguish them.
  3219. if (child.type === 'base_list') {
  3220. for (const baseType of child.namedChildren) {
  3221. if (baseType) {
  3222. // For generic base types like `ClientBase<T>`, extract just the type name
  3223. const name = baseType.type === 'generic_name'
  3224. ? getNodeText(baseType.namedChildren.find((c: SyntaxNode) => c.type === 'identifier') ?? baseType, this.source)
  3225. : getNodeText(baseType, this.source);
  3226. this.unresolvedReferences.push({
  3227. fromNodeId: classId,
  3228. referenceName: name,
  3229. referenceKind: 'extends',
  3230. line: baseType.startPosition.row + 1,
  3231. column: baseType.startPosition.column,
  3232. });
  3233. }
  3234. }
  3235. }
  3236. // Kotlin: `class Foo : Bar, Baz` → delegation_specifier > user_type > type_identifier
  3237. // Also handles `class Foo : Bar()` → delegation_specifier > constructor_invocation > user_type
  3238. if (child.type === 'delegation_specifier') {
  3239. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  3240. const constructorInvocation = child.namedChildren.find((c: SyntaxNode) => c.type === 'constructor_invocation');
  3241. const target = userType ?? constructorInvocation;
  3242. if (target) {
  3243. const typeId = target.type === 'user_type'
  3244. ? target.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier') ?? target
  3245. : target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type')?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  3246. ?? target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type') ?? target;
  3247. const name = getNodeText(typeId, this.source);
  3248. this.unresolvedReferences.push({
  3249. fromNodeId: classId,
  3250. referenceName: name,
  3251. referenceKind: 'extends',
  3252. line: typeId.startPosition.row + 1,
  3253. column: typeId.startPosition.column,
  3254. });
  3255. }
  3256. }
  3257. // Swift: inheritance_specifier > user_type > type_identifier
  3258. // Used for class inheritance, protocol conformance, and protocol inheritance
  3259. if (child.type === 'inheritance_specifier') {
  3260. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  3261. const typeId = userType?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  3262. if (typeId) {
  3263. const name = getNodeText(typeId, this.source);
  3264. this.unresolvedReferences.push({
  3265. fromNodeId: classId,
  3266. referenceName: name,
  3267. referenceKind: 'extends',
  3268. line: typeId.startPosition.row + 1,
  3269. column: typeId.startPosition.column,
  3270. });
  3271. }
  3272. }
  3273. // JavaScript class_heritage has bare identifier without extends_clause wrapper
  3274. // e.g. `class Foo extends Bar {}` → class_heritage → identifier("Bar")
  3275. if (
  3276. (child.type === 'identifier' || child.type === 'type_identifier') &&
  3277. node.type === 'class_heritage'
  3278. ) {
  3279. const name = getNodeText(child, this.source);
  3280. this.unresolvedReferences.push({
  3281. fromNodeId: classId,
  3282. referenceName: name,
  3283. referenceKind: 'extends',
  3284. line: child.startPosition.row + 1,
  3285. column: child.startPosition.column,
  3286. });
  3287. }
  3288. // Recurse into container nodes (e.g. field_declaration_list in Go structs,
  3289. // class_heritage in TypeScript which wraps extends_clause/implements_clause)
  3290. if (child.type === 'field_declaration_list' || child.type === 'class_heritage') {
  3291. this.extractInheritance(child, classId);
  3292. }
  3293. }
  3294. }
  3295. /**
  3296. * Rust `impl Trait for Type` — creates an implements edge from Type to Trait.
  3297. * For plain `impl Type { ... }` (no trait), no inheritance edge is needed.
  3298. */
  3299. private extractRustImplItem(node: SyntaxNode): void {
  3300. // Check if this is `impl Trait for Type` by looking for a `for` keyword
  3301. const hasFor = node.children.some(
  3302. (c: SyntaxNode) => c.type === 'for' && !c.isNamed
  3303. );
  3304. if (!hasFor) return;
  3305. // In `impl Trait for Type`, the type_identifiers are:
  3306. // first = Trait name, last = implementing Type name
  3307. // Also handle generic types like `impl<T> Trait for MyStruct<T>`
  3308. const typeIdents = node.namedChildren.filter(
  3309. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'generic_type' || c.type === 'scoped_type_identifier'
  3310. );
  3311. if (typeIdents.length < 2) return;
  3312. const traitNode = typeIdents[0]!;
  3313. const typeNode = typeIdents[typeIdents.length - 1]!;
  3314. // Get the trait name (handle scoped paths like std::fmt::Display)
  3315. const traitName = traitNode.type === 'scoped_type_identifier'
  3316. ? this.source.substring(traitNode.startIndex, traitNode.endIndex)
  3317. : getNodeText(traitNode, this.source);
  3318. // Get the implementing type name (extract inner type_identifier for generics)
  3319. let typeName: string;
  3320. if (typeNode.type === 'generic_type') {
  3321. const inner = typeNode.namedChildren.find(
  3322. (c: SyntaxNode) => c.type === 'type_identifier'
  3323. );
  3324. typeName = inner ? getNodeText(inner, this.source) : getNodeText(typeNode, this.source);
  3325. } else {
  3326. typeName = getNodeText(typeNode, this.source);
  3327. }
  3328. // Find the struct/type node for the implementing type
  3329. const typeNodeId = this.findNodeByName(typeName);
  3330. if (typeNodeId) {
  3331. this.unresolvedReferences.push({
  3332. fromNodeId: typeNodeId,
  3333. referenceName: traitName,
  3334. referenceKind: 'implements',
  3335. line: traitNode.startPosition.row + 1,
  3336. column: traitNode.startPosition.column,
  3337. });
  3338. }
  3339. }
  3340. /**
  3341. * Find a previously-extracted node by name (used for back-references like impl blocks)
  3342. */
  3343. private findNodeByName(name: string): string | undefined {
  3344. for (const node of this.nodes) {
  3345. if (node.name === name && (node.kind === 'struct' || node.kind === 'enum' || node.kind === 'class')) {
  3346. return node.id;
  3347. }
  3348. }
  3349. return undefined;
  3350. }
  3351. /**
  3352. * Languages that support type annotations (TypeScript, etc.)
  3353. */
  3354. private readonly TYPE_ANNOTATION_LANGUAGES = new Set([
  3355. 'typescript', 'tsx', 'dart', 'kotlin', 'swift', 'rust', 'go', 'java', 'csharp', 'scala', 'php',
  3356. ]);
  3357. /**
  3358. * PHP pseudo-types and `self`/`static`/`parent` that aren't project symbols.
  3359. * (Scalar primitives parse as `primitive_type` and are skipped structurally.)
  3360. */
  3361. private readonly PHP_PSEUDO_TYPES = new Set([
  3362. 'self', 'static', 'parent', 'mixed', 'object', 'iterable', 'callable', 'void',
  3363. 'null', 'false', 'true', 'never', 'array', 'int', 'float', 'string', 'bool',
  3364. ]);
  3365. /**
  3366. * Built-in/primitive type names that shouldn't create references
  3367. */
  3368. private readonly BUILTIN_TYPES = new Set([
  3369. 'string', 'number', 'boolean', 'void', 'null', 'undefined', 'never', 'any', 'unknown',
  3370. 'object', 'symbol', 'bigint', 'true', 'false',
  3371. // Rust
  3372. 'str', 'bool', 'i8', 'i16', 'i32', 'i64', 'i128', 'isize',
  3373. 'u8', 'u16', 'u32', 'u64', 'u128', 'usize', 'f32', 'f64', 'char',
  3374. // Java/C#
  3375. 'int', 'long', 'short', 'byte', 'float', 'double', 'char',
  3376. // Go
  3377. 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64',
  3378. 'float32', 'float64', 'complex64', 'complex128', 'rune', 'error',
  3379. // Scala (capitalized primitives + ubiquitous stdlib aliases)
  3380. 'Int', 'Long', 'Short', 'Byte', 'Float', 'Double', 'Boolean', 'Char', 'Unit',
  3381. 'String', 'Any', 'AnyRef', 'AnyVal', 'Nothing', 'Null',
  3382. ]);
  3383. /**
  3384. * Extract type references from type annotations on a function/method/field node.
  3385. * Creates 'references' edges for parameter types, return types, and field types.
  3386. */
  3387. private extractTypeAnnotations(node: SyntaxNode, nodeId: string): void {
  3388. if (!this.extractor) return;
  3389. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  3390. // C# tree-sitter doesn't produce `type_identifier` leaves — it uses
  3391. // `identifier`, `predefined_type`, `qualified_name`, `generic_name`,
  3392. // etc. — so the generic walker below emits zero references for it.
  3393. // Dispatch to a C#-aware path that only walks type-position subtrees
  3394. // (the `type` field of a parameter/method/property/field), so
  3395. // parameter NAMES never accidentally surface as type refs (#381).
  3396. if (this.language === 'csharp') {
  3397. this.extractCsharpTypeRefs(node, nodeId);
  3398. return;
  3399. }
  3400. // PHP type-hints are `named_type`/`optional_type`/`union_type` wrapping a
  3401. // `name`/`qualified_name` — never `type_identifier` — so the generic walker
  3402. // below emits nothing for them. Dispatch to a PHP-aware path that walks only
  3403. // type positions (parameter / return / property types), so type-hinted
  3404. // dependencies (the constructor-injected contracts that dominate Laravel) are
  3405. // recorded and a `variable_name` like `$events` never mis-emits as a ref.
  3406. if (this.language === 'php') {
  3407. this.extractPhpTypeRefs(node, nodeId);
  3408. return;
  3409. }
  3410. // Dart: a `method_signature` wraps the real `function_signature` (where the
  3411. // params and return type live), and the return type is a bare
  3412. // `type_identifier` child, not a `type` field — so getChildByField below
  3413. // finds neither. Walk the inner signature: param names / the method name are
  3414. // `identifier` (not `type_identifier`), so only types surface.
  3415. if (this.language === 'dart') {
  3416. let sig: SyntaxNode | undefined = node;
  3417. if (node.type === 'method_signature') {
  3418. sig = node.namedChildren.find(
  3419. (c: SyntaxNode) =>
  3420. c.type === 'function_signature' ||
  3421. c.type === 'getter_signature' ||
  3422. c.type === 'setter_signature' ||
  3423. c.type === 'constructor_signature' ||
  3424. c.type === 'factory_constructor_signature'
  3425. ) ?? node;
  3426. }
  3427. this.extractTypeRefsFromSubtree(sig, nodeId);
  3428. return;
  3429. }
  3430. // Extract parameter type annotations. Scala curries — `def f(a)(implicit
  3431. // M: TC)` has MULTIPLE `parameters` siblings, and the typeclass is almost
  3432. // always in the trailing implicit list — so walk every parameter list, not
  3433. // just getChildByField's first match.
  3434. if (this.language === 'scala') {
  3435. for (const pc of node.namedChildren) {
  3436. if (pc.type === 'parameters') this.extractTypeRefsFromSubtree(pc, nodeId);
  3437. }
  3438. } else {
  3439. const params = getChildByField(node, this.extractor.paramsField || 'parameters');
  3440. if (params) {
  3441. this.extractTypeRefsFromSubtree(params, nodeId);
  3442. }
  3443. }
  3444. // Extract return type annotation
  3445. const returnType = getChildByField(node, this.extractor.returnField || 'return_type');
  3446. if (returnType) {
  3447. this.extractTypeRefsFromSubtree(returnType, nodeId);
  3448. }
  3449. // Scala context bounds / type-parameter bounds: `def f[A: Monoid]`,
  3450. // `[F[_]: Monad]`, `[A <: Foo]` carry the bound type inside `type_parameters`.
  3451. // This is THE pervasive way a typeclass is required in Scala, yet the bound
  3452. // never appears in the value parameters. Param NAMES are `identifier` (not
  3453. // `type_identifier`), so only the bound types surface. Scala-only: in other
  3454. // languages a `type_parameters` child holds declaration names as
  3455. // `type_identifier` (TS `<T>`), which would wrongly surface as refs.
  3456. if (this.language === 'scala') {
  3457. const typeParams = node.namedChildren.find(
  3458. (c: SyntaxNode) => c.type === 'type_parameters'
  3459. );
  3460. if (typeParams) {
  3461. this.extractTypeRefsFromSubtree(typeParams, nodeId);
  3462. }
  3463. }
  3464. // Extract direct type annotation (for class fields like `model: ITextModel`)
  3465. const typeAnnotation = node.namedChildren.find(
  3466. (c: SyntaxNode) => c.type === 'type_annotation'
  3467. );
  3468. if (typeAnnotation) {
  3469. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  3470. }
  3471. }
  3472. /**
  3473. * Extract C# type references from a node that owns a type position —
  3474. * a method/constructor declaration, a property declaration, or a
  3475. * field declaration (which wraps `variable_declaration → type`).
  3476. *
  3477. * Walks ONLY into known type fields, so parameter names like
  3478. * `request` in `Build(UserDto request)` are never mis-emitted as
  3479. * type references. Once inside a type subtree, `walkCsharpTypePosition`
  3480. * recognizes C#'s actual type-leaf node kinds (`identifier`,
  3481. * `qualified_name`, `generic_name`, `array_type`, `nullable_type`,
  3482. * `tuple_type`, …) — none of which are `type_identifier`. Closes #381.
  3483. */
  3484. private extractCsharpTypeRefs(node: SyntaxNode, nodeId: string): void {
  3485. // A property's type is under the `type` field; a method/constructor's RETURN
  3486. // type is under `returns` (tree-sitter-c-sharp 0.23.x — older builds used
  3487. // `type` for both). A node carries only one of the two, so checking both
  3488. // covers return types and property types without conflating them.
  3489. const directType = getChildByField(node, 'type') ?? getChildByField(node, 'returns');
  3490. if (directType) this.walkCsharpTypePosition(directType, nodeId);
  3491. // Field declarations wrap declarators in a `variable_declaration`
  3492. // whose `type` field carries the type. The outer `field_declaration`
  3493. // has no `type` field of its own, so the call above is a no-op here
  3494. // and we descend one level.
  3495. const varDecl = node.namedChildren.find((c: SyntaxNode) => c.type === 'variable_declaration');
  3496. if (varDecl) {
  3497. const vdType = getChildByField(varDecl, 'type');
  3498. if (vdType) this.walkCsharpTypePosition(vdType, nodeId);
  3499. }
  3500. // Method / constructor parameters. The field name on
  3501. // `method_declaration` is `parameters`; it points at a
  3502. // `parameter_list` whose `parameter` children each have their own
  3503. // `type` field. Walking ONLY the type field skips parameter NAMES,
  3504. // which would otherwise mis-emit as type references.
  3505. const params = getChildByField(node, 'parameters');
  3506. if (params) {
  3507. for (let i = 0; i < params.namedChildCount; i++) {
  3508. const child = params.namedChild(i);
  3509. if (!child || child.type !== 'parameter') continue;
  3510. const paramType = getChildByField(child, 'type');
  3511. if (paramType) this.walkCsharpTypePosition(paramType, nodeId);
  3512. }
  3513. }
  3514. }
  3515. /**
  3516. * Record the dependencies declared by a C# PRIMARY CONSTRUCTOR
  3517. * (`class Svc(IRepo repo, [FromKeyedServices("k")] ICache cache) { … }`,
  3518. * C# 12+). The parameter list hangs off the class/struct/record declaration
  3519. * as an unnamed-field `parameter_list` child (not the `parameters` field a
  3520. * method uses), so it's found by node type. Each parameter's declared type
  3521. * becomes a `references` edge from the owning type — these are exactly the
  3522. * services a DI-registered type depends on, so impact/blast-radius and
  3523. * "who depends on this contract" now see them. No-op when there's no primary
  3524. * constructor. (#237)
  3525. */
  3526. private extractCsharpPrimaryCtorParamRefs(node: SyntaxNode, ownerId: string): void {
  3527. if (this.language !== 'csharp') return;
  3528. const paramList = node.namedChildren.find((c: SyntaxNode) => c.type === 'parameter_list');
  3529. if (!paramList) return;
  3530. for (let i = 0; i < paramList.namedChildCount; i++) {
  3531. const param = paramList.namedChild(i);
  3532. if (!param || param.type !== 'parameter') continue;
  3533. const paramType = getChildByField(param, 'type');
  3534. if (paramType) this.walkCsharpTypePosition(paramType, ownerId);
  3535. }
  3536. }
  3537. /**
  3538. * Walk a C# subtree that is KNOWN to be in a type position
  3539. * (return type, parameter type, property type, field type, generic
  3540. * argument). Identifiers here are type names, not parameter names.
  3541. */
  3542. private walkCsharpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  3543. // `predefined_type` is int/string/bool/etc. — never a project ref.
  3544. if (node.type === 'predefined_type') return;
  3545. // Bare type name: `Foo` in `Foo bar`, or the `Foo` inside `List<Foo>`.
  3546. if (node.type === 'identifier') {
  3547. const name = getNodeText(node, this.source);
  3548. if (name && !this.BUILTIN_TYPES.has(name)) {
  3549. this.unresolvedReferences.push({
  3550. fromNodeId,
  3551. referenceName: name,
  3552. referenceKind: 'references',
  3553. line: node.startPosition.row + 1,
  3554. column: node.startPosition.column,
  3555. });
  3556. }
  3557. return;
  3558. }
  3559. // `Namespace.Foo` → the rightmost identifier is the type. Emit the
  3560. // full qualified name as the reference; the resolver can still match
  3561. // on the trailing simple name when needed.
  3562. if (node.type === 'qualified_name') {
  3563. const text = getNodeText(node, this.source);
  3564. const last = text.split('.').pop() ?? text;
  3565. if (last && !this.BUILTIN_TYPES.has(last)) {
  3566. this.unresolvedReferences.push({
  3567. fromNodeId,
  3568. referenceName: last,
  3569. referenceKind: 'references',
  3570. line: node.startPosition.row + 1,
  3571. column: node.startPosition.column,
  3572. });
  3573. }
  3574. return;
  3575. }
  3576. // `(int Code, Foo Payload)` — tuple element has BOTH a `type` and a
  3577. // `name` field; descending into all named children would mis-emit
  3578. // the element name (`Code`, `Payload`) as a type ref. Walk only the
  3579. // type field.
  3580. if (node.type === 'tuple_element') {
  3581. const t = getChildByField(node, 'type');
  3582. if (t) this.walkCsharpTypePosition(t, fromNodeId);
  3583. return;
  3584. }
  3585. // Composite type nodes — recurse into named children. Covers
  3586. // `generic_name` (head identifier + `type_argument_list`),
  3587. // `nullable_type`, `array_type`, `pointer_type`, `tuple_type`,
  3588. // `ref_type`, and any newer wrapping shapes the grammar adds.
  3589. // Identifiers reached here are all type-positional (parameter/field
  3590. // names are gated out before we descend).
  3591. for (let i = 0; i < node.namedChildCount; i++) {
  3592. const child = node.namedChild(i);
  3593. if (child) this.walkCsharpTypePosition(child, fromNodeId);
  3594. }
  3595. }
  3596. /**
  3597. * Extract PHP type references from a method/function/property declaration.
  3598. * Walks ONLY type positions: each parameter's type child (inside
  3599. * `formal_parameters`), the return type, and a property's type — all
  3600. * `named_type` / `optional_type` / `union_type` / … direct children. Parameter
  3601. * and property NAMES are `variable_name` (`$x`), never type nodes, so they
  3602. * can't be mis-emitted.
  3603. */
  3604. private extractPhpTypeRefs(node: SyntaxNode, nodeId: string): void {
  3605. const params = node.namedChildren.find((c: SyntaxNode) => c.type === 'formal_parameters');
  3606. if (params) {
  3607. for (const p of params.namedChildren) {
  3608. // simple_parameter / property_promotion_parameter / variadic_parameter
  3609. for (const c of p.namedChildren) {
  3610. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  3611. }
  3612. }
  3613. }
  3614. // Return type (method/function) and property type are TYPE nodes that are
  3615. // DIRECT children of the declaration.
  3616. for (const c of node.namedChildren) {
  3617. if (PHP_TYPE_NODES.has(c.type)) this.walkPhpTypePosition(c, nodeId);
  3618. }
  3619. }
  3620. /** Walk a PHP subtree KNOWN to be in a type position; emit class/interface refs. */
  3621. private walkPhpTypePosition(node: SyntaxNode, fromNodeId: string): void {
  3622. if (node.type === 'primitive_type') return; // int/string/void/…
  3623. if (node.type === 'name') {
  3624. const name = getNodeText(node, this.source);
  3625. if (name && !this.PHP_PSEUDO_TYPES.has(name)) {
  3626. this.unresolvedReferences.push({
  3627. fromNodeId, referenceName: name, referenceKind: 'references',
  3628. line: node.startPosition.row + 1, column: node.startPosition.column,
  3629. });
  3630. }
  3631. return;
  3632. }
  3633. if (node.type === 'qualified_name') {
  3634. // `App\Contracts\Logger` → match on the trailing simple name (what the
  3635. // class node is stored as, and what a `use` import brings into scope).
  3636. const last = getNodeText(node, this.source).split('\\').pop() ?? '';
  3637. if (last && !this.PHP_PSEUDO_TYPES.has(last)) {
  3638. this.unresolvedReferences.push({
  3639. fromNodeId, referenceName: last, referenceKind: 'references',
  3640. line: node.startPosition.row + 1, column: node.startPosition.column,
  3641. });
  3642. }
  3643. return;
  3644. }
  3645. // optional_type / nullable_type / union_type / intersection_type / named_type → recurse
  3646. for (let i = 0; i < node.namedChildCount; i++) {
  3647. const child = node.namedChild(i);
  3648. if (child) this.walkPhpTypePosition(child, fromNodeId);
  3649. }
  3650. }
  3651. /**
  3652. * Extract type references from a variable's type annotation.
  3653. */
  3654. private extractVariableTypeAnnotation(node: SyntaxNode, nodeId: string): void {
  3655. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  3656. // Find type_annotation child (covers TS `: Type`, Rust `: Type`, etc.)
  3657. const typeAnnotation = node.namedChildren.find(
  3658. (c: SyntaxNode) => c.type === 'type_annotation'
  3659. );
  3660. if (typeAnnotation) {
  3661. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  3662. }
  3663. }
  3664. /**
  3665. * Recursively walk a subtree and extract all type_identifier references.
  3666. * Handles unions, intersections, generics, arrays, etc.
  3667. */
  3668. private extractTypeRefsFromSubtree(node: SyntaxNode, fromNodeId: string): void {
  3669. if (node.type === 'type_identifier') {
  3670. const typeName = getNodeText(node, this.source);
  3671. if (typeName && !this.BUILTIN_TYPES.has(typeName)) {
  3672. this.unresolvedReferences.push({
  3673. fromNodeId,
  3674. referenceName: typeName,
  3675. referenceKind: 'references',
  3676. line: node.startPosition.row + 1,
  3677. column: node.startPosition.column,
  3678. });
  3679. }
  3680. return; // type_identifier is a leaf
  3681. }
  3682. // Recurse into children (handles union_type, intersection_type, generic_type, etc.)
  3683. for (let i = 0; i < node.namedChildCount; i++) {
  3684. const child = node.namedChild(i);
  3685. if (child) {
  3686. this.extractTypeRefsFromSubtree(child, fromNodeId);
  3687. }
  3688. }
  3689. }
  3690. /**
  3691. * Handle Pascal-specific AST structures.
  3692. * Returns true if the node was fully handled and children should be skipped.
  3693. */
  3694. private visitPascalNode(node: SyntaxNode): boolean {
  3695. const nodeType = node.type;
  3696. // Unit/Program/Library → module node
  3697. if (nodeType === 'unit' || nodeType === 'program' || nodeType === 'library') {
  3698. const moduleNameNode = node.namedChildren.find(
  3699. (c: SyntaxNode) => c.type === 'moduleName'
  3700. );
  3701. const name = moduleNameNode ? getNodeText(moduleNameNode, this.source) : '';
  3702. // Fallback to filename without extension if module name is empty
  3703. const moduleName = name || path.basename(this.filePath).replace(/\.[^.]+$/, '');
  3704. this.createNode('module', moduleName, node);
  3705. // Continue visiting children (interface/implementation sections)
  3706. for (let i = 0; i < node.namedChildCount; i++) {
  3707. const child = node.namedChild(i);
  3708. if (child) this.visitNode(child);
  3709. }
  3710. return true;
  3711. }
  3712. // declType wraps declClass/declIntf/declEnum/type-alias
  3713. // The name lives on declType, the inner node determines the kind
  3714. if (nodeType === 'declType') {
  3715. this.extractPascalDeclType(node);
  3716. return true;
  3717. }
  3718. // declUses → import nodes for each unit name
  3719. if (nodeType === 'declUses') {
  3720. this.extractPascalUses(node);
  3721. return true;
  3722. }
  3723. // declConsts → container; visit children for individual declConst
  3724. if (nodeType === 'declConsts') {
  3725. for (let i = 0; i < node.namedChildCount; i++) {
  3726. const child = node.namedChild(i);
  3727. if (child?.type === 'declConst') {
  3728. this.extractPascalConst(child);
  3729. }
  3730. }
  3731. return true;
  3732. }
  3733. // declConst at top level (outside declConsts)
  3734. if (nodeType === 'declConst') {
  3735. this.extractPascalConst(node);
  3736. return true;
  3737. }
  3738. // declTypes → container for type declarations
  3739. if (nodeType === 'declTypes') {
  3740. for (let i = 0; i < node.namedChildCount; i++) {
  3741. const child = node.namedChild(i);
  3742. if (child) this.visitNode(child);
  3743. }
  3744. return true;
  3745. }
  3746. // declVars → container for variable declarations
  3747. if (nodeType === 'declVars') {
  3748. for (let i = 0; i < node.namedChildCount; i++) {
  3749. const child = node.namedChild(i);
  3750. if (child?.type === 'declVar') {
  3751. const nameNode = getChildByField(child, 'name');
  3752. if (nameNode) {
  3753. const name = getNodeText(nameNode, this.source);
  3754. this.createNode('variable', name, child);
  3755. }
  3756. }
  3757. }
  3758. return true;
  3759. }
  3760. // defProc in implementation section → extract calls but don't create duplicate nodes
  3761. if (nodeType === 'defProc') {
  3762. this.extractPascalDefProc(node);
  3763. return true;
  3764. }
  3765. // declProp → property node
  3766. if (nodeType === 'declProp') {
  3767. const nameNode = getChildByField(node, 'name');
  3768. if (nameNode) {
  3769. const name = getNodeText(nameNode, this.source);
  3770. const visibility = this.extractor!.getVisibility?.(node);
  3771. this.createNode('property', name, node, { visibility });
  3772. }
  3773. return true;
  3774. }
  3775. // declField → field node
  3776. if (nodeType === 'declField') {
  3777. const nameNode = getChildByField(node, 'name');
  3778. if (nameNode) {
  3779. const name = getNodeText(nameNode, this.source);
  3780. const visibility = this.extractor!.getVisibility?.(node);
  3781. this.createNode('field', name, node, { visibility });
  3782. }
  3783. return true;
  3784. }
  3785. // declSection → visit children (propagates visibility via getVisibility)
  3786. if (nodeType === 'declSection') {
  3787. for (let i = 0; i < node.namedChildCount; i++) {
  3788. const child = node.namedChild(i);
  3789. if (child) this.visitNode(child);
  3790. }
  3791. return true;
  3792. }
  3793. // exprCall → extract function call reference
  3794. if (nodeType === 'exprCall') {
  3795. this.extractPascalCall(node);
  3796. return true;
  3797. }
  3798. // interface/implementation sections → visit children
  3799. if (nodeType === 'interface' || nodeType === 'implementation') {
  3800. for (let i = 0; i < node.namedChildCount; i++) {
  3801. const child = node.namedChild(i);
  3802. if (child) this.visitNode(child);
  3803. }
  3804. return true;
  3805. }
  3806. // block (begin..end) → visit for calls
  3807. if (nodeType === 'block') {
  3808. this.visitPascalBlock(node);
  3809. return true;
  3810. }
  3811. return false;
  3812. }
  3813. /**
  3814. * Extract a Pascal declType node (class, interface, enum, or type alias)
  3815. */
  3816. private extractPascalDeclType(node: SyntaxNode): void {
  3817. const nameNode = getChildByField(node, 'name');
  3818. if (!nameNode) return;
  3819. const name = getNodeText(nameNode, this.source);
  3820. // Find the inner type declaration
  3821. const declClass = node.namedChildren.find(
  3822. (c: SyntaxNode) => c.type === 'declClass'
  3823. );
  3824. const declIntf = node.namedChildren.find(
  3825. (c: SyntaxNode) => c.type === 'declIntf'
  3826. );
  3827. const typeChild = node.namedChildren.find(
  3828. (c: SyntaxNode) => c.type === 'type'
  3829. );
  3830. if (declClass) {
  3831. const classNode = this.createNode('class', name, node);
  3832. if (classNode) {
  3833. // Extract inheritance from typeref children of declClass
  3834. this.extractPascalInheritance(declClass, classNode.id);
  3835. // Visit class body
  3836. this.nodeStack.push(classNode.id);
  3837. for (let i = 0; i < declClass.namedChildCount; i++) {
  3838. const child = declClass.namedChild(i);
  3839. if (child) this.visitNode(child);
  3840. }
  3841. this.nodeStack.pop();
  3842. }
  3843. } else if (declIntf) {
  3844. const ifaceNode = this.createNode('interface', name, node);
  3845. if (ifaceNode) {
  3846. // Visit interface members
  3847. this.nodeStack.push(ifaceNode.id);
  3848. for (let i = 0; i < declIntf.namedChildCount; i++) {
  3849. const child = declIntf.namedChild(i);
  3850. if (child) this.visitNode(child);
  3851. }
  3852. this.nodeStack.pop();
  3853. }
  3854. } else if (typeChild) {
  3855. // Check if it contains a declEnum
  3856. const declEnum = typeChild.namedChildren.find(
  3857. (c: SyntaxNode) => c.type === 'declEnum'
  3858. );
  3859. if (declEnum) {
  3860. const enumNode = this.createNode('enum', name, node);
  3861. if (enumNode) {
  3862. // Extract enum members
  3863. this.nodeStack.push(enumNode.id);
  3864. for (let i = 0; i < declEnum.namedChildCount; i++) {
  3865. const child = declEnum.namedChild(i);
  3866. if (child?.type === 'declEnumValue') {
  3867. const memberName = getChildByField(child, 'name');
  3868. if (memberName) {
  3869. this.createNode('enum_member', getNodeText(memberName, this.source), child);
  3870. }
  3871. }
  3872. }
  3873. this.nodeStack.pop();
  3874. }
  3875. } else {
  3876. // Simple type alias: type TFoo = string / type TFoo = Integer
  3877. this.createNode('type_alias', name, node);
  3878. }
  3879. } else {
  3880. // Fallback: could be a forward declaration or simple alias
  3881. this.createNode('type_alias', name, node);
  3882. }
  3883. }
  3884. /**
  3885. * Extract Pascal uses clause into individual import nodes
  3886. */
  3887. private extractPascalUses(node: SyntaxNode): void {
  3888. const importText = getNodeText(node, this.source).trim();
  3889. for (let i = 0; i < node.namedChildCount; i++) {
  3890. const child = node.namedChild(i);
  3891. if (child?.type === 'moduleName') {
  3892. const unitName = getNodeText(child, this.source);
  3893. this.createNode('import', unitName, child, {
  3894. signature: importText,
  3895. });
  3896. // Create unresolved reference for resolution
  3897. if (this.nodeStack.length > 0) {
  3898. const parentId = this.nodeStack[this.nodeStack.length - 1];
  3899. if (parentId) {
  3900. this.unresolvedReferences.push({
  3901. fromNodeId: parentId,
  3902. referenceName: unitName,
  3903. referenceKind: 'imports',
  3904. line: child.startPosition.row + 1,
  3905. column: child.startPosition.column,
  3906. });
  3907. }
  3908. }
  3909. }
  3910. }
  3911. }
  3912. /**
  3913. * Extract a Pascal constant declaration
  3914. */
  3915. private extractPascalConst(node: SyntaxNode): void {
  3916. const nameNode = getChildByField(node, 'name');
  3917. if (!nameNode) return;
  3918. const name = getNodeText(nameNode, this.source);
  3919. const defaultValue = node.namedChildren.find(
  3920. (c: SyntaxNode) => c.type === 'defaultValue'
  3921. );
  3922. const sig = defaultValue ? getNodeText(defaultValue, this.source) : undefined;
  3923. this.createNode('constant', name, node, { signature: sig });
  3924. }
  3925. /**
  3926. * Extract Pascal inheritance (extends/implements) from declClass typeref children
  3927. */
  3928. private extractPascalInheritance(declClass: SyntaxNode, classId: string): void {
  3929. const typerefs = declClass.namedChildren.filter(
  3930. (c: SyntaxNode) => c.type === 'typeref'
  3931. );
  3932. for (let i = 0; i < typerefs.length; i++) {
  3933. const ref = typerefs[i]!;
  3934. const name = getNodeText(ref, this.source);
  3935. this.unresolvedReferences.push({
  3936. fromNodeId: classId,
  3937. referenceName: name,
  3938. referenceKind: i === 0 ? 'extends' : 'implements',
  3939. line: ref.startPosition.row + 1,
  3940. column: ref.startPosition.column,
  3941. });
  3942. }
  3943. }
  3944. /**
  3945. * Extract calls and resolve method context from a Pascal defProc (implementation body).
  3946. * Does not create a new node — the declaration was already captured from the interface section.
  3947. */
  3948. private extractPascalDefProc(node: SyntaxNode): void {
  3949. // Find the matching declaration node by name to use as call parent
  3950. const declProc = node.namedChildren.find(
  3951. (c: SyntaxNode) => c.type === 'declProc'
  3952. );
  3953. if (!declProc) return;
  3954. const nameNode = getChildByField(declProc, 'name');
  3955. if (!nameNode) return;
  3956. const fullName = getNodeText(nameNode, this.source).trim();
  3957. // fullName is like "TAuthService.Create"
  3958. const shortName = fullName.includes('.') ? fullName.split('.').pop()! : fullName;
  3959. const fullNameKey = fullName.toLowerCase();
  3960. const shortNameKey = shortName.toLowerCase();
  3961. // Build method index on first use (O(n) once, then O(1) per lookup)
  3962. if (!this.methodIndex) {
  3963. this.methodIndex = new Map();
  3964. for (const n of this.nodes) {
  3965. if (n.kind === 'method' || n.kind === 'function') {
  3966. const nameKey = n.name.toLowerCase();
  3967. // Keep first seen short-name mapping to avoid silently overwriting earlier entries.
  3968. if (!this.methodIndex.has(nameKey)) {
  3969. this.methodIndex.set(nameKey, n.id);
  3970. }
  3971. // For Pascal methods, also index qualified forms (e.g. TAuthService.Create).
  3972. if (n.kind === 'method') {
  3973. const qualifiedParts = n.qualifiedName.split('::');
  3974. if (qualifiedParts.length >= 2) {
  3975. // Create suffix keys so both "Module.Class.Method" and "Class.Method" can resolve.
  3976. for (let i = 0; i < qualifiedParts.length - 1; i++) {
  3977. const scopedName = qualifiedParts.slice(i).join('.').toLowerCase();
  3978. this.methodIndex.set(scopedName, n.id);
  3979. }
  3980. }
  3981. }
  3982. }
  3983. }
  3984. }
  3985. const parentId =
  3986. this.methodIndex.get(fullNameKey) ||
  3987. this.methodIndex.get(shortNameKey) ||
  3988. this.nodeStack[this.nodeStack.length - 1];
  3989. if (!parentId) return;
  3990. // Visit the block for calls
  3991. const block = node.namedChildren.find(
  3992. (c: SyntaxNode) => c.type === 'block'
  3993. );
  3994. if (block) {
  3995. this.nodeStack.push(parentId);
  3996. this.visitPascalBlock(block);
  3997. this.nodeStack.pop();
  3998. }
  3999. }
  4000. /**
  4001. * Extract function calls from a Pascal expression
  4002. */
  4003. private extractPascalCall(node: SyntaxNode): void {
  4004. if (this.nodeStack.length === 0) return;
  4005. const callerId = this.nodeStack[this.nodeStack.length - 1];
  4006. if (!callerId) return;
  4007. // Get the callee name — first child is typically the identifier or exprDot
  4008. const firstChild = node.namedChild(0);
  4009. if (!firstChild) return;
  4010. let calleeName = '';
  4011. if (firstChild.type === 'exprDot') {
  4012. // Chained static-factory call: `TFoo.GetInstance().DoIt()` — the exprDot's
  4013. // receiver is itself an `exprCall`, so the bare identifier list would
  4014. // collapse to just `DoIt` and mis-resolve to a same-named method on an
  4015. // unrelated class. Encode `TFoo.GetInstance().DoIt` so resolution infers
  4016. // DoIt's class from what `TFoo.GetInstance` RETURNS (#645/#608). Only a
  4017. // capitalized class-factory chain; a unary outer method.
  4018. const innerCall = firstChild.namedChildren.find((c: SyntaxNode) => c.type === 'exprCall');
  4019. const outerId = firstChild.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  4020. const method = outerId ? getNodeText(outerId, this.source) : '';
  4021. if (innerCall && method && /^\w+$/.test(method)) {
  4022. const innerFirst = innerCall.namedChild(0);
  4023. let innerCallee = '';
  4024. if (innerFirst?.type === 'exprDot') {
  4025. innerCallee = innerFirst.namedChildren
  4026. .filter((c: SyntaxNode) => c.type === 'identifier')
  4027. .map((id: SyntaxNode) => getNodeText(id, this.source))
  4028. .join('.');
  4029. } else if (innerFirst?.type === 'identifier') {
  4030. innerCallee = getNodeText(innerFirst, this.source);
  4031. }
  4032. // Gate on the Delphi type-naming convention — `TFoo` classes / `IFoo`
  4033. // interfaces — so a class-factory chain re-encodes but a capitalized
  4034. // VARIABLE/parameter chain (Pascal capitalizes locals too: `Curve.X().Y()`,
  4035. // `Self.X().Y()`) stays bare and keeps its existing bare-name resolution.
  4036. calleeName = innerCallee && /^[TI][A-Z]/.test(innerCallee)
  4037. ? `${innerCallee}().${method}`
  4038. : method;
  4039. } else {
  4040. // Qualified call: Obj.Method(...)
  4041. const identifiers = firstChild.namedChildren.filter(
  4042. (c: SyntaxNode) => c.type === 'identifier'
  4043. );
  4044. if (identifiers.length > 0) {
  4045. calleeName = identifiers.map((id: SyntaxNode) => getNodeText(id, this.source)).join('.');
  4046. }
  4047. }
  4048. } else if (firstChild.type === 'identifier') {
  4049. calleeName = getNodeText(firstChild, this.source);
  4050. }
  4051. if (calleeName) {
  4052. this.unresolvedReferences.push({
  4053. fromNodeId: callerId,
  4054. referenceName: calleeName,
  4055. referenceKind: 'calls',
  4056. line: node.startPosition.row + 1,
  4057. column: node.startPosition.column,
  4058. });
  4059. }
  4060. // Also visit arguments for nested calls
  4061. const args = node.namedChildren.find(
  4062. (c: SyntaxNode) => c.type === 'exprArgs'
  4063. );
  4064. if (args) {
  4065. this.visitPascalBlock(args);
  4066. }
  4067. }
  4068. /**
  4069. * Extract a PAREN-LESS Pascal method/procedure call (`Obj.Method;`,
  4070. * `TFoo.GetInstance.DoIt;`). Pascal lets a no-arg method drop its parens, so it
  4071. * parses as a bare `exprDot` (not an `exprCall`). A bare `exprDot` is
  4072. * syntactically identical to a field/property access, so this is only ever
  4073. * called for a STATEMENT-level exprDot (caller-gated): a bare `Obj.Field;`
  4074. * statement is a no-op, so a statement-level dot expression is a call. (An
  4075. * exprDot in assignment LHS/RHS or a condition is left alone — there it really
  4076. * can be a field/property read.)
  4077. */
  4078. private extractPascalParenlessCall(node: SyntaxNode): void {
  4079. if (this.nodeStack.length === 0) return;
  4080. const callerId = this.nodeStack[this.nodeStack.length - 1];
  4081. if (!callerId) return;
  4082. const receiver = node.namedChild(0);
  4083. const outerId = node.namedChildren.filter((c: SyntaxNode) => c.type === 'identifier').pop();
  4084. const method = outerId ? getNodeText(outerId, this.source) : '';
  4085. if (!method) return;
  4086. let calleeName = '';
  4087. // Chained: the receiver is itself a call — a paren-less `TFoo.GetInstance` (an
  4088. // inner exprDot) or a paren'd `TFoo.GetInstance()` (an exprCall). Encode the
  4089. // chain `TFoo.GetInstance().DoIt` so resolution infers DoIt's class from what
  4090. // the factory RETURNS (#645/#608), gated on the Delphi `TFoo`/`IFoo` type
  4091. // convention; a capitalized VARIABLE chain stays a bare method name.
  4092. if ((receiver?.type === 'exprDot' || receiver?.type === 'exprCall') && /^\w+$/.test(method)) {
  4093. const innerCalleeNode = receiver.type === 'exprCall' ? receiver.namedChild(0) : receiver;
  4094. const innerCallee = !innerCalleeNode
  4095. ? ''
  4096. : innerCalleeNode.type === 'identifier'
  4097. ? getNodeText(innerCalleeNode, this.source)
  4098. : innerCalleeNode.namedChildren
  4099. .filter((c: SyntaxNode) => c.type === 'identifier')
  4100. .map((id: SyntaxNode) => getNodeText(id, this.source))
  4101. .join('.');
  4102. if (innerCallee && /^[TI][A-Z]/.test(innerCallee)) {
  4103. calleeName = `${innerCallee}().${method}`;
  4104. // The T/I-prefixed inner is itself a real call — record it too.
  4105. if (receiver.type === 'exprCall') this.extractPascalCall(receiver);
  4106. else this.extractPascalParenlessCall(receiver);
  4107. } else {
  4108. calleeName = method; // non-class receiver: a bare method ref (no field-access ref)
  4109. }
  4110. } else {
  4111. // Simple: `Obj.Method` → the dotted name (resolves via the receiver / bare name).
  4112. calleeName = node.namedChildren
  4113. .filter((c: SyntaxNode) => c.type === 'identifier')
  4114. .map((id: SyntaxNode) => getNodeText(id, this.source))
  4115. .join('.');
  4116. }
  4117. if (calleeName) {
  4118. this.unresolvedReferences.push({
  4119. fromNodeId: callerId,
  4120. referenceName: calleeName,
  4121. referenceKind: 'calls',
  4122. line: node.startPosition.row + 1,
  4123. column: node.startPosition.column,
  4124. });
  4125. }
  4126. }
  4127. /**
  4128. * Recursively visit a Pascal block/statement tree for call expressions
  4129. */
  4130. private visitPascalBlock(node: SyntaxNode): void {
  4131. for (let i = 0; i < node.namedChildCount; i++) {
  4132. const child = node.namedChild(i);
  4133. if (!child) continue;
  4134. if (child.type === 'exprCall') {
  4135. this.extractPascalCall(child);
  4136. } else if (child.type === 'exprDot') {
  4137. // A STATEMENT-level bare exprDot is a paren-less call (`Obj.Free;`,
  4138. // `TFoo.GetInstance.DoIt;`). Anywhere else (assignment side, condition,
  4139. // expression) a bare exprDot is ambiguous with a field/property access,
  4140. // so there we only descend for paren'd inner calls.
  4141. if (node.type === 'statement') {
  4142. this.extractPascalParenlessCall(child);
  4143. } else {
  4144. for (let j = 0; j < child.namedChildCount; j++) {
  4145. const grandchild = child.namedChild(j);
  4146. if (grandchild?.type === 'exprCall') {
  4147. this.extractPascalCall(grandchild);
  4148. }
  4149. }
  4150. }
  4151. } else {
  4152. this.visitPascalBlock(child);
  4153. }
  4154. }
  4155. }
  4156. }
  4157. /**
  4158. * Extract nodes and edges from source code.
  4159. *
  4160. * If `frameworkNames` is provided, framework-specific extractors matching
  4161. * those names and the file's language are run after the tree-sitter pass.
  4162. * Their nodes/references/errors are merged into the returned result.
  4163. */
  4164. export function extractFromSource(
  4165. filePath: string,
  4166. source: string,
  4167. language?: Language,
  4168. frameworkNames?: string[]
  4169. ): ExtractionResult {
  4170. const detectedLanguage = language || detectLanguage(filePath, source);
  4171. const fileExtension = path.extname(filePath).toLowerCase();
  4172. let result: ExtractionResult;
  4173. // Use custom extractor for Svelte
  4174. if (detectedLanguage === 'svelte') {
  4175. const extractor = new SvelteExtractor(filePath, source);
  4176. result = extractor.extract();
  4177. } else if (detectedLanguage === 'vue') {
  4178. // Use custom extractor for Vue
  4179. const extractor = new VueExtractor(filePath, source);
  4180. result = extractor.extract();
  4181. } else if (detectedLanguage === 'liquid') {
  4182. // Use custom extractor for Liquid
  4183. const extractor = new LiquidExtractor(filePath, source);
  4184. result = extractor.extract();
  4185. } else if (detectedLanguage === 'razor') {
  4186. // Use custom extractor for ASP.NET Razor (.cshtml) / Blazor (.razor) markup
  4187. const extractor = new RazorExtractor(filePath, source);
  4188. result = extractor.extract();
  4189. } else if (detectedLanguage === 'xml') {
  4190. // Custom extractor for MyBatis mapper XML. Non-mapper XML returns just a
  4191. // file node so the watcher tracks it without emitting symbols.
  4192. const extractor = new MyBatisExtractor(filePath, source);
  4193. result = extractor.extract();
  4194. } else if (isFileLevelOnlyLanguage(detectedLanguage)) {
  4195. // No symbol extraction at this stage — files are tracked at the file-record
  4196. // level only. Framework extractors (Drupal routing yml, Spring `@Value`
  4197. // resolution against application.yml/application.properties) run later and
  4198. // add per-file nodes/references when they apply.
  4199. result = { nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: 0 };
  4200. } else if (
  4201. detectedLanguage === 'pascal' &&
  4202. (fileExtension === '.dfm' || fileExtension === '.fmx')
  4203. ) {
  4204. // Use custom extractor for DFM/FMX form files
  4205. const extractor = new DfmExtractor(filePath, source);
  4206. result = extractor.extract();
  4207. } else {
  4208. const extractor = new TreeSitterExtractor(filePath, source, detectedLanguage);
  4209. result = extractor.extract();
  4210. }
  4211. // Framework-specific extraction (routes, middleware, etc.)
  4212. if (frameworkNames && frameworkNames.length > 0) {
  4213. const allResolvers = getAllFrameworkResolvers();
  4214. const applicable = getApplicableFrameworks(
  4215. allResolvers.filter((r) => frameworkNames.includes(r.name)),
  4216. detectedLanguage
  4217. );
  4218. for (const fw of applicable) {
  4219. if (!fw.extract) continue;
  4220. try {
  4221. const fwResult = fw.extract(filePath, source);
  4222. result.nodes.push(...fwResult.nodes);
  4223. result.unresolvedReferences.push(...fwResult.references);
  4224. } catch (err) {
  4225. result.errors.push({
  4226. message: `Framework extractor '${fw.name}' failed: ${
  4227. err instanceof Error ? err.message : String(err)
  4228. }`,
  4229. filePath,
  4230. severity: 'warning',
  4231. });
  4232. }
  4233. }
  4234. }
  4235. return result;
  4236. }