tree-sitter.ts 213 KB

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