tree-sitter.ts 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  1. /**
  2. * Tree-sitter Parser Wrapper
  3. *
  4. * Handles parsing source code and extracting structural information.
  5. */
  6. import { SyntaxNode, Tree } from 'tree-sitter';
  7. import * as crypto from 'crypto';
  8. import {
  9. Language,
  10. Node,
  11. Edge,
  12. NodeKind,
  13. ExtractionResult,
  14. ExtractionError,
  15. UnresolvedReference,
  16. } from '../types';
  17. import { getParser, detectLanguage, isLanguageSupported } from './grammars';
  18. import { captureException } from '../sentry';
  19. /**
  20. * Generate a unique node ID
  21. *
  22. * Uses a 32-character (128-bit) hash to avoid collisions when indexing
  23. * large codebases with many files containing similar symbols.
  24. */
  25. export function generateNodeId(
  26. filePath: string,
  27. kind: NodeKind,
  28. name: string,
  29. line: number
  30. ): string {
  31. const hash = crypto
  32. .createHash('sha256')
  33. .update(`${filePath}:${kind}:${name}:${line}`)
  34. .digest('hex')
  35. .substring(0, 32);
  36. return `${kind}:${hash}`;
  37. }
  38. /**
  39. * Extract text from a syntax node
  40. */
  41. function getNodeText(node: SyntaxNode, source: string): string {
  42. return source.substring(node.startIndex, node.endIndex);
  43. }
  44. /**
  45. * Find a child node by field name
  46. */
  47. function getChildByField(node: SyntaxNode, fieldName: string): SyntaxNode | null {
  48. return node.childForFieldName(fieldName);
  49. }
  50. /**
  51. * Get the docstring/comment preceding a node
  52. */
  53. function getPrecedingDocstring(node: SyntaxNode, source: string): string | undefined {
  54. let sibling = node.previousNamedSibling;
  55. const comments: string[] = [];
  56. while (sibling) {
  57. if (
  58. sibling.type === 'comment' ||
  59. sibling.type === 'line_comment' ||
  60. sibling.type === 'block_comment' ||
  61. sibling.type === 'documentation_comment'
  62. ) {
  63. comments.unshift(getNodeText(sibling, source));
  64. sibling = sibling.previousNamedSibling;
  65. } else {
  66. break;
  67. }
  68. }
  69. if (comments.length === 0) return undefined;
  70. // Clean up comment markers
  71. return comments
  72. .map((c) =>
  73. c
  74. .replace(/^\/\*\*?|\*\/$/g, '')
  75. .replace(/^\/\/\s?/gm, '')
  76. .replace(/^\s*\*\s?/gm, '')
  77. .trim()
  78. )
  79. .join('\n')
  80. .trim();
  81. }
  82. /**
  83. * Language-specific extraction configuration
  84. */
  85. interface LanguageExtractor {
  86. /** Node types that represent functions */
  87. functionTypes: string[];
  88. /** Node types that represent classes */
  89. classTypes: string[];
  90. /** Node types that represent methods */
  91. methodTypes: string[];
  92. /** Node types that represent interfaces/protocols/traits */
  93. interfaceTypes: string[];
  94. /** Node types that represent structs */
  95. structTypes: string[];
  96. /** Node types that represent enums */
  97. enumTypes: string[];
  98. /** Node types that represent type aliases (e.g. `type X = ...`) */
  99. typeAliasTypes: string[];
  100. /** Node types that represent imports */
  101. importTypes: string[];
  102. /** Node types that represent function calls */
  103. callTypes: string[];
  104. /** Node types that represent variable declarations (const, let, var, etc.) */
  105. variableTypes: string[];
  106. /** Field name for identifier/name */
  107. nameField: string;
  108. /** Field name for body */
  109. bodyField: string;
  110. /** Field name for parameters */
  111. paramsField: string;
  112. /** Field name for return type */
  113. returnField?: string;
  114. /** Extract signature from node */
  115. getSignature?: (node: SyntaxNode, source: string) => string | undefined;
  116. /** Extract visibility from node */
  117. getVisibility?: (node: SyntaxNode) => 'public' | 'private' | 'protected' | 'internal' | undefined;
  118. /** Check if node is exported */
  119. isExported?: (node: SyntaxNode, source: string) => boolean;
  120. /** Check if node is async */
  121. isAsync?: (node: SyntaxNode) => boolean;
  122. /** Check if node is static */
  123. isStatic?: (node: SyntaxNode) => boolean;
  124. /** Check if variable declaration is a constant (const vs let/var) */
  125. isConst?: (node: SyntaxNode) => boolean;
  126. }
  127. /**
  128. * Language-specific extractors
  129. */
  130. const EXTRACTORS: Partial<Record<Language, LanguageExtractor>> = {
  131. typescript: {
  132. functionTypes: ['function_declaration', 'arrow_function', 'function_expression'],
  133. classTypes: ['class_declaration'],
  134. methodTypes: ['method_definition', 'public_field_definition'],
  135. interfaceTypes: ['interface_declaration'],
  136. structTypes: [],
  137. enumTypes: ['enum_declaration'],
  138. typeAliasTypes: ['type_alias_declaration'],
  139. importTypes: ['import_statement'],
  140. callTypes: ['call_expression'],
  141. variableTypes: ['lexical_declaration', 'variable_declaration'],
  142. nameField: 'name',
  143. bodyField: 'body',
  144. paramsField: 'parameters',
  145. returnField: 'return_type',
  146. getSignature: (node, source) => {
  147. const params = getChildByField(node, 'parameters');
  148. const returnType = getChildByField(node, 'return_type');
  149. if (!params) return undefined;
  150. let sig = getNodeText(params, source);
  151. if (returnType) {
  152. sig += ': ' + getNodeText(returnType, source).replace(/^:\s*/, '');
  153. }
  154. return sig;
  155. },
  156. getVisibility: (node) => {
  157. for (let i = 0; i < node.childCount; i++) {
  158. const child = node.child(i);
  159. if (child?.type === 'accessibility_modifier') {
  160. const text = child.text;
  161. if (text === 'public') return 'public';
  162. if (text === 'private') return 'private';
  163. if (text === 'protected') return 'protected';
  164. }
  165. }
  166. return undefined;
  167. },
  168. isExported: (node, _source) => {
  169. // Walk the parent chain to find an export_statement ancestor.
  170. // This correctly handles deeply nested nodes like arrow functions
  171. // inside variable declarations: `export const X = () => { ... }`
  172. // where the arrow_function is 3 levels deep under export_statement.
  173. let current = node.parent;
  174. while (current) {
  175. if (current.type === 'export_statement') return true;
  176. current = current.parent;
  177. }
  178. return false;
  179. },
  180. isAsync: (node) => {
  181. for (let i = 0; i < node.childCount; i++) {
  182. const child = node.child(i);
  183. if (child?.type === 'async') return true;
  184. }
  185. return false;
  186. },
  187. isStatic: (node) => {
  188. for (let i = 0; i < node.childCount; i++) {
  189. const child = node.child(i);
  190. if (child?.type === 'static') return true;
  191. }
  192. return false;
  193. },
  194. isConst: (node) => {
  195. // For lexical_declaration, check if it's 'const' or 'let'
  196. // For variable_declaration, it's always 'var'
  197. if (node.type === 'lexical_declaration') {
  198. for (let i = 0; i < node.childCount; i++) {
  199. const child = node.child(i);
  200. if (child?.type === 'const') return true;
  201. }
  202. }
  203. return false;
  204. },
  205. },
  206. javascript: {
  207. functionTypes: ['function_declaration', 'arrow_function', 'function_expression'],
  208. classTypes: ['class_declaration'],
  209. methodTypes: ['method_definition', 'field_definition'],
  210. interfaceTypes: [],
  211. structTypes: [],
  212. enumTypes: [],
  213. typeAliasTypes: [],
  214. importTypes: ['import_statement'],
  215. callTypes: ['call_expression'],
  216. variableTypes: ['lexical_declaration', 'variable_declaration'],
  217. nameField: 'name',
  218. bodyField: 'body',
  219. paramsField: 'parameters',
  220. getSignature: (node, source) => {
  221. const params = getChildByField(node, 'parameters');
  222. return params ? getNodeText(params, source) : undefined;
  223. },
  224. isExported: (node, _source) => {
  225. let current = node.parent;
  226. while (current) {
  227. if (current.type === 'export_statement') return true;
  228. current = current.parent;
  229. }
  230. return false;
  231. },
  232. isAsync: (node) => {
  233. for (let i = 0; i < node.childCount; i++) {
  234. const child = node.child(i);
  235. if (child?.type === 'async') return true;
  236. }
  237. return false;
  238. },
  239. isConst: (node) => {
  240. if (node.type === 'lexical_declaration') {
  241. for (let i = 0; i < node.childCount; i++) {
  242. const child = node.child(i);
  243. if (child?.type === 'const') return true;
  244. }
  245. }
  246. return false;
  247. },
  248. },
  249. python: {
  250. functionTypes: ['function_definition'],
  251. classTypes: ['class_definition'],
  252. methodTypes: ['function_definition'], // Methods are functions inside classes
  253. interfaceTypes: [],
  254. structTypes: [],
  255. enumTypes: [],
  256. typeAliasTypes: [],
  257. importTypes: ['import_statement', 'import_from_statement'],
  258. callTypes: ['call'],
  259. variableTypes: ['assignment'], // Python uses assignment for variable declarations
  260. nameField: 'name',
  261. bodyField: 'body',
  262. paramsField: 'parameters',
  263. returnField: 'return_type',
  264. getSignature: (node, source) => {
  265. const params = getChildByField(node, 'parameters');
  266. const returnType = getChildByField(node, 'return_type');
  267. if (!params) return undefined;
  268. let sig = getNodeText(params, source);
  269. if (returnType) {
  270. sig += ' -> ' + getNodeText(returnType, source);
  271. }
  272. return sig;
  273. },
  274. isAsync: (node) => {
  275. const prev = node.previousSibling;
  276. return prev?.type === 'async';
  277. },
  278. isStatic: (node) => {
  279. // Check for @staticmethod decorator
  280. const prev = node.previousNamedSibling;
  281. if (prev?.type === 'decorator') {
  282. const text = prev.text;
  283. return text.includes('staticmethod');
  284. }
  285. return false;
  286. },
  287. },
  288. go: {
  289. functionTypes: ['function_declaration'],
  290. classTypes: [], // Go doesn't have classes
  291. methodTypes: ['method_declaration'],
  292. interfaceTypes: ['interface_type'],
  293. structTypes: ['struct_type'],
  294. enumTypes: [],
  295. typeAliasTypes: ['type_spec'], // Go type declarations
  296. importTypes: ['import_declaration'],
  297. callTypes: ['call_expression'],
  298. variableTypes: ['var_declaration', 'short_var_declaration', 'const_declaration'],
  299. nameField: 'name',
  300. bodyField: 'body',
  301. paramsField: 'parameters',
  302. returnField: 'result',
  303. getSignature: (node, source) => {
  304. const params = getChildByField(node, 'parameters');
  305. const result = getChildByField(node, 'result');
  306. if (!params) return undefined;
  307. let sig = getNodeText(params, source);
  308. if (result) {
  309. sig += ' ' + getNodeText(result, source);
  310. }
  311. return sig;
  312. },
  313. },
  314. rust: {
  315. functionTypes: ['function_item'],
  316. classTypes: [], // Rust has impl blocks
  317. methodTypes: ['function_item'], // Methods are functions in impl blocks
  318. interfaceTypes: ['trait_item'],
  319. structTypes: ['struct_item'],
  320. enumTypes: ['enum_item'],
  321. typeAliasTypes: ['type_item'], // Rust type aliases
  322. importTypes: ['use_declaration'],
  323. callTypes: ['call_expression'],
  324. variableTypes: ['let_declaration', 'const_item', 'static_item'],
  325. nameField: 'name',
  326. bodyField: 'body',
  327. paramsField: 'parameters',
  328. returnField: 'return_type',
  329. getSignature: (node, source) => {
  330. const params = getChildByField(node, 'parameters');
  331. const returnType = getChildByField(node, 'return_type');
  332. if (!params) return undefined;
  333. let sig = getNodeText(params, source);
  334. if (returnType) {
  335. sig += ' -> ' + getNodeText(returnType, source);
  336. }
  337. return sig;
  338. },
  339. isAsync: (node) => {
  340. for (let i = 0; i < node.childCount; i++) {
  341. const child = node.child(i);
  342. if (child?.type === 'async') return true;
  343. }
  344. return false;
  345. },
  346. getVisibility: (node) => {
  347. for (let i = 0; i < node.childCount; i++) {
  348. const child = node.child(i);
  349. if (child?.type === 'visibility_modifier') {
  350. return child.text.includes('pub') ? 'public' : 'private';
  351. }
  352. }
  353. return 'private'; // Rust defaults to private
  354. },
  355. },
  356. java: {
  357. functionTypes: [],
  358. classTypes: ['class_declaration'],
  359. methodTypes: ['method_declaration', 'constructor_declaration'],
  360. interfaceTypes: ['interface_declaration'],
  361. structTypes: [],
  362. enumTypes: ['enum_declaration'],
  363. typeAliasTypes: [],
  364. importTypes: ['import_declaration'],
  365. callTypes: ['method_invocation'],
  366. variableTypes: ['local_variable_declaration', 'field_declaration'],
  367. nameField: 'name',
  368. bodyField: 'body',
  369. paramsField: 'parameters',
  370. returnField: 'type',
  371. getSignature: (node, source) => {
  372. const params = getChildByField(node, 'parameters');
  373. const returnType = getChildByField(node, 'type');
  374. if (!params) return undefined;
  375. const paramsText = getNodeText(params, source);
  376. return returnType ? getNodeText(returnType, source) + ' ' + paramsText : paramsText;
  377. },
  378. getVisibility: (node) => {
  379. for (let i = 0; i < node.childCount; i++) {
  380. const child = node.child(i);
  381. if (child?.type === 'modifiers') {
  382. const text = child.text;
  383. if (text.includes('public')) return 'public';
  384. if (text.includes('private')) return 'private';
  385. if (text.includes('protected')) return 'protected';
  386. }
  387. }
  388. return undefined;
  389. },
  390. isStatic: (node) => {
  391. for (let i = 0; i < node.childCount; i++) {
  392. const child = node.child(i);
  393. if (child?.type === 'modifiers' && child.text.includes('static')) {
  394. return true;
  395. }
  396. }
  397. return false;
  398. },
  399. },
  400. c: {
  401. functionTypes: ['function_definition'],
  402. classTypes: [],
  403. methodTypes: [],
  404. interfaceTypes: [],
  405. structTypes: ['struct_specifier'],
  406. enumTypes: ['enum_specifier'],
  407. typeAliasTypes: ['type_definition'], // typedef
  408. importTypes: ['preproc_include'],
  409. callTypes: ['call_expression'],
  410. variableTypes: ['declaration'],
  411. nameField: 'declarator',
  412. bodyField: 'body',
  413. paramsField: 'parameters',
  414. },
  415. cpp: {
  416. functionTypes: ['function_definition'],
  417. classTypes: ['class_specifier'],
  418. methodTypes: ['function_definition'],
  419. interfaceTypes: [],
  420. structTypes: ['struct_specifier'],
  421. enumTypes: ['enum_specifier'],
  422. typeAliasTypes: ['type_definition', 'alias_declaration'], // typedef and using
  423. importTypes: ['preproc_include'],
  424. callTypes: ['call_expression'],
  425. variableTypes: ['declaration'],
  426. nameField: 'declarator',
  427. bodyField: 'body',
  428. paramsField: 'parameters',
  429. getVisibility: (node) => {
  430. // Check for access specifier in parent
  431. const parent = node.parent;
  432. if (parent) {
  433. for (let i = 0; i < parent.childCount; i++) {
  434. const child = parent.child(i);
  435. if (child?.type === 'access_specifier') {
  436. const text = child.text;
  437. if (text.includes('public')) return 'public';
  438. if (text.includes('private')) return 'private';
  439. if (text.includes('protected')) return 'protected';
  440. }
  441. }
  442. }
  443. return undefined;
  444. },
  445. },
  446. csharp: {
  447. functionTypes: [],
  448. classTypes: ['class_declaration'],
  449. methodTypes: ['method_declaration', 'constructor_declaration'],
  450. interfaceTypes: ['interface_declaration'],
  451. structTypes: ['struct_declaration'],
  452. enumTypes: ['enum_declaration'],
  453. typeAliasTypes: [],
  454. importTypes: ['using_directive'],
  455. callTypes: ['invocation_expression'],
  456. variableTypes: ['local_declaration_statement', 'field_declaration'],
  457. nameField: 'name',
  458. bodyField: 'body',
  459. paramsField: 'parameter_list',
  460. getVisibility: (node) => {
  461. for (let i = 0; i < node.childCount; i++) {
  462. const child = node.child(i);
  463. if (child?.type === 'modifier') {
  464. const text = child.text;
  465. if (text === 'public') return 'public';
  466. if (text === 'private') return 'private';
  467. if (text === 'protected') return 'protected';
  468. if (text === 'internal') return 'internal';
  469. }
  470. }
  471. return 'private'; // C# defaults to private
  472. },
  473. isStatic: (node) => {
  474. for (let i = 0; i < node.childCount; i++) {
  475. const child = node.child(i);
  476. if (child?.type === 'modifier' && child.text === 'static') {
  477. return true;
  478. }
  479. }
  480. return false;
  481. },
  482. isAsync: (node) => {
  483. for (let i = 0; i < node.childCount; i++) {
  484. const child = node.child(i);
  485. if (child?.type === 'modifier' && child.text === 'async') {
  486. return true;
  487. }
  488. }
  489. return false;
  490. },
  491. },
  492. php: {
  493. functionTypes: ['function_definition'],
  494. classTypes: ['class_declaration'],
  495. methodTypes: ['method_declaration'],
  496. interfaceTypes: ['interface_declaration'],
  497. structTypes: [],
  498. enumTypes: ['enum_declaration'],
  499. typeAliasTypes: [],
  500. importTypes: ['namespace_use_declaration'],
  501. callTypes: ['function_call_expression', 'member_call_expression', 'scoped_call_expression'],
  502. variableTypes: ['property_declaration', 'const_declaration'],
  503. nameField: 'name',
  504. bodyField: 'body',
  505. paramsField: 'parameters',
  506. returnField: 'return_type',
  507. getVisibility: (node) => {
  508. for (let i = 0; i < node.childCount; i++) {
  509. const child = node.child(i);
  510. if (child?.type === 'visibility_modifier') {
  511. const text = child.text;
  512. if (text === 'public') return 'public';
  513. if (text === 'private') return 'private';
  514. if (text === 'protected') return 'protected';
  515. }
  516. }
  517. return 'public'; // PHP defaults to public
  518. },
  519. isStatic: (node) => {
  520. for (let i = 0; i < node.childCount; i++) {
  521. const child = node.child(i);
  522. if (child?.type === 'static_modifier') return true;
  523. }
  524. return false;
  525. },
  526. },
  527. ruby: {
  528. functionTypes: ['method'],
  529. classTypes: ['class'],
  530. methodTypes: ['method', 'singleton_method'],
  531. interfaceTypes: [], // Ruby uses modules
  532. structTypes: [],
  533. enumTypes: [],
  534. typeAliasTypes: [],
  535. importTypes: ['call'], // require/require_relative
  536. callTypes: ['call', 'method_call'],
  537. variableTypes: ['assignment'], // Ruby uses assignment like Python
  538. nameField: 'name',
  539. bodyField: 'body',
  540. paramsField: 'parameters',
  541. getVisibility: (node) => {
  542. // Ruby visibility is based on preceding visibility modifiers
  543. let sibling = node.previousNamedSibling;
  544. while (sibling) {
  545. if (sibling.type === 'call') {
  546. const methodName = getChildByField(sibling, 'method');
  547. if (methodName) {
  548. const text = methodName.text;
  549. if (text === 'private') return 'private';
  550. if (text === 'protected') return 'protected';
  551. if (text === 'public') return 'public';
  552. }
  553. }
  554. sibling = sibling.previousNamedSibling;
  555. }
  556. return 'public';
  557. },
  558. },
  559. swift: {
  560. functionTypes: ['function_declaration'],
  561. classTypes: ['class_declaration'],
  562. methodTypes: ['function_declaration'], // Methods are functions inside classes
  563. interfaceTypes: ['protocol_declaration'],
  564. structTypes: ['struct_declaration'],
  565. enumTypes: ['enum_declaration'],
  566. typeAliasTypes: ['typealias_declaration'],
  567. importTypes: ['import_declaration'],
  568. callTypes: ['call_expression'],
  569. variableTypes: ['property_declaration', 'constant_declaration'],
  570. nameField: 'name',
  571. bodyField: 'body',
  572. paramsField: 'parameter',
  573. returnField: 'return_type',
  574. getSignature: (node, source) => {
  575. // Swift function signature: func name(params) -> ReturnType
  576. const params = getChildByField(node, 'parameter');
  577. const returnType = getChildByField(node, 'return_type');
  578. if (!params) return undefined;
  579. let sig = getNodeText(params, source);
  580. if (returnType) {
  581. sig += ' -> ' + getNodeText(returnType, source);
  582. }
  583. return sig;
  584. },
  585. getVisibility: (node) => {
  586. // Check for visibility modifiers in Swift
  587. for (let i = 0; i < node.childCount; i++) {
  588. const child = node.child(i);
  589. if (child?.type === 'modifiers') {
  590. const text = child.text;
  591. if (text.includes('public')) return 'public';
  592. if (text.includes('private')) return 'private';
  593. if (text.includes('internal')) return 'internal';
  594. if (text.includes('fileprivate')) return 'private';
  595. }
  596. }
  597. return 'internal'; // Swift defaults to internal
  598. },
  599. isStatic: (node) => {
  600. for (let i = 0; i < node.childCount; i++) {
  601. const child = node.child(i);
  602. if (child?.type === 'modifiers') {
  603. if (child.text.includes('static') || child.text.includes('class')) {
  604. return true;
  605. }
  606. }
  607. }
  608. return false;
  609. },
  610. isAsync: (node) => {
  611. for (let i = 0; i < node.childCount; i++) {
  612. const child = node.child(i);
  613. if (child?.type === 'modifiers' && child.text.includes('async')) {
  614. return true;
  615. }
  616. }
  617. return false;
  618. },
  619. },
  620. kotlin: {
  621. functionTypes: ['function_declaration'],
  622. classTypes: ['class_declaration'],
  623. methodTypes: ['function_declaration'], // Methods are functions inside classes
  624. interfaceTypes: ['class_declaration'], // Interfaces use class_declaration with 'interface' modifier
  625. structTypes: [], // Kotlin uses data classes
  626. enumTypes: ['class_declaration'], // Enums use class_declaration with 'enum' modifier
  627. typeAliasTypes: ['type_alias'],
  628. importTypes: ['import_header'],
  629. callTypes: ['call_expression'],
  630. variableTypes: ['property_declaration'],
  631. nameField: 'simple_identifier',
  632. bodyField: 'function_body',
  633. paramsField: 'function_value_parameters',
  634. returnField: 'type',
  635. getSignature: (node, source) => {
  636. // Kotlin function signature: fun name(params): ReturnType
  637. const params = getChildByField(node, 'function_value_parameters');
  638. const returnType = getChildByField(node, 'type');
  639. if (!params) return undefined;
  640. let sig = getNodeText(params, source);
  641. if (returnType) {
  642. sig += ': ' + getNodeText(returnType, source);
  643. }
  644. return sig;
  645. },
  646. getVisibility: (node) => {
  647. // Check for visibility modifiers in Kotlin
  648. for (let i = 0; i < node.childCount; i++) {
  649. const child = node.child(i);
  650. if (child?.type === 'modifiers') {
  651. const text = child.text;
  652. if (text.includes('public')) return 'public';
  653. if (text.includes('private')) return 'private';
  654. if (text.includes('protected')) return 'protected';
  655. if (text.includes('internal')) return 'internal';
  656. }
  657. }
  658. return 'public'; // Kotlin defaults to public
  659. },
  660. isStatic: (_node) => {
  661. // Kotlin doesn't have static, uses companion objects
  662. // Check if inside companion object would require more context
  663. return false;
  664. },
  665. isAsync: (node) => {
  666. // Kotlin uses suspend keyword for coroutines
  667. for (let i = 0; i < node.childCount; i++) {
  668. const child = node.child(i);
  669. if (child?.type === 'modifiers' && child.text.includes('suspend')) {
  670. return true;
  671. }
  672. }
  673. return false;
  674. },
  675. },
  676. dart: {
  677. functionTypes: ['function_signature'],
  678. classTypes: ['class_definition'],
  679. methodTypes: ['method_signature'],
  680. interfaceTypes: [],
  681. structTypes: [],
  682. enumTypes: ['enum_declaration'],
  683. typeAliasTypes: ['type_alias'],
  684. importTypes: ['import_or_export'],
  685. callTypes: [], // Dart calls use identifier+selector, handled via function body traversal
  686. variableTypes: [],
  687. nameField: 'name',
  688. bodyField: 'body', // class_definition uses 'body' field
  689. paramsField: 'formal_parameter_list',
  690. returnField: 'type',
  691. getSignature: (node, source) => {
  692. // For function_signature: extract params + return type
  693. // For method_signature: delegate to inner function_signature
  694. let sig = node;
  695. if (node.type === 'method_signature') {
  696. const inner = node.namedChildren.find((c: SyntaxNode) =>
  697. c.type === 'function_signature' || c.type === 'getter_signature' || c.type === 'setter_signature'
  698. );
  699. if (inner) sig = inner;
  700. }
  701. const params = sig.namedChildren.find((c: SyntaxNode) => c.type === 'formal_parameter_list');
  702. const retType = sig.namedChildren.find((c: SyntaxNode) =>
  703. c.type === 'type_identifier' || c.type === 'void_type'
  704. );
  705. if (!params && !retType) return undefined;
  706. let result = '';
  707. if (retType) result += getNodeText(retType, source) + ' ';
  708. if (params) result += getNodeText(params, source);
  709. return result.trim() || undefined;
  710. },
  711. getVisibility: (node) => {
  712. // Dart convention: _ prefix means private, otherwise public
  713. let nameNode: SyntaxNode | null = null;
  714. if (node.type === 'method_signature') {
  715. const inner = node.namedChildren.find((c: SyntaxNode) =>
  716. c.type === 'function_signature' || c.type === 'getter_signature' || c.type === 'setter_signature'
  717. );
  718. if (inner) nameNode = inner.namedChildren.find((c: SyntaxNode) => c.type === 'identifier') || null;
  719. } else {
  720. nameNode = node.childForFieldName('name');
  721. }
  722. if (nameNode && nameNode.text.startsWith('_')) return 'private';
  723. return 'public';
  724. },
  725. isAsync: (node) => {
  726. // In Dart, 'async' is on the function_body (next sibling), not the signature
  727. const nextSibling = node.nextNamedSibling;
  728. if (nextSibling?.type === 'function_body') {
  729. for (let i = 0; i < nextSibling.childCount; i++) {
  730. const child = nextSibling.child(i);
  731. if (child?.type === 'async') return true;
  732. }
  733. }
  734. return false;
  735. },
  736. isStatic: (node) => {
  737. // For method_signature, check for 'static' child
  738. if (node.type === 'method_signature') {
  739. for (let i = 0; i < node.childCount; i++) {
  740. const child = node.child(i);
  741. if (child?.type === 'static') return true;
  742. }
  743. }
  744. return false;
  745. },
  746. },
  747. };
  748. // TSX and JSX use the same extractors as their base languages
  749. EXTRACTORS.tsx = EXTRACTORS.typescript;
  750. EXTRACTORS.jsx = EXTRACTORS.javascript;
  751. /**
  752. * Extract the name from a node based on language
  753. */
  754. function extractName(node: SyntaxNode, source: string, extractor: LanguageExtractor): string {
  755. // Try field name first
  756. const nameNode = getChildByField(node, extractor.nameField);
  757. if (nameNode) {
  758. // Handle complex declarators (C/C++)
  759. if (nameNode.type === 'function_declarator' || nameNode.type === 'declarator') {
  760. const innerName = getChildByField(nameNode, 'declarator') || nameNode.namedChild(0);
  761. return innerName ? getNodeText(innerName, source) : getNodeText(nameNode, source);
  762. }
  763. return getNodeText(nameNode, source);
  764. }
  765. // For Dart method_signature, look inside inner signature types
  766. if (node.type === 'method_signature') {
  767. for (let i = 0; i < node.namedChildCount; i++) {
  768. const child = node.namedChild(i);
  769. if (child && (
  770. child.type === 'function_signature' ||
  771. child.type === 'getter_signature' ||
  772. child.type === 'setter_signature' ||
  773. child.type === 'constructor_signature' ||
  774. child.type === 'factory_constructor_signature'
  775. )) {
  776. // Find identifier inside the inner signature
  777. for (let j = 0; j < child.namedChildCount; j++) {
  778. const inner = child.namedChild(j);
  779. if (inner?.type === 'identifier') {
  780. return getNodeText(inner, source);
  781. }
  782. }
  783. }
  784. }
  785. }
  786. // Fall back to first identifier child
  787. for (let i = 0; i < node.namedChildCount; i++) {
  788. const child = node.namedChild(i);
  789. if (
  790. child &&
  791. (child.type === 'identifier' ||
  792. child.type === 'type_identifier' ||
  793. child.type === 'simple_identifier' ||
  794. child.type === 'constant')
  795. ) {
  796. return getNodeText(child, source);
  797. }
  798. }
  799. return '<anonymous>';
  800. }
  801. /**
  802. * TreeSitterExtractor - Main extraction class
  803. */
  804. export class TreeSitterExtractor {
  805. private filePath: string;
  806. private language: Language;
  807. private source: string;
  808. private tree: Tree | null = null;
  809. private nodes: Node[] = [];
  810. private edges: Edge[] = [];
  811. private unresolvedReferences: UnresolvedReference[] = [];
  812. private errors: ExtractionError[] = [];
  813. private extractor: LanguageExtractor | null = null;
  814. private nodeStack: string[] = []; // Stack of parent node IDs
  815. constructor(filePath: string, source: string, language?: Language) {
  816. this.filePath = filePath;
  817. this.source = source;
  818. this.language = language || detectLanguage(filePath);
  819. this.extractor = EXTRACTORS[this.language] || null;
  820. }
  821. /**
  822. * Parse and extract from the source code
  823. */
  824. extract(): ExtractionResult {
  825. const startTime = Date.now();
  826. if (!isLanguageSupported(this.language)) {
  827. return {
  828. nodes: [],
  829. edges: [],
  830. unresolvedReferences: [],
  831. errors: [
  832. {
  833. message: `Unsupported language: ${this.language}`,
  834. severity: 'error',
  835. },
  836. ],
  837. durationMs: Date.now() - startTime,
  838. };
  839. }
  840. const parser = getParser(this.language);
  841. if (!parser) {
  842. return {
  843. nodes: [],
  844. edges: [],
  845. unresolvedReferences: [],
  846. errors: [
  847. {
  848. message: `Failed to get parser for language: ${this.language}`,
  849. severity: 'error',
  850. },
  851. ],
  852. durationMs: Date.now() - startTime,
  853. };
  854. }
  855. try {
  856. this.tree = parser.parse(this.source);
  857. this.visitNode(this.tree.rootNode);
  858. } catch (error) {
  859. captureException(error, { operation: 'tree-sitter-parse', filePath: this.filePath, language: this.language });
  860. this.errors.push({
  861. message: `Parse error: ${error instanceof Error ? error.message : String(error)}`,
  862. severity: 'error',
  863. });
  864. }
  865. return {
  866. nodes: this.nodes,
  867. edges: this.edges,
  868. unresolvedReferences: this.unresolvedReferences,
  869. errors: this.errors,
  870. durationMs: Date.now() - startTime,
  871. };
  872. }
  873. /**
  874. * Visit a node and extract information
  875. */
  876. private visitNode(node: SyntaxNode): void {
  877. if (!this.extractor) return;
  878. const nodeType = node.type;
  879. let skipChildren = false;
  880. // Check for function declarations
  881. // For Python/Ruby, function_definition inside a class should be treated as method
  882. if (this.extractor.functionTypes.includes(nodeType)) {
  883. if (this.nodeStack.length > 0 && this.extractor.methodTypes.includes(nodeType)) {
  884. // Inside a class - treat as method
  885. this.extractMethod(node);
  886. skipChildren = true; // extractMethod visits children via visitFunctionBody
  887. } else {
  888. this.extractFunction(node);
  889. skipChildren = true; // extractFunction visits children via visitFunctionBody
  890. }
  891. }
  892. // Check for class declarations
  893. else if (this.extractor.classTypes.includes(nodeType)) {
  894. // Swift uses class_declaration for both classes and structs
  895. // Check for 'struct' child to differentiate
  896. if (this.language === 'swift' && this.hasChildOfType(node, 'struct')) {
  897. this.extractStruct(node);
  898. } else if (this.language === 'swift' && this.hasChildOfType(node, 'enum')) {
  899. this.extractEnum(node);
  900. } else {
  901. this.extractClass(node);
  902. }
  903. skipChildren = true; // extractClass visits body children
  904. }
  905. // Dart-specific: mixin and extension declarations treated as classes
  906. else if (this.language === 'dart' && (nodeType === 'mixin_declaration' || nodeType === 'extension_declaration')) {
  907. this.extractClass(node);
  908. skipChildren = true;
  909. }
  910. // Check for method declarations (only if not already handled by functionTypes)
  911. else if (this.extractor.methodTypes.includes(nodeType)) {
  912. this.extractMethod(node);
  913. skipChildren = true; // extractMethod visits children via visitFunctionBody
  914. }
  915. // Check for interface/protocol/trait declarations
  916. else if (this.extractor.interfaceTypes.includes(nodeType)) {
  917. this.extractInterface(node);
  918. skipChildren = true; // extractInterface visits body children
  919. }
  920. // Check for struct declarations
  921. else if (this.extractor.structTypes.includes(nodeType)) {
  922. this.extractStruct(node);
  923. skipChildren = true; // extractStruct visits body children
  924. }
  925. // Check for enum declarations
  926. else if (this.extractor.enumTypes.includes(nodeType)) {
  927. this.extractEnum(node);
  928. skipChildren = true; // extractEnum visits body children
  929. }
  930. // Check for type alias declarations (e.g. `type X = ...` in TypeScript)
  931. else if (this.extractor.typeAliasTypes.includes(nodeType)) {
  932. this.extractTypeAlias(node);
  933. }
  934. // Check for variable declarations (const, let, var, etc.)
  935. // Only extract top-level variables (not inside functions/methods)
  936. else if (this.extractor.variableTypes.includes(nodeType) && this.nodeStack.length === 0) {
  937. this.extractVariable(node);
  938. skipChildren = true; // extractVariable handles children
  939. }
  940. // Check for export statements containing non-function variable declarations
  941. // e.g. `export const X = create(...)`, `export const X = { ... }`
  942. else if (nodeType === 'export_statement') {
  943. this.extractExportedVariables(node);
  944. // Don't skip children — still need to visit inner nodes (functions, calls, etc.)
  945. }
  946. // Check for imports
  947. else if (this.extractor.importTypes.includes(nodeType)) {
  948. this.extractImport(node);
  949. }
  950. // Check for function calls
  951. else if (this.extractor.callTypes.includes(nodeType)) {
  952. this.extractCall(node);
  953. }
  954. // Visit children (unless the extract method already visited them)
  955. if (!skipChildren) {
  956. for (let i = 0; i < node.namedChildCount; i++) {
  957. const child = node.namedChild(i);
  958. if (child) {
  959. this.visitNode(child);
  960. }
  961. }
  962. }
  963. }
  964. /**
  965. * Create a Node object
  966. */
  967. private createNode(
  968. kind: NodeKind,
  969. name: string,
  970. node: SyntaxNode,
  971. extra?: Partial<Node>
  972. ): Node {
  973. const id = generateNodeId(this.filePath, kind, name, node.startPosition.row + 1);
  974. const newNode: Node = {
  975. id,
  976. kind,
  977. name,
  978. qualifiedName: this.buildQualifiedName(name),
  979. filePath: this.filePath,
  980. language: this.language,
  981. startLine: node.startPosition.row + 1,
  982. endLine: node.endPosition.row + 1,
  983. startColumn: node.startPosition.column,
  984. endColumn: node.endPosition.column,
  985. updatedAt: Date.now(),
  986. ...extra,
  987. };
  988. this.nodes.push(newNode);
  989. // Add containment edge from parent
  990. if (this.nodeStack.length > 0) {
  991. const parentId = this.nodeStack[this.nodeStack.length - 1];
  992. if (parentId) {
  993. this.edges.push({
  994. source: parentId,
  995. target: id,
  996. kind: 'contains',
  997. });
  998. }
  999. }
  1000. return newNode;
  1001. }
  1002. /**
  1003. * Build qualified name from node stack
  1004. */
  1005. private buildQualifiedName(name: string): string {
  1006. // Get names from the node stack
  1007. const parts: string[] = [this.filePath];
  1008. for (const nodeId of this.nodeStack) {
  1009. const node = this.nodes.find((n) => n.id === nodeId);
  1010. if (node) {
  1011. parts.push(node.name);
  1012. }
  1013. }
  1014. parts.push(name);
  1015. return parts.join('::');
  1016. }
  1017. /**
  1018. * Check if a node has a child of a specific type
  1019. */
  1020. private hasChildOfType(node: SyntaxNode, type: string): boolean {
  1021. for (let i = 0; i < node.childCount; i++) {
  1022. const child = node.child(i);
  1023. if (child?.type === type) {
  1024. return true;
  1025. }
  1026. }
  1027. return false;
  1028. }
  1029. /**
  1030. * Extract a function
  1031. */
  1032. private extractFunction(node: SyntaxNode): void {
  1033. if (!this.extractor) return;
  1034. let name = extractName(node, this.source, this.extractor);
  1035. // For arrow functions and function expressions assigned to variables,
  1036. // resolve the name from the parent variable_declarator.
  1037. // e.g. `export const useAuth = () => { ... }` — the arrow_function node
  1038. // has no `name` field; the name lives on the variable_declarator.
  1039. if (
  1040. name === '<anonymous>' &&
  1041. (node.type === 'arrow_function' || node.type === 'function_expression')
  1042. ) {
  1043. const parent = node.parent;
  1044. if (parent?.type === 'variable_declarator') {
  1045. const varName = getChildByField(parent, 'name');
  1046. if (varName) {
  1047. name = getNodeText(varName, this.source);
  1048. }
  1049. }
  1050. }
  1051. if (name === '<anonymous>') return; // Skip anonymous functions
  1052. const docstring = getPrecedingDocstring(node, this.source);
  1053. const signature = this.extractor.getSignature?.(node, this.source);
  1054. const visibility = this.extractor.getVisibility?.(node);
  1055. const isExported = this.extractor.isExported?.(node, this.source);
  1056. const isAsync = this.extractor.isAsync?.(node);
  1057. const isStatic = this.extractor.isStatic?.(node);
  1058. const funcNode = this.createNode('function', name, node, {
  1059. docstring,
  1060. signature,
  1061. visibility,
  1062. isExported,
  1063. isAsync,
  1064. isStatic,
  1065. });
  1066. // Push to stack and visit body
  1067. this.nodeStack.push(funcNode.id);
  1068. // Dart: function_body is a next sibling of function_signature, not a child
  1069. const body = this.language === 'dart'
  1070. ? node.nextNamedSibling?.type === 'function_body' ? node.nextNamedSibling : null
  1071. : getChildByField(node, this.extractor.bodyField);
  1072. if (body) {
  1073. this.visitFunctionBody(body, funcNode.id);
  1074. }
  1075. this.nodeStack.pop();
  1076. }
  1077. /**
  1078. * Extract a class
  1079. */
  1080. private extractClass(node: SyntaxNode): void {
  1081. if (!this.extractor) return;
  1082. const name = extractName(node, this.source, this.extractor);
  1083. const docstring = getPrecedingDocstring(node, this.source);
  1084. const visibility = this.extractor.getVisibility?.(node);
  1085. const isExported = this.extractor.isExported?.(node, this.source);
  1086. const classNode = this.createNode('class', name, node, {
  1087. docstring,
  1088. visibility,
  1089. isExported,
  1090. });
  1091. // Extract extends/implements
  1092. this.extractInheritance(node, classNode.id);
  1093. // Push to stack and visit body
  1094. this.nodeStack.push(classNode.id);
  1095. let body = getChildByField(node, this.extractor.bodyField);
  1096. // Dart: mixin_declaration uses class_body, extension uses extension_body
  1097. if (!body && this.language === 'dart') {
  1098. body = node.namedChildren.find((c: SyntaxNode) =>
  1099. c.type === 'class_body' || c.type === 'extension_body'
  1100. ) || null;
  1101. }
  1102. if (!body) body = node;
  1103. // Visit all children for methods and properties
  1104. for (let i = 0; i < body.namedChildCount; i++) {
  1105. const child = body.namedChild(i);
  1106. if (child) {
  1107. this.visitNode(child);
  1108. }
  1109. }
  1110. this.nodeStack.pop();
  1111. }
  1112. /**
  1113. * Extract a method
  1114. */
  1115. private extractMethod(node: SyntaxNode): void {
  1116. if (!this.extractor) return;
  1117. // For most languages, only extract as method if inside a class
  1118. // But Go methods are top-level with a receiver, so always treat them as methods
  1119. if (this.nodeStack.length === 0 && this.language !== 'go') {
  1120. // Top-level and not Go, treat as function
  1121. this.extractFunction(node);
  1122. return;
  1123. }
  1124. const name = extractName(node, this.source, this.extractor);
  1125. const docstring = getPrecedingDocstring(node, this.source);
  1126. const signature = this.extractor.getSignature?.(node, this.source);
  1127. const visibility = this.extractor.getVisibility?.(node);
  1128. const isAsync = this.extractor.isAsync?.(node);
  1129. const isStatic = this.extractor.isStatic?.(node);
  1130. const methodNode = this.createNode('method', name, node, {
  1131. docstring,
  1132. signature,
  1133. visibility,
  1134. isAsync,
  1135. isStatic,
  1136. });
  1137. // Push to stack and visit body
  1138. this.nodeStack.push(methodNode.id);
  1139. // Dart: function_body is a next sibling of method_signature, not a child
  1140. const body = this.language === 'dart'
  1141. ? node.nextNamedSibling?.type === 'function_body' ? node.nextNamedSibling : null
  1142. : getChildByField(node, this.extractor.bodyField);
  1143. if (body) {
  1144. this.visitFunctionBody(body, methodNode.id);
  1145. }
  1146. this.nodeStack.pop();
  1147. }
  1148. /**
  1149. * Extract an interface/protocol/trait
  1150. */
  1151. private extractInterface(node: SyntaxNode): void {
  1152. if (!this.extractor) return;
  1153. const name = extractName(node, this.source, this.extractor);
  1154. const docstring = getPrecedingDocstring(node, this.source);
  1155. const isExported = this.extractor.isExported?.(node, this.source);
  1156. // Determine kind based on language
  1157. let kind: NodeKind = 'interface';
  1158. if (this.language === 'rust') kind = 'trait';
  1159. this.createNode(kind, name, node, {
  1160. docstring,
  1161. isExported,
  1162. });
  1163. }
  1164. /**
  1165. * Extract a struct
  1166. */
  1167. private extractStruct(node: SyntaxNode): void {
  1168. if (!this.extractor) return;
  1169. const name = extractName(node, this.source, this.extractor);
  1170. const docstring = getPrecedingDocstring(node, this.source);
  1171. const visibility = this.extractor.getVisibility?.(node);
  1172. const isExported = this.extractor.isExported?.(node, this.source);
  1173. const structNode = this.createNode('struct', name, node, {
  1174. docstring,
  1175. visibility,
  1176. isExported,
  1177. });
  1178. // Push to stack for field extraction
  1179. this.nodeStack.push(structNode.id);
  1180. const body = getChildByField(node, this.extractor.bodyField) || node;
  1181. for (let i = 0; i < body.namedChildCount; i++) {
  1182. const child = body.namedChild(i);
  1183. if (child) {
  1184. this.visitNode(child);
  1185. }
  1186. }
  1187. this.nodeStack.pop();
  1188. }
  1189. /**
  1190. * Extract an enum
  1191. */
  1192. private extractEnum(node: SyntaxNode): void {
  1193. if (!this.extractor) return;
  1194. const name = extractName(node, this.source, this.extractor);
  1195. const docstring = getPrecedingDocstring(node, this.source);
  1196. const visibility = this.extractor.getVisibility?.(node);
  1197. const isExported = this.extractor.isExported?.(node, this.source);
  1198. this.createNode('enum', name, node, {
  1199. docstring,
  1200. visibility,
  1201. isExported,
  1202. });
  1203. }
  1204. /**
  1205. * Extract a variable declaration (const, let, var, etc.)
  1206. *
  1207. * Extracts top-level and module-level variable declarations.
  1208. * Captures the variable name and first 100 chars of initializer in signature for searchability.
  1209. */
  1210. private extractVariable(node: SyntaxNode): void {
  1211. if (!this.extractor) return;
  1212. // Different languages have different variable declaration structures
  1213. // TypeScript/JavaScript: lexical_declaration contains variable_declarator children
  1214. // Python: assignment has left (identifier) and right (value)
  1215. // Go: var_declaration, short_var_declaration, const_declaration
  1216. const isConst = this.extractor.isConst?.(node) ?? false;
  1217. const kind: NodeKind = isConst ? 'constant' : 'variable';
  1218. const docstring = getPrecedingDocstring(node, this.source);
  1219. const isExported = this.extractor.isExported?.(node, this.source) ?? false;
  1220. // Extract variable declarators based on language
  1221. if (this.language === 'typescript' || this.language === 'javascript' ||
  1222. this.language === 'tsx' || this.language === 'jsx') {
  1223. // Handle lexical_declaration and variable_declaration
  1224. // These contain one or more variable_declarator children
  1225. for (let i = 0; i < node.namedChildCount; i++) {
  1226. const child = node.namedChild(i);
  1227. if (child?.type === 'variable_declarator') {
  1228. const nameNode = getChildByField(child, 'name');
  1229. const valueNode = getChildByField(child, 'value');
  1230. if (nameNode) {
  1231. const name = getNodeText(nameNode, this.source);
  1232. // Arrow functions / function expressions: extract as function instead of variable
  1233. if (valueNode && (valueNode.type === 'arrow_function' || valueNode.type === 'function_expression')) {
  1234. this.extractFunction(valueNode);
  1235. continue;
  1236. }
  1237. // Capture first 100 chars of initializer for context (stored in signature for searchability)
  1238. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  1239. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1240. this.createNode(kind, name, child, {
  1241. docstring,
  1242. signature: initSignature,
  1243. isExported,
  1244. });
  1245. }
  1246. }
  1247. }
  1248. } else if (this.language === 'python' || this.language === 'ruby') {
  1249. // Python/Ruby assignment: left = right
  1250. const left = getChildByField(node, 'left') || node.namedChild(0);
  1251. const right = getChildByField(node, 'right') || node.namedChild(1);
  1252. if (left && left.type === 'identifier') {
  1253. const name = getNodeText(left, this.source);
  1254. // Skip if name starts with lowercase and looks like a function call result
  1255. // Python constants are usually UPPER_CASE
  1256. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  1257. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1258. this.createNode(kind, name, node, {
  1259. docstring,
  1260. signature: initSignature,
  1261. });
  1262. }
  1263. } else if (this.language === 'go') {
  1264. // Go: var_declaration, short_var_declaration, const_declaration
  1265. // These can have multiple identifiers on the left
  1266. const specs = node.namedChildren.filter(c =>
  1267. c.type === 'var_spec' || c.type === 'const_spec'
  1268. );
  1269. for (const spec of specs) {
  1270. const nameNode = spec.namedChild(0);
  1271. if (nameNode && nameNode.type === 'identifier') {
  1272. const name = getNodeText(nameNode, this.source);
  1273. const valueNode = spec.namedChildCount > 1 ? spec.namedChild(spec.namedChildCount - 1) : null;
  1274. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  1275. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1276. this.createNode(node.type === 'const_declaration' ? 'constant' : 'variable', name, spec, {
  1277. docstring,
  1278. signature: initSignature,
  1279. });
  1280. }
  1281. }
  1282. // Handle short_var_declaration (:=)
  1283. if (node.type === 'short_var_declaration') {
  1284. const left = getChildByField(node, 'left');
  1285. const right = getChildByField(node, 'right');
  1286. if (left) {
  1287. // Can be expression_list with multiple identifiers
  1288. const identifiers = left.type === 'expression_list'
  1289. ? left.namedChildren.filter(c => c.type === 'identifier')
  1290. : [left];
  1291. for (const id of identifiers) {
  1292. const name = getNodeText(id, this.source);
  1293. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  1294. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1295. this.createNode('variable', name, node, {
  1296. docstring,
  1297. signature: initSignature,
  1298. });
  1299. }
  1300. }
  1301. }
  1302. } else {
  1303. // Generic fallback for other languages
  1304. // Try to find identifier children
  1305. for (let i = 0; i < node.namedChildCount; i++) {
  1306. const child = node.namedChild(i);
  1307. if (child?.type === 'identifier' || child?.type === 'variable_declarator') {
  1308. const name = child.type === 'identifier'
  1309. ? getNodeText(child, this.source)
  1310. : extractName(child, this.source, this.extractor);
  1311. if (name && name !== '<anonymous>') {
  1312. this.createNode(kind, name, child, {
  1313. docstring,
  1314. isExported,
  1315. });
  1316. }
  1317. }
  1318. }
  1319. }
  1320. }
  1321. /**
  1322. * Extract a type alias (e.g. `export type X = ...` in TypeScript)
  1323. */
  1324. private extractTypeAlias(node: SyntaxNode): void {
  1325. if (!this.extractor) return;
  1326. const name = extractName(node, this.source, this.extractor);
  1327. if (name === '<anonymous>') return;
  1328. const docstring = getPrecedingDocstring(node, this.source);
  1329. const isExported = this.extractor.isExported?.(node, this.source);
  1330. this.createNode('type_alias', name, node, {
  1331. docstring,
  1332. isExported,
  1333. });
  1334. }
  1335. /**
  1336. * Extract an exported variable declaration that isn't a function.
  1337. * Handles patterns like:
  1338. * export const X = create(...)
  1339. * export const X = { ... }
  1340. * export const X = [...]
  1341. * export const X = "value"
  1342. *
  1343. * This is called for `export_statement` nodes that contain a
  1344. * `lexical_declaration` with `variable_declarator` children whose
  1345. * values are NOT already handled by functionTypes (arrow_function,
  1346. * function_expression).
  1347. */
  1348. private extractExportedVariables(exportNode: SyntaxNode): void {
  1349. if (!this.extractor) return;
  1350. // Find the lexical_declaration or variable_declaration child
  1351. for (let i = 0; i < exportNode.namedChildCount; i++) {
  1352. const decl = exportNode.namedChild(i);
  1353. if (!decl || (decl.type !== 'lexical_declaration' && decl.type !== 'variable_declaration')) {
  1354. continue;
  1355. }
  1356. // Iterate over each variable_declarator in the declaration
  1357. for (let j = 0; j < decl.namedChildCount; j++) {
  1358. const declarator = decl.namedChild(j);
  1359. if (!declarator || declarator.type !== 'variable_declarator') continue;
  1360. const nameNode = getChildByField(declarator, 'name');
  1361. if (!nameNode) continue;
  1362. const name = getNodeText(nameNode, this.source);
  1363. // Skip if the value is a function type — those are already handled
  1364. // by extractFunction via the functionTypes dispatch
  1365. const value = getChildByField(declarator, 'value');
  1366. if (value) {
  1367. const valueType = value.type;
  1368. if (
  1369. this.extractor.functionTypes.includes(valueType)
  1370. ) {
  1371. continue; // Already handled by extractFunction
  1372. }
  1373. }
  1374. const docstring = getPrecedingDocstring(exportNode, this.source);
  1375. this.createNode('variable', name, declarator, {
  1376. docstring,
  1377. isExported: true,
  1378. });
  1379. }
  1380. }
  1381. }
  1382. /**
  1383. * Extract an import
  1384. *
  1385. * Creates an import node with the full import statement stored in signature for searchability.
  1386. * Also creates unresolved references for resolution purposes.
  1387. */
  1388. private extractImport(node: SyntaxNode): void {
  1389. const importText = getNodeText(node, this.source).trim();
  1390. // Extract module/package name based on language
  1391. let moduleName = '';
  1392. if (this.language === 'typescript' || this.language === 'javascript' ||
  1393. this.language === 'tsx' || this.language === 'jsx') {
  1394. const source = getChildByField(node, 'source');
  1395. if (source) {
  1396. moduleName = getNodeText(source, this.source).replace(/['"]/g, '');
  1397. }
  1398. // Create import node with full statement as signature for searchability
  1399. if (moduleName) {
  1400. this.createNode('import', moduleName, node, {
  1401. signature: importText,
  1402. });
  1403. }
  1404. } else if (this.language === 'python') {
  1405. // Python has two import forms:
  1406. // 1. import_statement: import os, sys
  1407. // 2. import_from_statement: from os import path
  1408. if (node.type === 'import_from_statement') {
  1409. const moduleNode = getChildByField(node, 'module_name');
  1410. if (moduleNode) {
  1411. moduleName = getNodeText(moduleNode, this.source);
  1412. }
  1413. } else {
  1414. // import_statement - may have multiple modules
  1415. // Can be dotted_name (import os) or aliased_import (import numpy as np)
  1416. for (let i = 0; i < node.namedChildCount; i++) {
  1417. const child = node.namedChild(i);
  1418. if (child?.type === 'dotted_name') {
  1419. const name = getNodeText(child, this.source);
  1420. this.createNode('import', name, node, {
  1421. signature: importText,
  1422. });
  1423. } else if (child?.type === 'aliased_import') {
  1424. // Extract the module name from inside aliased_import
  1425. const dottedName = child.namedChildren.find(c => c.type === 'dotted_name');
  1426. if (dottedName) {
  1427. const name = getNodeText(dottedName, this.source);
  1428. this.createNode('import', name, node, {
  1429. signature: importText,
  1430. });
  1431. }
  1432. }
  1433. }
  1434. // Skip creating another node below if we handled import_statement
  1435. if (node.type === 'import_statement') {
  1436. return;
  1437. }
  1438. }
  1439. if (moduleName) {
  1440. this.createNode('import', moduleName, node, {
  1441. signature: importText,
  1442. });
  1443. }
  1444. } else if (this.language === 'go') {
  1445. // Go imports can be single or grouped
  1446. // Single: import "fmt" - uses import_spec directly as child
  1447. // Grouped: import ( "fmt" \n "os" ) - uses import_spec_list containing import_spec children
  1448. // Helper function to extract path from import_spec
  1449. const extractFromSpec = (spec: SyntaxNode): void => {
  1450. const stringLiteral = spec.namedChildren.find(c => c.type === 'interpreted_string_literal');
  1451. if (stringLiteral) {
  1452. const path = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  1453. if (path) {
  1454. this.createNode('import', path, spec, {
  1455. signature: getNodeText(spec, this.source).trim(),
  1456. });
  1457. }
  1458. }
  1459. };
  1460. // Find import_spec_list for grouped imports
  1461. const importSpecList = node.namedChildren.find(c => c.type === 'import_spec_list');
  1462. if (importSpecList) {
  1463. // Grouped imports - iterate through import_spec children
  1464. const importSpecs = importSpecList.namedChildren.filter(c => c.type === 'import_spec');
  1465. for (const spec of importSpecs) {
  1466. extractFromSpec(spec);
  1467. }
  1468. } else {
  1469. // Single import: import "fmt" - import_spec is direct child
  1470. const importSpec = node.namedChildren.find(c => c.type === 'import_spec');
  1471. if (importSpec) {
  1472. extractFromSpec(importSpec);
  1473. }
  1474. }
  1475. return; // Go handled completely above
  1476. } else if (this.language === 'rust') {
  1477. // Rust use declarations
  1478. // use std::{ffi::OsStr, io}; -> scoped_use_list with identifier "std"
  1479. // use crate::error::Error; -> scoped_identifier starting with "crate"
  1480. // use super::utils; -> scoped_identifier starting with "super"
  1481. // Helper to get the root crate/module from a scoped path
  1482. const getRootModule = (scopedNode: SyntaxNode): string => {
  1483. // Recursively find the leftmost identifier/crate/super/self
  1484. const firstChild = scopedNode.namedChild(0);
  1485. if (!firstChild) return getNodeText(scopedNode, this.source);
  1486. if (firstChild.type === 'identifier' ||
  1487. firstChild.type === 'crate' ||
  1488. firstChild.type === 'super' ||
  1489. firstChild.type === 'self') {
  1490. return getNodeText(firstChild, this.source);
  1491. } else if (firstChild.type === 'scoped_identifier') {
  1492. return getRootModule(firstChild);
  1493. }
  1494. return getNodeText(firstChild, this.source);
  1495. };
  1496. // Find the use argument (scoped_use_list or scoped_identifier)
  1497. const useArg = node.namedChildren.find(c =>
  1498. c.type === 'scoped_use_list' ||
  1499. c.type === 'scoped_identifier' ||
  1500. c.type === 'use_list' ||
  1501. c.type === 'identifier'
  1502. );
  1503. if (useArg) {
  1504. moduleName = getRootModule(useArg);
  1505. this.createNode('import', moduleName, node, {
  1506. signature: importText,
  1507. });
  1508. }
  1509. return; // Rust handled completely above
  1510. } else if (this.language === 'swift') {
  1511. // Swift imports: import Foundation, @testable import Alamofire
  1512. // AST structure: import_declaration -> identifier -> simple_identifier
  1513. const identifier = node.namedChildren.find(c => c.type === 'identifier');
  1514. if (identifier) {
  1515. moduleName = getNodeText(identifier, this.source);
  1516. this.createNode('import', moduleName, node, {
  1517. signature: importText,
  1518. });
  1519. }
  1520. return; // Swift handled completely above
  1521. } else if (this.language === 'kotlin') {
  1522. // Kotlin imports: import java.io.IOException, import x.y.Z as Alias, import x.y.*
  1523. // AST structure: import_header -> identifier (dotted path)
  1524. const identifier = node.namedChildren.find(c => c.type === 'identifier');
  1525. if (identifier) {
  1526. moduleName = getNodeText(identifier, this.source);
  1527. this.createNode('import', moduleName, node, {
  1528. signature: importText,
  1529. });
  1530. }
  1531. return; // Kotlin handled completely above
  1532. } else if (this.language === 'java') {
  1533. // Java imports: import java.util.List, import static x.Y.method, import x.y.*
  1534. // AST structure: import_declaration -> scoped_identifier (dotted path)
  1535. const scopedId = node.namedChildren.find(c => c.type === 'scoped_identifier');
  1536. if (scopedId) {
  1537. moduleName = getNodeText(scopedId, this.source);
  1538. this.createNode('import', moduleName, node, {
  1539. signature: importText,
  1540. });
  1541. }
  1542. return; // Java handled completely above
  1543. } else if (this.language === 'csharp') {
  1544. // C# using directives: using System, using System.Collections.Generic, using static X, using Alias = X
  1545. // AST structure: using_directive -> qualified_name (dotted) or identifier (simple)
  1546. // For alias imports: identifier = qualified_name - we want the qualified_name
  1547. const qualifiedName = node.namedChildren.find(c => c.type === 'qualified_name');
  1548. if (qualifiedName) {
  1549. moduleName = getNodeText(qualifiedName, this.source);
  1550. } else {
  1551. // Simple namespace like "using System;" - get the first identifier
  1552. const identifier = node.namedChildren.find(c => c.type === 'identifier');
  1553. if (identifier) {
  1554. moduleName = getNodeText(identifier, this.source);
  1555. }
  1556. }
  1557. if (moduleName) {
  1558. this.createNode('import', moduleName, node, {
  1559. signature: importText,
  1560. });
  1561. }
  1562. return; // C# handled completely above
  1563. } else if (this.language === 'php') {
  1564. // PHP use declarations: use X\Y\Z, use X as Y, use function X\func, use X\{A, B}
  1565. // AST structure: namespace_use_declaration -> namespace_use_clause -> qualified_name or name
  1566. // Check for grouped imports first: use X\{A, B}
  1567. const namespacePrefix = node.namedChildren.find(c => c.type === 'namespace_name');
  1568. const useGroup = node.namedChildren.find(c => c.type === 'namespace_use_group');
  1569. if (namespacePrefix && useGroup) {
  1570. // Grouped import - create one import per item
  1571. const prefix = getNodeText(namespacePrefix, this.source);
  1572. const useClauses = useGroup.namedChildren.filter((c: SyntaxNode) => c.type === 'namespace_use_clause');
  1573. for (const clause of useClauses) {
  1574. const name = clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  1575. if (name) {
  1576. const fullPath = `${prefix}\\${getNodeText(name, this.source)}`;
  1577. this.createNode('import', fullPath, node, {
  1578. signature: importText,
  1579. });
  1580. }
  1581. }
  1582. return;
  1583. }
  1584. // Single import - find namespace_use_clause
  1585. const useClause = node.namedChildren.find(c => c.type === 'namespace_use_clause');
  1586. if (useClause) {
  1587. // Look for qualified_name (full path) or name (simple)
  1588. const qualifiedName = useClause.namedChildren.find((c: SyntaxNode) => c.type === 'qualified_name');
  1589. if (qualifiedName) {
  1590. moduleName = getNodeText(qualifiedName, this.source);
  1591. } else {
  1592. const name = useClause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  1593. if (name) {
  1594. moduleName = getNodeText(name, this.source);
  1595. }
  1596. }
  1597. }
  1598. if (moduleName) {
  1599. this.createNode('import', moduleName, node, {
  1600. signature: importText,
  1601. });
  1602. }
  1603. return; // PHP handled completely above
  1604. } else if (this.language === 'ruby') {
  1605. // Ruby imports: require 'json', require_relative '../helper'
  1606. // AST structure: call -> identifier (require/require_relative) + argument_list -> string -> string_content
  1607. // Check if this is a require/require_relative call
  1608. const identifier = node.namedChildren.find(c => c.type === 'identifier');
  1609. if (!identifier) return;
  1610. const methodName = getNodeText(identifier, this.source);
  1611. if (methodName !== 'require' && methodName !== 'require_relative') {
  1612. return; // Not an import, skip
  1613. }
  1614. // Find the argument (string)
  1615. const argList = node.namedChildren.find(c => c.type === 'argument_list');
  1616. if (argList) {
  1617. const stringNode = argList.namedChildren.find((c: SyntaxNode) => c.type === 'string');
  1618. if (stringNode) {
  1619. // Get string_content (without quotes)
  1620. const stringContent = stringNode.namedChildren.find((c: SyntaxNode) => c.type === 'string_content');
  1621. if (stringContent) {
  1622. moduleName = getNodeText(stringContent, this.source);
  1623. }
  1624. }
  1625. }
  1626. if (moduleName) {
  1627. this.createNode('import', moduleName, node, {
  1628. signature: importText,
  1629. });
  1630. }
  1631. return; // Ruby handled completely above
  1632. } else if (this.language === 'dart') {
  1633. // Dart imports: import 'dart:async'; import 'package:foo/bar.dart' as bar;
  1634. // AST: import_or_export -> library_import -> import_specification -> configurable_uri -> uri -> string_literal
  1635. const libraryImport = node.namedChildren.find(c => c.type === 'library_import');
  1636. if (libraryImport) {
  1637. const importSpec = libraryImport.namedChildren.find((c: SyntaxNode) => c.type === 'import_specification');
  1638. if (importSpec) {
  1639. const configurableUri = importSpec.namedChildren.find((c: SyntaxNode) => c.type === 'configurable_uri');
  1640. if (configurableUri) {
  1641. const uri = configurableUri.namedChildren.find((c: SyntaxNode) => c.type === 'uri');
  1642. if (uri) {
  1643. const stringLiteral = uri.namedChildren.find((c: SyntaxNode) => c.type === 'string_literal');
  1644. if (stringLiteral) {
  1645. moduleName = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  1646. }
  1647. }
  1648. }
  1649. }
  1650. }
  1651. // Also handle exports: export 'src/foo.dart';
  1652. const libraryExport = node.namedChildren.find(c => c.type === 'library_export');
  1653. if (libraryExport) {
  1654. const configurableUri = libraryExport.namedChildren.find((c: SyntaxNode) => c.type === 'configurable_uri');
  1655. if (configurableUri) {
  1656. const uri = configurableUri.namedChildren.find((c: SyntaxNode) => c.type === 'uri');
  1657. if (uri) {
  1658. const stringLiteral = uri.namedChildren.find((c: SyntaxNode) => c.type === 'string_literal');
  1659. if (stringLiteral) {
  1660. moduleName = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  1661. }
  1662. }
  1663. }
  1664. }
  1665. if (moduleName) {
  1666. this.createNode('import', moduleName, node, {
  1667. signature: importText,
  1668. });
  1669. }
  1670. return; // Dart handled completely above
  1671. } else if (this.language === 'c' || this.language === 'cpp') {
  1672. // C/C++ includes: #include <iostream>, #include "myheader.h"
  1673. // AST: preproc_include -> system_lib_string (<...>) or string_literal ("...")
  1674. // Check for system include: <path>
  1675. const systemLib = node.namedChildren.find(c => c.type === 'system_lib_string');
  1676. if (systemLib) {
  1677. // Remove angle brackets: <iostream> -> iostream
  1678. moduleName = getNodeText(systemLib, this.source).replace(/^<|>$/g, '');
  1679. } else {
  1680. // Check for local include: "path"
  1681. const stringLiteral = node.namedChildren.find(c => c.type === 'string_literal');
  1682. if (stringLiteral) {
  1683. const stringContent = stringLiteral.namedChildren.find((c: SyntaxNode) => c.type === 'string_content');
  1684. if (stringContent) {
  1685. moduleName = getNodeText(stringContent, this.source);
  1686. }
  1687. }
  1688. }
  1689. if (moduleName) {
  1690. this.createNode('import', moduleName, node, {
  1691. signature: importText,
  1692. });
  1693. }
  1694. return; // C/C++ handled completely above
  1695. } else {
  1696. // Generic extraction for other languages
  1697. moduleName = importText;
  1698. if (moduleName) {
  1699. this.createNode('import', moduleName, node, {
  1700. signature: importText,
  1701. });
  1702. }
  1703. }
  1704. // Keep unresolved reference creation for resolution purposes
  1705. // This is used to resolve imports to their target files/modules
  1706. if (moduleName && this.nodeStack.length > 0) {
  1707. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1708. if (parentId) {
  1709. this.unresolvedReferences.push({
  1710. fromNodeId: parentId,
  1711. referenceName: moduleName,
  1712. referenceKind: 'imports',
  1713. line: node.startPosition.row + 1,
  1714. column: node.startPosition.column,
  1715. });
  1716. }
  1717. }
  1718. }
  1719. /**
  1720. * Extract a function call
  1721. */
  1722. private extractCall(node: SyntaxNode): void {
  1723. if (this.nodeStack.length === 0) return;
  1724. const callerId = this.nodeStack[this.nodeStack.length - 1];
  1725. if (!callerId) return;
  1726. // Get the function/method being called
  1727. let calleeName = '';
  1728. const func = getChildByField(node, 'function') || node.namedChild(0);
  1729. if (func) {
  1730. if (func.type === 'member_expression' || func.type === 'attribute') {
  1731. // Method call: obj.method()
  1732. const property = getChildByField(func, 'property') || func.namedChild(1);
  1733. if (property) {
  1734. calleeName = getNodeText(property, this.source);
  1735. }
  1736. } else if (func.type === 'scoped_identifier' || func.type === 'scoped_call_expression') {
  1737. // Scoped call: Module::function()
  1738. calleeName = getNodeText(func, this.source);
  1739. } else {
  1740. calleeName = getNodeText(func, this.source);
  1741. }
  1742. }
  1743. if (calleeName) {
  1744. this.unresolvedReferences.push({
  1745. fromNodeId: callerId,
  1746. referenceName: calleeName,
  1747. referenceKind: 'calls',
  1748. line: node.startPosition.row + 1,
  1749. column: node.startPosition.column,
  1750. });
  1751. }
  1752. }
  1753. /**
  1754. * Visit function body and extract calls
  1755. */
  1756. private visitFunctionBody(body: SyntaxNode, _functionId: string): void {
  1757. if (!this.extractor) return;
  1758. // Recursively find all call expressions
  1759. const visitForCalls = (node: SyntaxNode): void => {
  1760. if (this.extractor!.callTypes.includes(node.type)) {
  1761. this.extractCall(node);
  1762. }
  1763. for (let i = 0; i < node.namedChildCount; i++) {
  1764. const child = node.namedChild(i);
  1765. if (child) {
  1766. visitForCalls(child);
  1767. }
  1768. }
  1769. };
  1770. visitForCalls(body);
  1771. }
  1772. /**
  1773. * Extract inheritance relationships
  1774. */
  1775. private extractInheritance(node: SyntaxNode, classId: string): void {
  1776. // Look for extends/implements clauses
  1777. for (let i = 0; i < node.namedChildCount; i++) {
  1778. const child = node.namedChild(i);
  1779. if (!child) continue;
  1780. if (
  1781. child.type === 'extends_clause' ||
  1782. child.type === 'class_heritage' ||
  1783. child.type === 'superclass'
  1784. ) {
  1785. // Extract parent class name
  1786. const superclass = child.namedChild(0);
  1787. if (superclass) {
  1788. const name = getNodeText(superclass, this.source);
  1789. this.unresolvedReferences.push({
  1790. fromNodeId: classId,
  1791. referenceName: name,
  1792. referenceKind: 'extends',
  1793. line: child.startPosition.row + 1,
  1794. column: child.startPosition.column,
  1795. });
  1796. }
  1797. }
  1798. if (
  1799. child.type === 'implements_clause' ||
  1800. child.type === 'class_interface_clause' ||
  1801. child.type === 'interfaces' // Dart
  1802. ) {
  1803. // Extract implemented interfaces
  1804. for (let j = 0; j < child.namedChildCount; j++) {
  1805. const iface = child.namedChild(j);
  1806. if (iface) {
  1807. const name = getNodeText(iface, this.source);
  1808. this.unresolvedReferences.push({
  1809. fromNodeId: classId,
  1810. referenceName: name,
  1811. referenceKind: 'implements',
  1812. line: iface.startPosition.row + 1,
  1813. column: iface.startPosition.column,
  1814. });
  1815. }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. }
  1821. /**
  1822. * LiquidExtractor - Extracts relationships from Liquid template files
  1823. *
  1824. * Liquid is a templating language (used by Shopify, Jekyll, etc.) that doesn't
  1825. * have traditional functions or classes. Instead, we extract:
  1826. * - Section references ({% section 'name' %})
  1827. * - Snippet references ({% render 'name' %} and {% include 'name' %})
  1828. * - Schema blocks ({% schema %}...{% endschema %})
  1829. */
  1830. export class LiquidExtractor {
  1831. private filePath: string;
  1832. private source: string;
  1833. private nodes: Node[] = [];
  1834. private edges: Edge[] = [];
  1835. private unresolvedReferences: UnresolvedReference[] = [];
  1836. private errors: ExtractionError[] = [];
  1837. constructor(filePath: string, source: string) {
  1838. this.filePath = filePath;
  1839. this.source = source;
  1840. }
  1841. /**
  1842. * Extract from Liquid source
  1843. */
  1844. extract(): ExtractionResult {
  1845. const startTime = Date.now();
  1846. try {
  1847. // Create file node
  1848. const fileNode = this.createFileNode();
  1849. // Extract render/include statements (snippet references)
  1850. this.extractSnippetReferences(fileNode.id);
  1851. // Extract section references
  1852. this.extractSectionReferences(fileNode.id);
  1853. // Extract schema block
  1854. this.extractSchema(fileNode.id);
  1855. // Extract assign statements as variables
  1856. this.extractAssignments(fileNode.id);
  1857. } catch (error) {
  1858. captureException(error, { operation: 'liquid-extraction', filePath: this.filePath });
  1859. this.errors.push({
  1860. message: `Liquid extraction error: ${error instanceof Error ? error.message : String(error)}`,
  1861. severity: 'error',
  1862. });
  1863. }
  1864. return {
  1865. nodes: this.nodes,
  1866. edges: this.edges,
  1867. unresolvedReferences: this.unresolvedReferences,
  1868. errors: this.errors,
  1869. durationMs: Date.now() - startTime,
  1870. };
  1871. }
  1872. /**
  1873. * Create a file node for the Liquid template
  1874. */
  1875. private createFileNode(): Node {
  1876. const lines = this.source.split('\n');
  1877. const id = generateNodeId(this.filePath, 'file', this.filePath, 1);
  1878. const fileNode: Node = {
  1879. id,
  1880. kind: 'file',
  1881. name: this.filePath.split('/').pop() || this.filePath,
  1882. qualifiedName: this.filePath,
  1883. filePath: this.filePath,
  1884. language: 'liquid',
  1885. startLine: 1,
  1886. endLine: lines.length,
  1887. startColumn: 0,
  1888. endColumn: lines[lines.length - 1]?.length || 0,
  1889. updatedAt: Date.now(),
  1890. };
  1891. this.nodes.push(fileNode);
  1892. return fileNode;
  1893. }
  1894. /**
  1895. * Extract {% render 'snippet' %} and {% include 'snippet' %} references
  1896. */
  1897. private extractSnippetReferences(fileNodeId: string): void {
  1898. // Match {% render 'name' %} or {% include 'name' %} with optional parameters
  1899. const renderRegex = /\{%[-]?\s*(render|include)\s+['"]([^'"]+)['"]/g;
  1900. let match;
  1901. while ((match = renderRegex.exec(this.source)) !== null) {
  1902. const [fullMatch, tagType, snippetName] = match;
  1903. const line = this.getLineNumber(match.index);
  1904. // Create an import node for searchability
  1905. const importNodeId = generateNodeId(this.filePath, 'import', snippetName!, line);
  1906. const importNode: Node = {
  1907. id: importNodeId,
  1908. kind: 'import',
  1909. name: snippetName!,
  1910. qualifiedName: `${this.filePath}::import:${snippetName}`,
  1911. filePath: this.filePath,
  1912. language: 'liquid',
  1913. signature: fullMatch,
  1914. startLine: line,
  1915. endLine: line,
  1916. startColumn: match.index - this.getLineStart(line),
  1917. endColumn: match.index - this.getLineStart(line) + fullMatch.length,
  1918. updatedAt: Date.now(),
  1919. };
  1920. this.nodes.push(importNode);
  1921. // Add containment edge from file to import
  1922. this.edges.push({
  1923. source: fileNodeId,
  1924. target: importNodeId,
  1925. kind: 'contains',
  1926. });
  1927. // Create a component node for the snippet reference
  1928. const nodeId = generateNodeId(this.filePath, 'component', `${tagType}:${snippetName}`, line);
  1929. const node: Node = {
  1930. id: nodeId,
  1931. kind: 'component',
  1932. name: snippetName!,
  1933. qualifiedName: `${this.filePath}::${tagType}:${snippetName}`,
  1934. filePath: this.filePath,
  1935. language: 'liquid',
  1936. startLine: line,
  1937. endLine: line,
  1938. startColumn: match.index - this.getLineStart(line),
  1939. endColumn: match.index - this.getLineStart(line) + fullMatch.length,
  1940. updatedAt: Date.now(),
  1941. };
  1942. this.nodes.push(node);
  1943. // Add containment edge from file
  1944. this.edges.push({
  1945. source: fileNodeId,
  1946. target: nodeId,
  1947. kind: 'contains',
  1948. });
  1949. // Add unresolved reference to the snippet file
  1950. this.unresolvedReferences.push({
  1951. fromNodeId: fileNodeId,
  1952. referenceName: `snippets/${snippetName}.liquid`,
  1953. referenceKind: 'references',
  1954. line,
  1955. column: match.index - this.getLineStart(line),
  1956. });
  1957. }
  1958. }
  1959. /**
  1960. * Extract {% section 'name' %} references
  1961. */
  1962. private extractSectionReferences(fileNodeId: string): void {
  1963. // Match {% section 'name' %}
  1964. const sectionRegex = /\{%[-]?\s*section\s+['"]([^'"]+)['"]/g;
  1965. let match;
  1966. while ((match = sectionRegex.exec(this.source)) !== null) {
  1967. const [fullMatch, sectionName] = match;
  1968. const line = this.getLineNumber(match.index);
  1969. // Create an import node for searchability
  1970. const importNodeId = generateNodeId(this.filePath, 'import', sectionName!, line);
  1971. const importNode: Node = {
  1972. id: importNodeId,
  1973. kind: 'import',
  1974. name: sectionName!,
  1975. qualifiedName: `${this.filePath}::import:${sectionName}`,
  1976. filePath: this.filePath,
  1977. language: 'liquid',
  1978. signature: fullMatch,
  1979. startLine: line,
  1980. endLine: line,
  1981. startColumn: match.index - this.getLineStart(line),
  1982. endColumn: match.index - this.getLineStart(line) + fullMatch.length,
  1983. updatedAt: Date.now(),
  1984. };
  1985. this.nodes.push(importNode);
  1986. // Add containment edge from file to import
  1987. this.edges.push({
  1988. source: fileNodeId,
  1989. target: importNodeId,
  1990. kind: 'contains',
  1991. });
  1992. // Create a component node for the section reference
  1993. const nodeId = generateNodeId(this.filePath, 'component', `section:${sectionName}`, line);
  1994. const node: Node = {
  1995. id: nodeId,
  1996. kind: 'component',
  1997. name: sectionName!,
  1998. qualifiedName: `${this.filePath}::section:${sectionName}`,
  1999. filePath: this.filePath,
  2000. language: 'liquid',
  2001. startLine: line,
  2002. endLine: line,
  2003. startColumn: match.index - this.getLineStart(line),
  2004. endColumn: match.index - this.getLineStart(line) + fullMatch.length,
  2005. updatedAt: Date.now(),
  2006. };
  2007. this.nodes.push(node);
  2008. // Add containment edge from file
  2009. this.edges.push({
  2010. source: fileNodeId,
  2011. target: nodeId,
  2012. kind: 'contains',
  2013. });
  2014. // Add unresolved reference to the section file
  2015. this.unresolvedReferences.push({
  2016. fromNodeId: fileNodeId,
  2017. referenceName: `sections/${sectionName}.liquid`,
  2018. referenceKind: 'references',
  2019. line,
  2020. column: match.index - this.getLineStart(line),
  2021. });
  2022. }
  2023. }
  2024. /**
  2025. * Extract {% schema %}...{% endschema %} blocks
  2026. */
  2027. private extractSchema(fileNodeId: string): void {
  2028. // Match {% schema %}...{% endschema %}
  2029. const schemaRegex = /\{%[-]?\s*schema\s*[-]?%\}([\s\S]*?)\{%[-]?\s*endschema\s*[-]?%\}/g;
  2030. let match;
  2031. while ((match = schemaRegex.exec(this.source)) !== null) {
  2032. const [fullMatch, schemaContent] = match;
  2033. const startLine = this.getLineNumber(match.index);
  2034. const endLine = this.getLineNumber(match.index + fullMatch.length);
  2035. // Try to parse the schema JSON to get the name
  2036. let schemaName = 'schema';
  2037. try {
  2038. const schemaJson = JSON.parse(schemaContent!);
  2039. if (schemaJson.name) {
  2040. schemaName = schemaJson.name;
  2041. }
  2042. } catch {
  2043. // Schema isn't valid JSON, use default name
  2044. }
  2045. // Create a node for the schema
  2046. const nodeId = generateNodeId(this.filePath, 'constant', `schema:${schemaName}`, startLine);
  2047. const node: Node = {
  2048. id: nodeId,
  2049. kind: 'constant',
  2050. name: schemaName,
  2051. qualifiedName: `${this.filePath}::schema:${schemaName}`,
  2052. filePath: this.filePath,
  2053. language: 'liquid',
  2054. startLine,
  2055. endLine,
  2056. startColumn: match.index - this.getLineStart(startLine),
  2057. endColumn: 0,
  2058. docstring: schemaContent?.trim().substring(0, 200), // Store first 200 chars as docstring
  2059. updatedAt: Date.now(),
  2060. };
  2061. this.nodes.push(node);
  2062. // Add containment edge from file
  2063. this.edges.push({
  2064. source: fileNodeId,
  2065. target: nodeId,
  2066. kind: 'contains',
  2067. });
  2068. }
  2069. }
  2070. /**
  2071. * Extract {% assign var = value %} statements
  2072. */
  2073. private extractAssignments(fileNodeId: string): void {
  2074. // Match {% assign variable_name = ... %}
  2075. const assignRegex = /\{%[-]?\s*assign\s+(\w+)\s*=/g;
  2076. let match;
  2077. while ((match = assignRegex.exec(this.source)) !== null) {
  2078. const [, variableName] = match;
  2079. const line = this.getLineNumber(match.index);
  2080. // Create a variable node
  2081. const nodeId = generateNodeId(this.filePath, 'variable', variableName!, line);
  2082. const node: Node = {
  2083. id: nodeId,
  2084. kind: 'variable',
  2085. name: variableName!,
  2086. qualifiedName: `${this.filePath}::${variableName}`,
  2087. filePath: this.filePath,
  2088. language: 'liquid',
  2089. startLine: line,
  2090. endLine: line,
  2091. startColumn: match.index - this.getLineStart(line),
  2092. endColumn: match.index - this.getLineStart(line) + match[0].length,
  2093. updatedAt: Date.now(),
  2094. };
  2095. this.nodes.push(node);
  2096. // Add containment edge from file
  2097. this.edges.push({
  2098. source: fileNodeId,
  2099. target: nodeId,
  2100. kind: 'contains',
  2101. });
  2102. }
  2103. }
  2104. /**
  2105. * Get the line number for a character index
  2106. */
  2107. private getLineNumber(index: number): number {
  2108. const substring = this.source.substring(0, index);
  2109. return (substring.match(/\n/g) || []).length + 1;
  2110. }
  2111. /**
  2112. * Get the character index of the start of a line
  2113. */
  2114. private getLineStart(lineNumber: number): number {
  2115. const lines = this.source.split('\n');
  2116. let index = 0;
  2117. for (let i = 0; i < lineNumber - 1 && i < lines.length; i++) {
  2118. index += lines[i]!.length + 1; // +1 for newline
  2119. }
  2120. return index;
  2121. }
  2122. }
  2123. /**
  2124. * SvelteExtractor - Extracts code relationships from Svelte component files
  2125. *
  2126. * Svelte files are multi-language (script + template + style). Rather than
  2127. * parsing the full Svelte grammar, we extract the <script> block content
  2128. * and delegate it to the TypeScript/JavaScript TreeSitterExtractor.
  2129. *
  2130. * Every .svelte file produces a component node (Svelte components are always importable).
  2131. */
  2132. export class SvelteExtractor {
  2133. private filePath: string;
  2134. private source: string;
  2135. private nodes: Node[] = [];
  2136. private edges: Edge[] = [];
  2137. private unresolvedReferences: UnresolvedReference[] = [];
  2138. private errors: ExtractionError[] = [];
  2139. constructor(filePath: string, source: string) {
  2140. this.filePath = filePath;
  2141. this.source = source;
  2142. }
  2143. /**
  2144. * Extract from Svelte source
  2145. */
  2146. extract(): ExtractionResult {
  2147. const startTime = Date.now();
  2148. try {
  2149. // Create component node for the .svelte file itself
  2150. const componentNode = this.createComponentNode();
  2151. // Extract and process script blocks
  2152. const scriptBlocks = this.extractScriptBlocks();
  2153. for (const block of scriptBlocks) {
  2154. this.processScriptBlock(block, componentNode.id);
  2155. }
  2156. } catch (error) {
  2157. captureException(error, { operation: 'svelte-extraction', filePath: this.filePath });
  2158. this.errors.push({
  2159. message: `Svelte extraction error: ${error instanceof Error ? error.message : String(error)}`,
  2160. severity: 'error',
  2161. });
  2162. }
  2163. return {
  2164. nodes: this.nodes,
  2165. edges: this.edges,
  2166. unresolvedReferences: this.unresolvedReferences,
  2167. errors: this.errors,
  2168. durationMs: Date.now() - startTime,
  2169. };
  2170. }
  2171. /**
  2172. * Create a component node for the .svelte file
  2173. */
  2174. private createComponentNode(): Node {
  2175. const lines = this.source.split('\n');
  2176. const fileName = this.filePath.split(/[/\\]/).pop() || this.filePath;
  2177. const componentName = fileName.replace(/\.svelte$/, '');
  2178. const id = generateNodeId(this.filePath, 'component', componentName, 1);
  2179. const node: Node = {
  2180. id,
  2181. kind: 'component',
  2182. name: componentName,
  2183. qualifiedName: `${this.filePath}::${componentName}`,
  2184. filePath: this.filePath,
  2185. language: 'svelte',
  2186. startLine: 1,
  2187. endLine: lines.length,
  2188. startColumn: 0,
  2189. endColumn: lines[lines.length - 1]?.length || 0,
  2190. isExported: true, // Svelte components are always importable
  2191. updatedAt: Date.now(),
  2192. };
  2193. this.nodes.push(node);
  2194. return node;
  2195. }
  2196. /**
  2197. * Extract <script> blocks from the Svelte source
  2198. */
  2199. private extractScriptBlocks(): Array<{
  2200. content: string;
  2201. startLine: number;
  2202. isModule: boolean;
  2203. isTypeScript: boolean;
  2204. }> {
  2205. const blocks: Array<{
  2206. content: string;
  2207. startLine: number;
  2208. isModule: boolean;
  2209. isTypeScript: boolean;
  2210. }> = [];
  2211. const scriptRegex = /<script(\s[^>]*)?>(?<content>[\s\S]*?)<\/script>/g;
  2212. let match;
  2213. while ((match = scriptRegex.exec(this.source)) !== null) {
  2214. const attrs = match[1] || '';
  2215. const content = match.groups?.content || match[2] || '';
  2216. // Detect TypeScript from lang attribute
  2217. const isTypeScript = /lang\s*=\s*["'](ts|typescript)["']/.test(attrs);
  2218. // Detect module script
  2219. const isModule = /context\s*=\s*["']module["']/.test(attrs);
  2220. // Calculate start line of the script content (line after <script>)
  2221. const beforeScript = this.source.substring(0, match.index);
  2222. const scriptTagLine = (beforeScript.match(/\n/g) || []).length;
  2223. // The content starts on the line after the opening <script> tag
  2224. const openingTag = match[0].substring(0, match[0].indexOf('>') + 1);
  2225. const openingTagLines = (openingTag.match(/\n/g) || []).length;
  2226. const contentStartLine = scriptTagLine + openingTagLines + 1; // 0-indexed line
  2227. blocks.push({
  2228. content,
  2229. startLine: contentStartLine,
  2230. isModule,
  2231. isTypeScript,
  2232. });
  2233. }
  2234. return blocks;
  2235. }
  2236. /**
  2237. * Process a script block by delegating to TreeSitterExtractor
  2238. */
  2239. private processScriptBlock(
  2240. block: { content: string; startLine: number; isModule: boolean; isTypeScript: boolean },
  2241. componentNodeId: string
  2242. ): void {
  2243. const scriptLanguage: Language = block.isTypeScript ? 'typescript' : 'javascript';
  2244. // Check if the script language parser is available
  2245. if (!isLanguageSupported(scriptLanguage)) {
  2246. this.errors.push({
  2247. message: `Parser for ${scriptLanguage} not available, cannot parse Svelte script block`,
  2248. severity: 'warning',
  2249. });
  2250. return;
  2251. }
  2252. // Delegate to TreeSitterExtractor
  2253. const extractor = new TreeSitterExtractor(this.filePath, block.content, scriptLanguage);
  2254. const result = extractor.extract();
  2255. // Offset line numbers from script block back to .svelte file positions
  2256. for (const node of result.nodes) {
  2257. node.startLine += block.startLine;
  2258. node.endLine += block.startLine;
  2259. node.language = 'svelte'; // Mark as svelte, not TS/JS
  2260. this.nodes.push(node);
  2261. // Add containment edge from component to this node
  2262. this.edges.push({
  2263. source: componentNodeId,
  2264. target: node.id,
  2265. kind: 'contains',
  2266. });
  2267. }
  2268. // Offset edges (they reference line numbers)
  2269. for (const edge of result.edges) {
  2270. if (edge.line) {
  2271. edge.line += block.startLine;
  2272. }
  2273. this.edges.push(edge);
  2274. }
  2275. // Offset unresolved references
  2276. for (const ref of result.unresolvedReferences) {
  2277. ref.line += block.startLine;
  2278. ref.filePath = this.filePath;
  2279. ref.language = 'svelte';
  2280. this.unresolvedReferences.push(ref);
  2281. }
  2282. // Carry over errors
  2283. for (const error of result.errors) {
  2284. if (error.line) {
  2285. error.line += block.startLine;
  2286. }
  2287. this.errors.push(error);
  2288. }
  2289. }
  2290. }
  2291. /**
  2292. * Extract nodes and edges from source code
  2293. */
  2294. export function extractFromSource(
  2295. filePath: string,
  2296. source: string,
  2297. language?: Language
  2298. ): ExtractionResult {
  2299. const detectedLanguage = language || detectLanguage(filePath);
  2300. // Use custom extractor for Svelte
  2301. if (detectedLanguage === 'svelte') {
  2302. const extractor = new SvelteExtractor(filePath, source);
  2303. return extractor.extract();
  2304. }
  2305. // Use custom extractor for Liquid
  2306. if (detectedLanguage === 'liquid') {
  2307. const extractor = new LiquidExtractor(filePath, source);
  2308. return extractor.extract();
  2309. }
  2310. const extractor = new TreeSitterExtractor(filePath, source, detectedLanguage);
  2311. return extractor.extract();
  2312. }