tree-sitter.ts 205 KB

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