tree-sitter.ts 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620
  1. /**
  2. * Tree-sitter Parser Wrapper
  3. *
  4. * Handles parsing source code and extracting structural information.
  5. */
  6. import { Node as SyntaxNode, Tree } from 'web-tree-sitter';
  7. import * as path from 'path';
  8. import {
  9. Language,
  10. Node,
  11. Edge,
  12. NodeKind,
  13. ExtractionResult,
  14. ExtractionError,
  15. UnresolvedReference,
  16. } from '../types';
  17. import { getParser, detectLanguage, isLanguageSupported } from './grammars';
  18. import { generateNodeId, getNodeText, getChildByField, getPrecedingDocstring } from './tree-sitter-helpers';
  19. import type { LanguageExtractor, ExtractorContext } from './tree-sitter-types';
  20. import { EXTRACTORS } from './languages';
  21. import { LiquidExtractor } from './liquid-extractor';
  22. import { SvelteExtractor } from './svelte-extractor';
  23. import { DfmExtractor } from './dfm-extractor';
  24. import { VueExtractor } from './vue-extractor';
  25. import {
  26. getAllFrameworkResolvers,
  27. getApplicableFrameworks,
  28. } from '../resolution/frameworks';
  29. // Re-export for backward compatibility
  30. export { generateNodeId } from './tree-sitter-helpers';
  31. /**
  32. * Extract the name from a node based on language
  33. */
  34. function extractName(node: SyntaxNode, source: string, extractor: LanguageExtractor): string {
  35. // Try field name first
  36. const nameNode = getChildByField(node, extractor.nameField);
  37. if (nameNode) {
  38. // Unwrap pointer_declarator(s) for C/C++ pointer return types
  39. let resolved = nameNode;
  40. while (resolved.type === 'pointer_declarator') {
  41. const inner = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
  42. if (!inner) break;
  43. resolved = inner;
  44. }
  45. // Handle complex declarators (C/C++)
  46. if (resolved.type === 'function_declarator' || resolved.type === 'declarator') {
  47. const innerName = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
  48. return innerName ? getNodeText(innerName, source) : getNodeText(resolved, source);
  49. }
  50. // Lua: `function t.f()` / `function t:m()` — the name node is a dot/method
  51. // index expression; the simple name is the trailing field/method (the table
  52. // receiver is captured separately via getReceiverType).
  53. if (resolved.type === 'dot_index_expression') {
  54. const field = getChildByField(resolved, 'field');
  55. if (field) return getNodeText(field, source);
  56. }
  57. if (resolved.type === 'method_index_expression') {
  58. const method = getChildByField(resolved, 'method');
  59. if (method) return getNodeText(method, source);
  60. }
  61. return getNodeText(resolved, source);
  62. }
  63. // For Dart method_signature, look inside inner signature types
  64. if (node.type === 'method_signature') {
  65. for (let i = 0; i < node.namedChildCount; i++) {
  66. const child = node.namedChild(i);
  67. if (child && (
  68. child.type === 'function_signature' ||
  69. child.type === 'getter_signature' ||
  70. child.type === 'setter_signature' ||
  71. child.type === 'constructor_signature' ||
  72. child.type === 'factory_constructor_signature'
  73. )) {
  74. // Find identifier inside the inner signature
  75. for (let j = 0; j < child.namedChildCount; j++) {
  76. const inner = child.namedChild(j);
  77. if (inner?.type === 'identifier') {
  78. return getNodeText(inner, source);
  79. }
  80. }
  81. }
  82. }
  83. }
  84. // Arrow/function expressions get their name from the parent variable_declarator,
  85. // not from identifiers in their body. Without this, single-expression arrow
  86. // functions like `const fn = () => someIdentifier` get named "someIdentifier"
  87. // instead of "fn", because the fallback below finds the body identifier.
  88. if (node.type === 'arrow_function' || node.type === 'function_expression') {
  89. return '<anonymous>';
  90. }
  91. // Fall back to first identifier child
  92. for (let i = 0; i < node.namedChildCount; i++) {
  93. const child = node.namedChild(i);
  94. if (
  95. child &&
  96. (child.type === 'identifier' ||
  97. child.type === 'type_identifier' ||
  98. child.type === 'simple_identifier' ||
  99. child.type === 'constant')
  100. ) {
  101. return getNodeText(child, source);
  102. }
  103. }
  104. return '<anonymous>';
  105. }
  106. /**
  107. * Tree-sitter node kinds that represent constructor invocations
  108. * (`new Foo()` and friends). Used by extractInstantiation to emit
  109. * an `instantiates` reference targeting the class name.
  110. */
  111. const INSTANTIATION_KINDS: ReadonlySet<string> = new Set([
  112. 'new_expression', // typescript / javascript / tsx / jsx
  113. 'object_creation_expression', // java / c#
  114. 'instance_creation_expression', // some grammars
  115. ]);
  116. /**
  117. * TreeSitterExtractor - Main extraction class
  118. */
  119. export class TreeSitterExtractor {
  120. private filePath: string;
  121. private language: Language;
  122. private source: string;
  123. private tree: Tree | null = null;
  124. private nodes: Node[] = [];
  125. private edges: Edge[] = [];
  126. private unresolvedReferences: UnresolvedReference[] = [];
  127. private errors: ExtractionError[] = [];
  128. private extractor: LanguageExtractor | null = null;
  129. private nodeStack: string[] = []; // Stack of parent node IDs
  130. private methodIndex: Map<string, string> | null = null; // lookup key → node ID for Pascal defProc lookup
  131. constructor(filePath: string, source: string, language?: Language) {
  132. this.filePath = filePath;
  133. this.source = source;
  134. this.language = language || detectLanguage(filePath, source);
  135. this.extractor = EXTRACTORS[this.language] || null;
  136. }
  137. /**
  138. * Parse and extract from the source code
  139. */
  140. extract(): ExtractionResult {
  141. const startTime = Date.now();
  142. if (!isLanguageSupported(this.language)) {
  143. return {
  144. nodes: [],
  145. edges: [],
  146. unresolvedReferences: [],
  147. errors: [
  148. {
  149. message: `Unsupported language: ${this.language}`,
  150. filePath: this.filePath,
  151. severity: 'error',
  152. code: 'unsupported_language',
  153. },
  154. ],
  155. durationMs: Date.now() - startTime,
  156. };
  157. }
  158. const parser = getParser(this.language);
  159. if (!parser) {
  160. return {
  161. nodes: [],
  162. edges: [],
  163. unresolvedReferences: [],
  164. errors: [
  165. {
  166. message: `Failed to get parser for language: ${this.language}`,
  167. filePath: this.filePath,
  168. severity: 'error',
  169. code: 'parser_error',
  170. },
  171. ],
  172. durationMs: Date.now() - startTime,
  173. };
  174. }
  175. try {
  176. this.tree = parser.parse(this.source) ?? null;
  177. if (!this.tree) {
  178. throw new Error('Parser returned null tree');
  179. }
  180. // Create file node representing the source file
  181. const fileNode: Node = {
  182. id: `file:${this.filePath}`,
  183. kind: 'file',
  184. name: path.basename(this.filePath),
  185. qualifiedName: this.filePath,
  186. filePath: this.filePath,
  187. language: this.language,
  188. startLine: 1,
  189. endLine: this.source.split('\n').length,
  190. startColumn: 0,
  191. endColumn: 0,
  192. isExported: false,
  193. updatedAt: Date.now(),
  194. };
  195. this.nodes.push(fileNode);
  196. // Push file node onto stack so top-level declarations get contains edges
  197. this.nodeStack.push(fileNode.id);
  198. this.visitNode(this.tree.rootNode);
  199. this.nodeStack.pop();
  200. } catch (error) {
  201. const msg = error instanceof Error ? error.message : String(error);
  202. // WASM memory errors leave the module in a corrupted state — all subsequent
  203. // parses would also fail. Re-throw so the worker can detect and crash,
  204. // forcing a clean restart with a fresh heap.
  205. if (msg.includes('memory access out of bounds') || msg.includes('out of memory')) {
  206. throw error;
  207. }
  208. this.errors.push({
  209. message: `Parse error: ${msg}`,
  210. filePath: this.filePath,
  211. severity: 'error',
  212. code: 'parse_error',
  213. });
  214. } finally {
  215. // Free tree-sitter WASM memory immediately — trees hold native heap memory
  216. // invisible to V8's GC that accumulates across thousands of files.
  217. if (this.tree) {
  218. this.tree.delete();
  219. this.tree = null;
  220. }
  221. // Release source string to reduce GC pressure
  222. this.source = '';
  223. }
  224. return {
  225. nodes: this.nodes,
  226. edges: this.edges,
  227. unresolvedReferences: this.unresolvedReferences,
  228. errors: this.errors,
  229. durationMs: Date.now() - startTime,
  230. };
  231. }
  232. /**
  233. * Visit a node and extract information
  234. */
  235. private visitNode(node: SyntaxNode): void {
  236. if (!this.extractor) return;
  237. const nodeType = node.type;
  238. let skipChildren = false;
  239. // Language-specific custom visitor hook
  240. if (this.extractor.visitNode) {
  241. const ctx = this.makeExtractorContext();
  242. const handled = this.extractor.visitNode(node, ctx);
  243. if (handled) return;
  244. }
  245. // Pascal-specific AST handling
  246. if (this.language === 'pascal') {
  247. skipChildren = this.visitPascalNode(node);
  248. if (skipChildren) return;
  249. }
  250. // Check for function declarations
  251. // For Python/Ruby, function_definition inside a class should be treated as method
  252. if (this.extractor.functionTypes.includes(nodeType)) {
  253. if (this.isInsideClassLikeNode() && this.extractor.methodTypes.includes(nodeType)) {
  254. // Inside a class - treat as method
  255. this.extractMethod(node);
  256. skipChildren = true; // extractMethod visits children via visitFunctionBody
  257. } else {
  258. this.extractFunction(node);
  259. skipChildren = true; // extractFunction visits children via visitFunctionBody
  260. }
  261. }
  262. // Check for class declarations
  263. else if (this.extractor.classTypes.includes(nodeType)) {
  264. // Some languages reuse class_declaration for structs/enums (e.g. Swift)
  265. const classification = this.extractor.classifyClassNode?.(node) ?? 'class';
  266. if (classification === 'struct') {
  267. this.extractStruct(node);
  268. } else if (classification === 'enum') {
  269. this.extractEnum(node);
  270. } else if (classification === 'interface') {
  271. this.extractInterface(node);
  272. } else if (classification === 'trait') {
  273. this.extractClass(node, 'trait');
  274. } else {
  275. this.extractClass(node);
  276. }
  277. skipChildren = true; // extractClass visits body children
  278. }
  279. // Extra class node types (e.g. Dart mixin_declaration, extension_declaration)
  280. else if (this.extractor.extraClassNodeTypes?.includes(nodeType)) {
  281. this.extractClass(node);
  282. skipChildren = true;
  283. }
  284. // Check for method declarations (only if not already handled by functionTypes)
  285. else if (this.extractor.methodTypes.includes(nodeType)) {
  286. this.extractMethod(node);
  287. skipChildren = true; // extractMethod visits children via visitFunctionBody
  288. }
  289. // Check for interface/protocol/trait declarations
  290. else if (this.extractor.interfaceTypes.includes(nodeType)) {
  291. this.extractInterface(node);
  292. skipChildren = true; // extractInterface visits body children
  293. }
  294. // Check for struct declarations
  295. else if (this.extractor.structTypes.includes(nodeType)) {
  296. this.extractStruct(node);
  297. skipChildren = true; // extractStruct visits body children
  298. }
  299. // Check for enum declarations
  300. else if (this.extractor.enumTypes.includes(nodeType)) {
  301. this.extractEnum(node);
  302. skipChildren = true; // extractEnum visits body children
  303. }
  304. // Check for type alias declarations (e.g. `type X = ...` in TypeScript)
  305. // For Go, type_spec wraps struct/interface definitions — resolveTypeAliasKind
  306. // detects these and extractTypeAlias creates the correct node kind.
  307. else if (this.extractor.typeAliasTypes.includes(nodeType)) {
  308. skipChildren = this.extractTypeAlias(node);
  309. }
  310. // Check for class properties (e.g. C# property_declaration)
  311. else if (this.extractor.propertyTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
  312. this.extractProperty(node);
  313. skipChildren = true;
  314. }
  315. // Check for class fields (e.g. Java field_declaration, C# field_declaration)
  316. else if (this.extractor.fieldTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
  317. this.extractField(node);
  318. skipChildren = true;
  319. }
  320. // Check for variable declarations (const, let, var, etc.)
  321. // Only extract top-level variables (not inside functions/methods)
  322. else if (this.extractor.variableTypes.includes(nodeType) && !this.isInsideClassLikeNode()) {
  323. this.extractVariable(node);
  324. skipChildren = true; // extractVariable handles children
  325. }
  326. // `export_statement` itself is not extracted — the walker descends
  327. // into children, where the inner declaration (lexical_declaration,
  328. // function_declaration, class_declaration, etc.) is dispatched to
  329. // its own extractor. `isExported` walks the parent chain, so the
  330. // exported flag is preserved automatically.
  331. //
  332. // Calling extractExportedVariables here AND descending caused every
  333. // `export const X = ...` to produce two nodes for the same symbol —
  334. // one kind:'variable' from extractExportedVariables and one
  335. // kind:'constant' from extractVariable. The dedicated dispatch is
  336. // the correct one (it picks kind from isConst, captures the
  337. // initializer signature, and walks type annotations); the
  338. // export-statement helper was redundant.
  339. // Check for imports
  340. else if (this.extractor.importTypes.includes(nodeType)) {
  341. this.extractImport(node);
  342. }
  343. // Check for function calls
  344. else if (this.extractor.callTypes.includes(nodeType)) {
  345. this.extractCall(node);
  346. }
  347. // `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  348. // produce an `instantiates` reference. Children still walked so
  349. // nested calls inside the constructor args (`new Foo(bar())`) get
  350. // their own `calls` refs.
  351. else if (INSTANTIATION_KINDS.has(nodeType)) {
  352. this.extractInstantiation(node);
  353. }
  354. // (Decorator handling lives inside the symbol-creating extractors
  355. // — extractClass / extractFunction / extractProperty — because the
  356. // decorator node sits BEFORE the symbol in the AST and the walker
  357. // would otherwise see the wrong nodeStack head.)
  358. // Rust: `impl Trait for Type { ... }` — creates implements edge from Type to Trait
  359. else if (nodeType === 'impl_item') {
  360. this.extractRustImplItem(node);
  361. }
  362. // Visit children (unless the extract method already visited them)
  363. if (!skipChildren) {
  364. for (let i = 0; i < node.namedChildCount; i++) {
  365. const child = node.namedChild(i);
  366. if (child) {
  367. this.visitNode(child);
  368. }
  369. }
  370. }
  371. }
  372. /**
  373. * Create a Node object
  374. */
  375. private createNode(
  376. kind: NodeKind,
  377. name: string,
  378. node: SyntaxNode,
  379. extra?: Partial<Node>
  380. ): Node | null {
  381. // Skip nodes with empty/missing names — they are not meaningful symbols
  382. // and would cause FK violations when edges reference them (see issue #42)
  383. if (!name) {
  384. return null;
  385. }
  386. const id = generateNodeId(this.filePath, kind, name, node.startPosition.row + 1);
  387. const newNode: Node = {
  388. id,
  389. kind,
  390. name,
  391. qualifiedName: this.buildQualifiedName(name),
  392. filePath: this.filePath,
  393. language: this.language,
  394. startLine: node.startPosition.row + 1,
  395. endLine: node.endPosition.row + 1,
  396. startColumn: node.startPosition.column,
  397. endColumn: node.endPosition.column,
  398. updatedAt: Date.now(),
  399. ...extra,
  400. };
  401. this.nodes.push(newNode);
  402. // Add containment edge from parent
  403. if (this.nodeStack.length > 0) {
  404. const parentId = this.nodeStack[this.nodeStack.length - 1];
  405. if (parentId) {
  406. this.edges.push({
  407. source: parentId,
  408. target: id,
  409. kind: 'contains',
  410. });
  411. }
  412. }
  413. return newNode;
  414. }
  415. /**
  416. * Find first named child whose type is in the given list.
  417. * Used to locate inner type nodes (e.g. enum_specifier inside a typedef).
  418. */
  419. private findChildByTypes(node: SyntaxNode, types: string[]): SyntaxNode | null {
  420. for (let i = 0; i < node.namedChildCount; i++) {
  421. const child = node.namedChild(i);
  422. if (child && types.includes(child.type)) return child;
  423. }
  424. return null;
  425. }
  426. /**
  427. * Build qualified name from node stack
  428. */
  429. private buildQualifiedName(name: string): string {
  430. // Build a qualified name from the semantic hierarchy only (no file path).
  431. // The file path is stored separately in filePath and pollutes FTS if included here.
  432. const parts: string[] = [];
  433. for (const nodeId of this.nodeStack) {
  434. const node = this.nodes.find((n) => n.id === nodeId);
  435. if (node && node.kind !== 'file') {
  436. parts.push(node.name);
  437. }
  438. }
  439. parts.push(name);
  440. return parts.join('::');
  441. }
  442. /**
  443. * Build an ExtractorContext for passing to language-specific visitNode hooks.
  444. */
  445. private makeExtractorContext(): ExtractorContext {
  446. // eslint-disable-next-line @typescript-eslint/no-this-alias
  447. const self = this;
  448. return {
  449. createNode: (kind, name, node, extra) => self.createNode(kind, name, node, extra),
  450. visitNode: (node) => self.visitNode(node),
  451. visitFunctionBody: (body, functionId) => self.visitFunctionBody(body, functionId),
  452. addUnresolvedReference: (ref) => self.unresolvedReferences.push(ref),
  453. pushScope: (nodeId) => self.nodeStack.push(nodeId),
  454. popScope: () => self.nodeStack.pop(),
  455. get filePath() { return self.filePath; },
  456. get source() { return self.source; },
  457. get nodeStack() { return self.nodeStack; },
  458. get nodes() { return self.nodes; },
  459. };
  460. }
  461. /**
  462. * Check if the current node stack indicates we are inside a class-like node
  463. * (class, struct, interface, trait). File nodes do not count as class-like.
  464. */
  465. private isInsideClassLikeNode(): boolean {
  466. if (this.nodeStack.length === 0) return false;
  467. const parentId = this.nodeStack[this.nodeStack.length - 1];
  468. if (!parentId) return false;
  469. const parentNode = this.nodes.find((n) => n.id === parentId);
  470. if (!parentNode) return false;
  471. return (
  472. parentNode.kind === 'class' ||
  473. parentNode.kind === 'struct' ||
  474. parentNode.kind === 'interface' ||
  475. parentNode.kind === 'trait' ||
  476. parentNode.kind === 'enum' ||
  477. parentNode.kind === 'module'
  478. );
  479. }
  480. /**
  481. * Extract a function
  482. */
  483. private extractFunction(node: SyntaxNode, nameOverride?: string): void {
  484. if (!this.extractor) return;
  485. // If the language provides getReceiverType and this function has a receiver
  486. // (e.g., Rust function_item inside an impl block), extract as method instead
  487. if (this.extractor.getReceiverType?.(node, this.source)) {
  488. this.extractMethod(node);
  489. return;
  490. }
  491. // nameOverride is supplied only for explicitly-named anonymous functions the
  492. // caller resolved itself (e.g. arrow values of exported-const object members
  493. // — SvelteKit actions). Inline-object arrows reached by the general walker
  494. // get no override, so they still fall through to the <anonymous> skip below.
  495. let name = nameOverride ?? extractName(node, this.source, this.extractor);
  496. // For arrow functions and function expressions assigned to variables,
  497. // resolve the name from the parent variable_declarator.
  498. // e.g. `export const useAuth = () => { ... }` — the arrow_function node
  499. // has no `name` field; the name lives on the variable_declarator.
  500. if (
  501. !nameOverride &&
  502. name === '<anonymous>' &&
  503. (node.type === 'arrow_function' || node.type === 'function_expression')
  504. ) {
  505. const parent = node.parent;
  506. if (parent?.type === 'variable_declarator') {
  507. const varName = getChildByField(parent, 'name');
  508. if (varName) {
  509. name = getNodeText(varName, this.source);
  510. }
  511. }
  512. }
  513. if (name === '<anonymous>') return; // Skip anonymous functions
  514. // Check for misparse artifacts (e.g. C++ macros causing "namespace detail" functions)
  515. // Skip the node but still visit the body for calls and structural nodes
  516. if (this.extractor.isMisparsedFunction?.(name, node)) {
  517. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  518. ?? getChildByField(node, this.extractor.bodyField);
  519. if (body) {
  520. this.visitFunctionBody(body, '');
  521. }
  522. return;
  523. }
  524. const docstring = getPrecedingDocstring(node, this.source);
  525. const signature = this.extractor.getSignature?.(node, this.source);
  526. const visibility = this.extractor.getVisibility?.(node);
  527. const isExported = this.extractor.isExported?.(node, this.source);
  528. const isAsync = this.extractor.isAsync?.(node);
  529. const isStatic = this.extractor.isStatic?.(node);
  530. const funcNode = this.createNode('function', name, node, {
  531. docstring,
  532. signature,
  533. visibility,
  534. isExported,
  535. isAsync,
  536. isStatic,
  537. });
  538. if (!funcNode) return;
  539. // Extract type annotations (parameter types and return type)
  540. this.extractTypeAnnotations(node, funcNode.id);
  541. // Extract decorators applied to the function (rare in JS/TS but
  542. // present in Python `@decorator def f():` and Java/Kotlin
  543. // annotations on free functions).
  544. this.extractDecoratorsFor(node, funcNode.id);
  545. // Push to stack and visit body
  546. this.nodeStack.push(funcNode.id);
  547. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  548. ?? getChildByField(node, this.extractor.bodyField);
  549. if (body) {
  550. this.visitFunctionBody(body, funcNode.id);
  551. }
  552. this.nodeStack.pop();
  553. }
  554. /**
  555. * Extract a class
  556. */
  557. private extractClass(node: SyntaxNode, kind: NodeKind = 'class'): void {
  558. if (!this.extractor) return;
  559. const name = extractName(node, this.source, this.extractor);
  560. const docstring = getPrecedingDocstring(node, this.source);
  561. const visibility = this.extractor.getVisibility?.(node);
  562. const isExported = this.extractor.isExported?.(node, this.source);
  563. const classNode = this.createNode(kind, name, node, {
  564. docstring,
  565. visibility,
  566. isExported,
  567. });
  568. if (!classNode) return;
  569. // Extract extends/implements
  570. this.extractInheritance(node, classNode.id);
  571. // Extract decorators applied to the class (`@Foo class X {}`).
  572. this.extractDecoratorsFor(node, classNode.id);
  573. // Push to stack and visit body
  574. this.nodeStack.push(classNode.id);
  575. let body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  576. ?? getChildByField(node, this.extractor.bodyField);
  577. if (!body) body = node;
  578. // Visit all children for methods and properties
  579. for (let i = 0; i < body.namedChildCount; i++) {
  580. const child = body.namedChild(i);
  581. if (child) {
  582. this.visitNode(child);
  583. }
  584. }
  585. this.nodeStack.pop();
  586. }
  587. /**
  588. * Extract a method
  589. */
  590. private extractMethod(node: SyntaxNode): void {
  591. if (!this.extractor) return;
  592. // For languages with receiver types (Go, Rust), include receiver in qualified name
  593. // so FTS can match "scrapeLoop.run" → qualified_name "...::scrapeLoop::run"
  594. const receiverType = this.extractor.getReceiverType?.(node, this.source);
  595. // For most languages, only extract as method if inside a class-like node
  596. // Languages with methodsAreTopLevel (e.g. Go) always treat them as methods
  597. // Languages with getReceiverType (e.g. Rust) extract as method when receiver is found
  598. if (!this.isInsideClassLikeNode() && !this.extractor.methodsAreTopLevel && !receiverType) {
  599. // Skip method_definition nodes inside object literals (getters/setters/methods
  600. // in inline objects). These are ephemeral and create noise (e.g., Svelte context
  601. // objects: `ctx.set({ get view() { ... } })`).
  602. if (node.parent?.type === 'object' || node.parent?.type === 'object_expression') {
  603. return;
  604. }
  605. // Not inside a class-like node and no receiver type, treat as function
  606. this.extractFunction(node);
  607. return;
  608. }
  609. const name = extractName(node, this.source, this.extractor);
  610. // Check for misparse artifacts (e.g. C++ "switch" inside macro-confused class body)
  611. if (this.extractor.isMisparsedFunction?.(name, node)) {
  612. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  613. ?? getChildByField(node, this.extractor.bodyField);
  614. if (body) {
  615. this.visitFunctionBody(body, '');
  616. }
  617. return;
  618. }
  619. const docstring = getPrecedingDocstring(node, this.source);
  620. const signature = this.extractor.getSignature?.(node, this.source);
  621. const visibility = this.extractor.getVisibility?.(node);
  622. const isAsync = this.extractor.isAsync?.(node);
  623. const isStatic = this.extractor.isStatic?.(node);
  624. const extraProps: Partial<Node> = {
  625. docstring,
  626. signature,
  627. visibility,
  628. isAsync,
  629. isStatic,
  630. };
  631. if (receiverType) {
  632. extraProps.qualifiedName = `${receiverType}::${name}`;
  633. }
  634. const methodNode = this.createNode('method', name, node, extraProps);
  635. if (!methodNode) return;
  636. // For methods with a receiver type but no class-like parent on the stack
  637. // (e.g., Rust impl blocks), add a contains edge from the owning struct/trait
  638. if (receiverType && !this.isInsideClassLikeNode()) {
  639. const ownerNode = this.nodes.find(
  640. (n) =>
  641. n.name === receiverType &&
  642. n.filePath === this.filePath &&
  643. (n.kind === 'struct' || n.kind === 'class' || n.kind === 'enum' || n.kind === 'trait')
  644. );
  645. if (ownerNode) {
  646. this.edges.push({
  647. source: ownerNode.id,
  648. target: methodNode.id,
  649. kind: 'contains',
  650. });
  651. }
  652. }
  653. // Extract type annotations (parameter types and return type)
  654. this.extractTypeAnnotations(node, methodNode.id);
  655. // Extract decorators (`@Get('/list') list() {}`).
  656. this.extractDecoratorsFor(node, methodNode.id);
  657. // Push to stack and visit body
  658. this.nodeStack.push(methodNode.id);
  659. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  660. ?? getChildByField(node, this.extractor.bodyField);
  661. if (body) {
  662. this.visitFunctionBody(body, methodNode.id);
  663. }
  664. this.nodeStack.pop();
  665. }
  666. /**
  667. * Extract an interface/protocol/trait
  668. */
  669. private extractInterface(node: SyntaxNode): void {
  670. if (!this.extractor) return;
  671. const name = extractName(node, this.source, this.extractor);
  672. const docstring = getPrecedingDocstring(node, this.source);
  673. const isExported = this.extractor.isExported?.(node, this.source);
  674. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  675. const interfaceNode = this.createNode(kind, name, node, {
  676. docstring,
  677. isExported,
  678. });
  679. if (!interfaceNode) return;
  680. // Extract extends (interface inheritance)
  681. this.extractInheritance(node, interfaceNode.id);
  682. // Visit body children for interface methods and nested types
  683. this.nodeStack.push(interfaceNode.id);
  684. let body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  685. ?? getChildByField(node, this.extractor.bodyField);
  686. if (!body) body = node;
  687. for (let i = 0; i < body.namedChildCount; i++) {
  688. const child = body.namedChild(i);
  689. if (child) {
  690. this.visitNode(child);
  691. }
  692. }
  693. this.nodeStack.pop();
  694. }
  695. /**
  696. * Extract a struct
  697. */
  698. private extractStruct(node: SyntaxNode): void {
  699. if (!this.extractor) return;
  700. // Skip forward declarations and type references (no body = not a definition)
  701. const body = getChildByField(node, this.extractor.bodyField);
  702. if (!body) return;
  703. const name = extractName(node, this.source, this.extractor);
  704. const docstring = getPrecedingDocstring(node, this.source);
  705. const visibility = this.extractor.getVisibility?.(node);
  706. const isExported = this.extractor.isExported?.(node, this.source);
  707. const structNode = this.createNode('struct', name, node, {
  708. docstring,
  709. visibility,
  710. isExported,
  711. });
  712. if (!structNode) return;
  713. // Extract inheritance (e.g. Swift: struct HTTPMethod: RawRepresentable)
  714. this.extractInheritance(node, structNode.id);
  715. // Push to stack for field extraction
  716. this.nodeStack.push(structNode.id);
  717. for (let i = 0; i < body.namedChildCount; i++) {
  718. const child = body.namedChild(i);
  719. if (child) {
  720. this.visitNode(child);
  721. }
  722. }
  723. this.nodeStack.pop();
  724. }
  725. /**
  726. * Extract an enum
  727. */
  728. private extractEnum(node: SyntaxNode): void {
  729. if (!this.extractor) return;
  730. // Skip forward declarations and type references (no body = not a definition)
  731. const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
  732. ?? getChildByField(node, this.extractor.bodyField);
  733. if (!body) return;
  734. const name = extractName(node, this.source, this.extractor);
  735. const docstring = getPrecedingDocstring(node, this.source);
  736. const visibility = this.extractor.getVisibility?.(node);
  737. const isExported = this.extractor.isExported?.(node, this.source);
  738. const enumNode = this.createNode('enum', name, node, {
  739. docstring,
  740. visibility,
  741. isExported,
  742. });
  743. if (!enumNode) return;
  744. // Extract inheritance (e.g. Swift: enum AFError: Error)
  745. this.extractInheritance(node, enumNode.id);
  746. // Push to stack and visit body children (enum members, nested types, methods)
  747. this.nodeStack.push(enumNode.id);
  748. const memberTypes = this.extractor.enumMemberTypes;
  749. for (let i = 0; i < body.namedChildCount; i++) {
  750. const child = body.namedChild(i);
  751. if (!child) continue;
  752. if (memberTypes?.includes(child.type)) {
  753. this.extractEnumMembers(child);
  754. } else {
  755. this.visitNode(child);
  756. }
  757. }
  758. this.nodeStack.pop();
  759. }
  760. /**
  761. * Extract enum member names from an enum member node.
  762. * Handles multi-case declarations (Swift: `case put, delete`) and single-case patterns.
  763. */
  764. private extractEnumMembers(node: SyntaxNode): void {
  765. // Try field-based name first (e.g. Rust enum_variant has a 'name' field)
  766. const nameNode = getChildByField(node, 'name');
  767. if (nameNode) {
  768. this.createNode('enum_member', getNodeText(nameNode, this.source), node);
  769. return;
  770. }
  771. // Check for identifier-like children (Swift: simple_identifier, TS: property_identifier)
  772. let found = false;
  773. for (let i = 0; i < node.namedChildCount; i++) {
  774. const child = node.namedChild(i);
  775. if (child && (child.type === 'simple_identifier' || child.type === 'identifier' || child.type === 'property_identifier')) {
  776. this.createNode('enum_member', getNodeText(child, this.source), child);
  777. found = true;
  778. }
  779. }
  780. // If the node itself IS the identifier (e.g. TS property_identifier directly in enum body)
  781. if (!found && node.namedChildCount === 0) {
  782. this.createNode('enum_member', getNodeText(node, this.source), node);
  783. }
  784. }
  785. /**
  786. * Extract a class property declaration (e.g. C# `public string Name { get; set; }`).
  787. * Extracts as 'property' kind node inside the owning class.
  788. */
  789. private extractProperty(node: SyntaxNode): void {
  790. if (!this.extractor) return;
  791. const docstring = getPrecedingDocstring(node, this.source);
  792. const visibility = this.extractor.getVisibility?.(node);
  793. const isStatic = this.extractor.isStatic?.(node) ?? false;
  794. // Property name is a direct identifier child
  795. const nameNode = getChildByField(node, 'name')
  796. || node.namedChildren.find(c => c.type === 'identifier');
  797. if (!nameNode) return;
  798. const name = getNodeText(nameNode, this.source);
  799. // Get property type from the type child (first named child that isn't modifier or identifier)
  800. const typeNode = node.namedChildren.find(
  801. c => c.type !== 'modifier' && c.type !== 'modifiers'
  802. && c.type !== 'identifier' && c.type !== 'accessor_list'
  803. && c.type !== 'accessors' && c.type !== 'equals_value_clause'
  804. );
  805. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  806. const signature = typeText ? `${typeText} ${name}` : name;
  807. const propNode = this.createNode('property', name, node, {
  808. docstring,
  809. signature,
  810. visibility,
  811. isStatic,
  812. });
  813. // `@Inject() private svc: Foo` and similar — capture the
  814. // decorator->target relationship for class properties too.
  815. if (propNode) {
  816. this.extractDecoratorsFor(node, propNode.id);
  817. }
  818. }
  819. /**
  820. * Extract a class field declaration (e.g. Java field_declaration, C# field_declaration).
  821. * Extracts each declarator as a 'field' kind node inside the owning class.
  822. */
  823. private extractField(node: SyntaxNode): void {
  824. if (!this.extractor) return;
  825. const docstring = getPrecedingDocstring(node, this.source);
  826. const visibility = this.extractor.getVisibility?.(node);
  827. const isStatic = this.extractor.isStatic?.(node) ?? false;
  828. // Java field_declaration: "private final String name = value;" → variable_declarator(s) are direct children
  829. // C# field_declaration: wraps in variable_declaration → variable_declarator(s)
  830. let declarators = node.namedChildren.filter(
  831. c => c.type === 'variable_declarator'
  832. );
  833. // C#: look inside variable_declaration wrapper
  834. if (declarators.length === 0) {
  835. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  836. if (varDecl) {
  837. declarators = varDecl.namedChildren.filter(c => c.type === 'variable_declarator');
  838. }
  839. }
  840. // PHP property_declaration: property_element → variable_name → name
  841. if (declarators.length === 0) {
  842. const propElements = node.namedChildren.filter(c => c.type === 'property_element');
  843. if (propElements.length > 0) {
  844. // Get type annotation if present (e.g. "string", "int", "?Foo")
  845. const typeNode = node.namedChildren.find(
  846. c => c.type !== 'visibility_modifier' && c.type !== 'static_modifier'
  847. && c.type !== 'readonly_modifier' && c.type !== 'property_element'
  848. && c.type !== 'var_modifier'
  849. );
  850. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  851. for (const elem of propElements) {
  852. const varName = elem.namedChildren.find(c => c.type === 'variable_name');
  853. const nameNode = varName?.namedChildren.find(c => c.type === 'name');
  854. if (!nameNode) continue;
  855. const name = getNodeText(nameNode, this.source);
  856. const signature = typeText ? `${typeText} $${name}` : `$${name}`;
  857. this.createNode('field', name, elem, {
  858. docstring,
  859. signature,
  860. visibility,
  861. isStatic,
  862. });
  863. }
  864. return;
  865. }
  866. }
  867. if (declarators.length > 0) {
  868. // Get field type from the type child
  869. // Java: type is a direct child of field_declaration
  870. // C#: type is inside variable_declaration wrapper
  871. const varDecl = node.namedChildren.find(c => c.type === 'variable_declaration');
  872. const typeSearchNode = varDecl ?? node;
  873. const typeNode = typeSearchNode.namedChildren.find(
  874. c => c.type !== 'modifiers' && c.type !== 'modifier' && c.type !== 'variable_declarator'
  875. && c.type !== 'variable_declaration' && c.type !== 'marker_annotation' && c.type !== 'annotation'
  876. );
  877. const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
  878. for (const decl of declarators) {
  879. const nameNode = getChildByField(decl, 'name')
  880. || decl.namedChildren.find(c => c.type === 'identifier');
  881. if (!nameNode) continue;
  882. const name = getNodeText(nameNode, this.source);
  883. const signature = typeText ? `${typeText} ${name}` : name;
  884. const fieldNode = this.createNode('field', name, decl, {
  885. docstring,
  886. signature,
  887. visibility,
  888. isStatic,
  889. });
  890. // Java/Kotlin annotations / TS field decorators sit on the
  891. // outer field_declaration, not on the individual declarator.
  892. if (fieldNode) this.extractDecoratorsFor(node, fieldNode.id);
  893. }
  894. } else {
  895. // Fallback: try to find an identifier child directly
  896. const nameNode = getChildByField(node, 'name')
  897. || node.namedChildren.find(c => c.type === 'identifier');
  898. if (nameNode) {
  899. const name = getNodeText(nameNode, this.source);
  900. this.createNode('field', name, node, {
  901. docstring,
  902. visibility,
  903. isStatic,
  904. });
  905. }
  906. }
  907. }
  908. /**
  909. * Extract a variable declaration (const, let, var, etc.)
  910. *
  911. * Extracts top-level and module-level variable declarations.
  912. * Captures the variable name and first 100 chars of initializer in signature for searchability.
  913. */
  914. private extractVariable(node: SyntaxNode): void {
  915. if (!this.extractor) return;
  916. // Different languages have different variable declaration structures
  917. // TypeScript/JavaScript: lexical_declaration contains variable_declarator children
  918. // Python: assignment has left (identifier) and right (value)
  919. // Go: var_declaration, short_var_declaration, const_declaration
  920. const isConst = this.extractor.isConst?.(node) ?? false;
  921. const kind: NodeKind = isConst ? 'constant' : 'variable';
  922. const docstring = getPrecedingDocstring(node, this.source);
  923. const isExported = this.extractor.isExported?.(node, this.source) ?? false;
  924. // Extract variable declarators based on language
  925. if (this.language === 'typescript' || this.language === 'javascript' ||
  926. this.language === 'tsx' || this.language === 'jsx') {
  927. // Handle lexical_declaration and variable_declaration
  928. // These contain one or more variable_declarator children
  929. for (let i = 0; i < node.namedChildCount; i++) {
  930. const child = node.namedChild(i);
  931. if (child?.type === 'variable_declarator') {
  932. const nameNode = getChildByField(child, 'name');
  933. const valueNode = getChildByField(child, 'value');
  934. if (nameNode) {
  935. // Skip destructured patterns (e.g., `let { x, y } = $props()` in Svelte)
  936. // These produce ugly multi-line names like "{ class: className }"
  937. if (nameNode.type === 'object_pattern' || nameNode.type === 'array_pattern') {
  938. continue;
  939. }
  940. const name = getNodeText(nameNode, this.source);
  941. // Arrow functions / function expressions: extract as function instead of variable
  942. if (valueNode && (valueNode.type === 'arrow_function' || valueNode.type === 'function_expression')) {
  943. this.extractFunction(valueNode);
  944. continue;
  945. }
  946. // Capture first 100 chars of initializer for context (stored in signature for searchability)
  947. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  948. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  949. const varNode = this.createNode(kind, name, child, {
  950. docstring,
  951. signature: initSignature,
  952. isExported,
  953. });
  954. // Extract type annotation references (e.g., const x: ITextModel = ...)
  955. if (varNode) {
  956. this.extractVariableTypeAnnotation(child, varNode.id);
  957. }
  958. // Exported const object-of-functions: `export const actions =
  959. // { default: async () => {} }` (SvelteKit form actions / handler maps
  960. // / route tables). Extract each function-valued property as a function
  961. // named by its key + walk its body so its calls (e.g. api.post) are
  962. // captured. Scoped to EXPORTED consts to exclude the inline-object
  963. // noise (`ctx.set({...})`) the object-method skip deliberately avoids.
  964. if (isExported && valueNode &&
  965. (valueNode.type === 'object' || valueNode.type === 'object_expression')) {
  966. for (let j = 0; j < valueNode.namedChildCount; j++) {
  967. const pair = valueNode.namedChild(j);
  968. if (pair?.type !== 'pair') continue;
  969. const v = getChildByField(pair, 'value');
  970. const k = getChildByField(pair, 'key');
  971. if (k && v && (v.type === 'arrow_function' || v.type === 'function_expression')) {
  972. this.extractFunction(v, getNodeText(k, this.source).replace(/^['"`]|['"`]$/g, ''));
  973. }
  974. }
  975. }
  976. }
  977. }
  978. }
  979. } else if (this.language === 'python' || this.language === 'ruby') {
  980. // Python/Ruby assignment: left = right
  981. const left = getChildByField(node, 'left') || node.namedChild(0);
  982. const right = getChildByField(node, 'right') || node.namedChild(1);
  983. if (left && left.type === 'identifier') {
  984. const name = getNodeText(left, this.source);
  985. // Skip if name starts with lowercase and looks like a function call result
  986. // Python constants are usually UPPER_CASE
  987. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  988. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  989. this.createNode(kind, name, node, {
  990. docstring,
  991. signature: initSignature,
  992. });
  993. }
  994. } else if (this.language === 'go') {
  995. // Go: var_declaration, short_var_declaration, const_declaration
  996. // These can have multiple identifiers on the left
  997. const specs = node.namedChildren.filter(c =>
  998. c.type === 'var_spec' || c.type === 'const_spec'
  999. );
  1000. for (const spec of specs) {
  1001. const nameNode = spec.namedChild(0);
  1002. if (nameNode && nameNode.type === 'identifier') {
  1003. const name = getNodeText(nameNode, this.source);
  1004. const valueNode = spec.namedChildCount > 1 ? spec.namedChild(spec.namedChildCount - 1) : null;
  1005. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  1006. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1007. this.createNode(node.type === 'const_declaration' ? 'constant' : 'variable', name, spec, {
  1008. docstring,
  1009. signature: initSignature,
  1010. });
  1011. }
  1012. }
  1013. // Handle short_var_declaration (:=)
  1014. if (node.type === 'short_var_declaration') {
  1015. const left = getChildByField(node, 'left');
  1016. const right = getChildByField(node, 'right');
  1017. if (left) {
  1018. // Can be expression_list with multiple identifiers
  1019. const identifiers = left.type === 'expression_list'
  1020. ? left.namedChildren.filter(c => c.type === 'identifier')
  1021. : [left];
  1022. for (const id of identifiers) {
  1023. const name = getNodeText(id, this.source);
  1024. const initValue = right ? getNodeText(right, this.source).slice(0, 100) : undefined;
  1025. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1026. this.createNode('variable', name, node, {
  1027. docstring,
  1028. signature: initSignature,
  1029. });
  1030. }
  1031. }
  1032. }
  1033. } else if (this.language === 'lua' || this.language === 'luau') {
  1034. // Lua/Luau: variable_declaration → assignment_statement → variable_list
  1035. // (name: identifier...) = expression_list. `local x, y = 1, 2`
  1036. // declares multiple names; only plain identifiers are locals.
  1037. const assign = node.namedChildren.find((c) => c.type === 'assignment_statement') ?? node;
  1038. const varList = assign.namedChildren.find((c) => c.type === 'variable_list');
  1039. const exprList = assign.namedChildren.find((c) => c.type === 'expression_list');
  1040. const values = exprList ? exprList.namedChildren : [];
  1041. const names = varList ? varList.namedChildren.filter((c) => c.type === 'identifier') : [];
  1042. names.forEach((nameNode, i) => {
  1043. const name = getNodeText(nameNode, this.source);
  1044. if (!name) return;
  1045. const valueNode = values[i];
  1046. const initValue = valueNode ? getNodeText(valueNode, this.source).slice(0, 100) : undefined;
  1047. const initSignature = initValue ? `= ${initValue}${initValue.length >= 100 ? '...' : ''}` : undefined;
  1048. this.createNode(kind, name, nameNode, { docstring, signature: initSignature, isExported });
  1049. });
  1050. } else {
  1051. // Generic fallback for other languages
  1052. // Try to find identifier children
  1053. for (let i = 0; i < node.namedChildCount; i++) {
  1054. const child = node.namedChild(i);
  1055. if (child?.type === 'identifier' || child?.type === 'variable_declarator') {
  1056. const name = child.type === 'identifier'
  1057. ? getNodeText(child, this.source)
  1058. : extractName(child, this.source, this.extractor);
  1059. if (name && name !== '<anonymous>') {
  1060. this.createNode(kind, name, child, {
  1061. docstring,
  1062. isExported,
  1063. });
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. /**
  1070. * Extract a type alias (e.g. `export type X = ...` in TypeScript).
  1071. * For languages like Go, resolveTypeAliasKind detects when the type_spec
  1072. * wraps a struct or interface definition and creates the correct node kind.
  1073. * Returns true if children should be skipped (struct/interface handled body visiting).
  1074. */
  1075. private extractTypeAlias(node: SyntaxNode): boolean {
  1076. if (!this.extractor) return false;
  1077. const name = extractName(node, this.source, this.extractor);
  1078. if (name === '<anonymous>') return false;
  1079. const docstring = getPrecedingDocstring(node, this.source);
  1080. const isExported = this.extractor.isExported?.(node, this.source);
  1081. // Check if this type alias is actually a struct or interface definition
  1082. // (e.g. Go: `type Foo struct { ... }` is a type_spec wrapping struct_type)
  1083. const resolvedKind = this.extractor.resolveTypeAliasKind?.(node, this.source);
  1084. if (resolvedKind === 'struct') {
  1085. const structNode = this.createNode('struct', name, node, { docstring, isExported });
  1086. if (!structNode) return true;
  1087. // Visit body children for field extraction
  1088. this.nodeStack.push(structNode.id);
  1089. // Try Go-style 'type' field first, then find inner struct child (C typedef struct)
  1090. const typeChild = getChildByField(node, 'type')
  1091. || this.findChildByTypes(node, this.extractor.structTypes);
  1092. if (typeChild) {
  1093. // Extract struct embedding (e.g. Go: `type DB struct { *Head; Queryable }`)
  1094. this.extractInheritance(typeChild, structNode.id);
  1095. const body = getChildByField(typeChild, this.extractor.bodyField) || typeChild;
  1096. for (let i = 0; i < body.namedChildCount; i++) {
  1097. const child = body.namedChild(i);
  1098. if (child) this.visitNode(child);
  1099. }
  1100. }
  1101. this.nodeStack.pop();
  1102. return true;
  1103. }
  1104. if (resolvedKind === 'enum') {
  1105. const enumNode = this.createNode('enum', name, node, { docstring, isExported });
  1106. if (!enumNode) return true;
  1107. this.nodeStack.push(enumNode.id);
  1108. // Find the inner enum type child (e.g. C: typedef enum { ... } name)
  1109. const innerEnum = this.findChildByTypes(node, this.extractor.enumTypes);
  1110. if (innerEnum) {
  1111. this.extractInheritance(innerEnum, enumNode.id);
  1112. const body = this.extractor.resolveBody?.(innerEnum, this.extractor.bodyField)
  1113. ?? getChildByField(innerEnum, this.extractor.bodyField);
  1114. if (body) {
  1115. const memberTypes = this.extractor.enumMemberTypes;
  1116. for (let i = 0; i < body.namedChildCount; i++) {
  1117. const child = body.namedChild(i);
  1118. if (!child) continue;
  1119. if (memberTypes?.includes(child.type)) {
  1120. this.extractEnumMembers(child);
  1121. } else {
  1122. this.visitNode(child);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. this.nodeStack.pop();
  1128. return true;
  1129. }
  1130. if (resolvedKind === 'interface') {
  1131. const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
  1132. const interfaceNode = this.createNode(kind, name, node, { docstring, isExported });
  1133. if (!interfaceNode) return true;
  1134. // Extract interface inheritance from the inner type node
  1135. const typeChild = getChildByField(node, 'type');
  1136. if (typeChild) this.extractInheritance(typeChild, interfaceNode.id);
  1137. return true;
  1138. }
  1139. const typeAliasNode = this.createNode('type_alias', name, node, {
  1140. docstring,
  1141. isExported,
  1142. });
  1143. // Extract type references from the alias value (e.g., `type X = ITextModel | null`)
  1144. if (typeAliasNode && this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) {
  1145. // The value is everything after the `=`, which is typically the last named child
  1146. // In tree-sitter TS: type_alias_declaration has name + value children
  1147. const value = getChildByField(node, 'value');
  1148. if (value) {
  1149. this.extractTypeRefsFromSubtree(value, typeAliasNode.id);
  1150. }
  1151. }
  1152. return false;
  1153. }
  1154. // extractExportedVariables removed — the walker now descends into
  1155. // export_statement children and the inner declaration's dedicated
  1156. // extractor (extractVariable, extractFunction, extractClass, etc.)
  1157. // handles the symbol with isExported=true via parent-walk in the
  1158. // language extractor's isExported predicate.
  1159. /**
  1160. * Extract an import
  1161. *
  1162. * Creates an import node with the full import statement stored in signature for searchability.
  1163. * Also creates unresolved references for resolution purposes.
  1164. */
  1165. private extractImport(node: SyntaxNode): void {
  1166. if (!this.extractor) return;
  1167. const importText = getNodeText(node, this.source).trim();
  1168. // Try language-specific hook first
  1169. if (this.extractor.extractImport) {
  1170. const info = this.extractor.extractImport(node, this.source);
  1171. if (info) {
  1172. this.createNode('import', info.moduleName, node, {
  1173. signature: info.signature,
  1174. });
  1175. // Create unresolved reference unless the hook handled it
  1176. if (!info.handledRefs && info.moduleName && this.nodeStack.length > 0) {
  1177. const parentId = this.nodeStack[this.nodeStack.length - 1];
  1178. if (parentId) {
  1179. this.unresolvedReferences.push({
  1180. fromNodeId: parentId,
  1181. referenceName: info.moduleName,
  1182. referenceKind: 'imports',
  1183. line: node.startPosition.row + 1,
  1184. column: node.startPosition.column,
  1185. });
  1186. }
  1187. }
  1188. return;
  1189. }
  1190. // Hook returned null — fall through to multi-import inline handlers only
  1191. // (hook returning null means "I didn't handle this" for multi-import cases,
  1192. // NOT "use generic fallback" — the hook already declined)
  1193. }
  1194. // Multi-import cases that create multiple nodes (can't be expressed with single-return hook)
  1195. // Python import_statement: import os, sys (creates one import per module)
  1196. if (this.language === 'python' && node.type === 'import_statement') {
  1197. for (let i = 0; i < node.namedChildCount; i++) {
  1198. const child = node.namedChild(i);
  1199. if (child?.type === 'dotted_name') {
  1200. this.createNode('import', getNodeText(child, this.source), node, {
  1201. signature: importText,
  1202. });
  1203. } else if (child?.type === 'aliased_import') {
  1204. const dottedName = child.namedChildren.find(c => c.type === 'dotted_name');
  1205. if (dottedName) {
  1206. this.createNode('import', getNodeText(dottedName, this.source), node, {
  1207. signature: importText,
  1208. });
  1209. }
  1210. }
  1211. }
  1212. return;
  1213. }
  1214. // Go imports: single or grouped (creates one import per spec)
  1215. if (this.language === 'go') {
  1216. const parentId = this.nodeStack.length > 0 ? this.nodeStack[this.nodeStack.length - 1] : null;
  1217. const extractFromSpec = (spec: SyntaxNode): void => {
  1218. const stringLiteral = spec.namedChildren.find(c => c.type === 'interpreted_string_literal');
  1219. if (stringLiteral) {
  1220. const importPath = getNodeText(stringLiteral, this.source).replace(/['"]/g, '');
  1221. if (importPath) {
  1222. this.createNode('import', importPath, spec, {
  1223. signature: getNodeText(spec, this.source).trim(),
  1224. });
  1225. // Create unresolved reference so the resolver can create imports edges
  1226. if (parentId) {
  1227. this.unresolvedReferences.push({
  1228. fromNodeId: parentId,
  1229. referenceName: importPath,
  1230. referenceKind: 'imports',
  1231. line: spec.startPosition.row + 1,
  1232. column: spec.startPosition.column,
  1233. });
  1234. }
  1235. }
  1236. }
  1237. };
  1238. const importSpecList = node.namedChildren.find(c => c.type === 'import_spec_list');
  1239. if (importSpecList) {
  1240. for (const spec of importSpecList.namedChildren.filter(c => c.type === 'import_spec')) {
  1241. extractFromSpec(spec);
  1242. }
  1243. } else {
  1244. const importSpec = node.namedChildren.find(c => c.type === 'import_spec');
  1245. if (importSpec) {
  1246. extractFromSpec(importSpec);
  1247. }
  1248. }
  1249. return;
  1250. }
  1251. // PHP grouped imports: use X\{A, B} (creates one import per item)
  1252. if (this.language === 'php') {
  1253. const namespacePrefix = node.namedChildren.find(c => c.type === 'namespace_name');
  1254. const useGroup = node.namedChildren.find(c => c.type === 'namespace_use_group');
  1255. if (namespacePrefix && useGroup) {
  1256. const prefix = getNodeText(namespacePrefix, this.source);
  1257. const useClauses = useGroup.namedChildren.filter((c: SyntaxNode) =>
  1258. c.type === 'namespace_use_group_clause' || c.type === 'namespace_use_clause'
  1259. );
  1260. for (const clause of useClauses) {
  1261. const nsName = clause.namedChildren.find((c: SyntaxNode) => c.type === 'namespace_name');
  1262. const name = nsName
  1263. ? nsName.namedChildren.find((c: SyntaxNode) => c.type === 'name')
  1264. : clause.namedChildren.find((c: SyntaxNode) => c.type === 'name');
  1265. if (name) {
  1266. const fullPath = `${prefix}\\${getNodeText(name, this.source)}`;
  1267. this.createNode('import', fullPath, node, {
  1268. signature: importText,
  1269. });
  1270. }
  1271. }
  1272. return;
  1273. }
  1274. }
  1275. // If a hook exists but returned null, it intentionally declined this node — don't create fallback
  1276. if (this.extractor.extractImport) return;
  1277. // Generic fallback for languages without hooks
  1278. this.createNode('import', importText, node, {
  1279. signature: importText,
  1280. });
  1281. }
  1282. /**
  1283. * Extract a function call
  1284. */
  1285. private extractCall(node: SyntaxNode): void {
  1286. if (this.nodeStack.length === 0) return;
  1287. const callerId = this.nodeStack[this.nodeStack.length - 1];
  1288. if (!callerId) return;
  1289. // Get the function/method being called
  1290. let calleeName = '';
  1291. // Java/Kotlin method_invocation has 'object' + 'name' fields instead of 'function'
  1292. // PHP member_call_expression has 'object' + 'name', scoped_call_expression has 'scope' + 'name'
  1293. const nameField = getChildByField(node, 'name');
  1294. const objectField = getChildByField(node, 'object') || getChildByField(node, 'scope');
  1295. if (nameField && objectField && (node.type === 'method_invocation' || node.type === 'member_call_expression' || node.type === 'scoped_call_expression')) {
  1296. // Method call with explicit receiver: receiver.method() / $receiver->method() / ClassName::method()
  1297. const methodName = getNodeText(nameField, this.source);
  1298. let receiverName = getNodeText(objectField, this.source);
  1299. // Strip PHP $ prefix from variable names
  1300. receiverName = receiverName.replace(/^\$/, '');
  1301. if (methodName) {
  1302. // Skip self/this/parent/static receivers — they don't aid resolution
  1303. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super', 'parent', 'static']);
  1304. if (SKIP_RECEIVERS.has(receiverName)) {
  1305. calleeName = methodName;
  1306. } else {
  1307. calleeName = `${receiverName}.${methodName}`;
  1308. }
  1309. }
  1310. } else {
  1311. const func = getChildByField(node, 'function') || node.namedChild(0);
  1312. if (func) {
  1313. if (func.type === 'member_expression' || func.type === 'attribute' || func.type === 'selector_expression' || func.type === 'navigation_expression') {
  1314. // Method call: obj.method() or obj.field.method()
  1315. // Go uses selector_expression with 'field', JS/TS uses member_expression with 'property'
  1316. // Kotlin uses navigation_expression with navigation_suffix > simple_identifier
  1317. let property = getChildByField(func, 'property') || getChildByField(func, 'field');
  1318. if (!property) {
  1319. const child1 = func.namedChild(1);
  1320. // Kotlin: navigation_suffix wraps the method name — extract simple_identifier from it
  1321. if (child1?.type === 'navigation_suffix') {
  1322. property = child1.namedChildren.find((c: SyntaxNode) => c.type === 'simple_identifier') ?? child1;
  1323. } else {
  1324. property = child1;
  1325. }
  1326. }
  1327. if (property) {
  1328. const methodName = getNodeText(property, this.source);
  1329. // Include receiver name for qualified resolution (e.g., console.print → "console.print")
  1330. // This helps the resolver distinguish method calls from bare function calls
  1331. // (e.g., Python's console.print() vs builtin print())
  1332. // Skip self/this/cls as they don't aid resolution
  1333. const receiver = getChildByField(func, 'object') || getChildByField(func, 'operand') || func.namedChild(0);
  1334. const SKIP_RECEIVERS = new Set(['self', 'this', 'cls', 'super']);
  1335. if (receiver && (receiver.type === 'identifier' || receiver.type === 'simple_identifier')) {
  1336. const receiverName = getNodeText(receiver, this.source);
  1337. if (!SKIP_RECEIVERS.has(receiverName)) {
  1338. calleeName = `${receiverName}.${methodName}`;
  1339. } else {
  1340. calleeName = methodName;
  1341. }
  1342. } else {
  1343. calleeName = methodName;
  1344. }
  1345. }
  1346. } else if (func.type === 'scoped_identifier' || func.type === 'scoped_call_expression') {
  1347. // Scoped call: Module::function()
  1348. calleeName = getNodeText(func, this.source);
  1349. } else {
  1350. calleeName = getNodeText(func, this.source);
  1351. }
  1352. }
  1353. }
  1354. if (calleeName) {
  1355. this.unresolvedReferences.push({
  1356. fromNodeId: callerId,
  1357. referenceName: calleeName,
  1358. referenceKind: 'calls',
  1359. line: node.startPosition.row + 1,
  1360. column: node.startPosition.column,
  1361. });
  1362. }
  1363. }
  1364. /**
  1365. * `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
  1366. * emit an `instantiates` reference to the class name. The resolver
  1367. * then links it to the class node, producing the `instantiates`
  1368. * edge that powers "what creates instances of X" queries.
  1369. *
  1370. * Children are still walked so nested calls inside the constructor
  1371. * arguments (`new Foo(bar())`) get their own `calls` references.
  1372. */
  1373. private extractInstantiation(node: SyntaxNode): void {
  1374. if (this.nodeStack.length === 0) return;
  1375. const fromId = this.nodeStack[this.nodeStack.length - 1];
  1376. if (!fromId) return;
  1377. // The class name is in the `constructor`/`type`/first-named-child
  1378. // depending on grammar.
  1379. const ctor =
  1380. getChildByField(node, 'constructor') ||
  1381. getChildByField(node, 'type') ||
  1382. getChildByField(node, 'name') ||
  1383. node.namedChild(0);
  1384. if (!ctor) return;
  1385. let className = getNodeText(ctor, this.source);
  1386. // Strip type-argument suffix first: `new Map<K, V>()` would
  1387. // otherwise produce className 'Map<K, V>' (the constructor
  1388. // field is a `generic_type` node) and resolution would fail
  1389. // because no class is named with the angle-bracket suffix.
  1390. const ltIdx = className.indexOf('<');
  1391. if (ltIdx > 0) className = className.slice(0, ltIdx);
  1392. // For namespaced/qualified constructors (`new ns.Foo()`,
  1393. // `new ns::Foo()`) keep the trailing identifier — that's what
  1394. // matches a class node in the index.
  1395. const lastDot = Math.max(
  1396. className.lastIndexOf('.'),
  1397. className.lastIndexOf('::')
  1398. );
  1399. if (lastDot >= 0) className = className.slice(lastDot + 1).replace(/^[:.]/, '');
  1400. className = className.trim();
  1401. if (className) {
  1402. this.unresolvedReferences.push({
  1403. fromNodeId: fromId,
  1404. referenceName: className,
  1405. referenceKind: 'instantiates',
  1406. line: node.startPosition.row + 1,
  1407. column: node.startPosition.column,
  1408. });
  1409. }
  1410. }
  1411. /**
  1412. * Scan `declNode` and its preceding siblings (within the parent's
  1413. * named children) for decorator nodes, emitting a `decorates`
  1414. * reference from `decoratedId` to each decorator's function name.
  1415. *
  1416. * Why preceding siblings: in TypeScript, `@Foo class Bar {}` parses
  1417. * as an `export_statement` (or top-level wrapper) with the
  1418. * `decorator` as a child *before* the `class_declaration` — so the
  1419. * decorator isn't a child of the class itself. For methods/
  1420. * properties, the decorator IS a direct child of the declaration,
  1421. * so we also scan declNode.namedChildren.
  1422. *
  1423. * Idempotent across grammars: if neither location yields decorators
  1424. * (most non-decorator-using languages), the function is a no-op.
  1425. */
  1426. private extractDecoratorsFor(declNode: SyntaxNode, decoratedId: string): void {
  1427. const consider = (n: SyntaxNode | null): void => {
  1428. if (!n) return;
  1429. // `marker_annotation` is Java's grammar for arg-less annotations
  1430. // (`@Override`, `@Deprecated`); without including it, every
  1431. // such Java annotation would be silently skipped.
  1432. if (
  1433. n.type !== 'decorator' &&
  1434. n.type !== 'annotation' &&
  1435. n.type !== 'marker_annotation'
  1436. ) {
  1437. return;
  1438. }
  1439. // Find the leading identifier: skip the `@` punct, unwrap
  1440. // a call_expression if the decorator is invoked with args.
  1441. let target: SyntaxNode | null = null;
  1442. for (let i = 0; i < n.namedChildCount; i++) {
  1443. const child = n.namedChild(i);
  1444. if (!child) continue;
  1445. if (child.type === 'call_expression') {
  1446. const fn = getChildByField(child, 'function') ?? child.namedChild(0);
  1447. if (fn) target = fn;
  1448. if (target) break;
  1449. }
  1450. if (
  1451. child.type === 'identifier' ||
  1452. child.type === 'member_expression' ||
  1453. child.type === 'scoped_identifier' ||
  1454. child.type === 'navigation_expression'
  1455. ) {
  1456. target = child;
  1457. break;
  1458. }
  1459. }
  1460. if (!target) return;
  1461. let name = getNodeText(target, this.source);
  1462. const lastDot = Math.max(name.lastIndexOf('.'), name.lastIndexOf('::'));
  1463. if (lastDot >= 0) name = name.slice(lastDot + 1).replace(/^[:.]/, '');
  1464. if (!name) return;
  1465. this.unresolvedReferences.push({
  1466. fromNodeId: decoratedId,
  1467. referenceName: name,
  1468. referenceKind: 'decorates',
  1469. line: n.startPosition.row + 1,
  1470. column: n.startPosition.column,
  1471. });
  1472. };
  1473. // 1. Decorators that are direct children of the declaration
  1474. // (method/property style, also some grammars for class).
  1475. for (let i = 0; i < declNode.namedChildCount; i++) {
  1476. consider(declNode.namedChild(i));
  1477. }
  1478. // 2. Decorators that are PRECEDING siblings of the declaration
  1479. // inside the parent's children (TypeScript class style).
  1480. // Walk BACKWARDS from the declaration and stop at the first
  1481. // non-decorator sibling — without that stop, decorators
  1482. // belonging to an EARLIER unrelated declaration leak in
  1483. // (e.g. `@A class Foo {} @B class Bar {}` would otherwise
  1484. // attribute @A to Bar).
  1485. //
  1486. // Note on identity: tree-sitter web bindings return fresh JS
  1487. // wrapper objects from `parent`/`namedChild` navigation, so
  1488. // `sibling === declNode` is unreliable — `startIndex` does
  1489. // the matching instead.
  1490. const parent = declNode.parent;
  1491. if (parent) {
  1492. const declStart = declNode.startIndex;
  1493. let declIdx = -1;
  1494. for (let i = 0; i < parent.namedChildCount; i++) {
  1495. const sibling = parent.namedChild(i);
  1496. if (sibling && sibling.startIndex === declStart) {
  1497. declIdx = i;
  1498. break;
  1499. }
  1500. }
  1501. if (declIdx > 0) {
  1502. for (let j = declIdx - 1; j >= 0; j--) {
  1503. const sibling = parent.namedChild(j);
  1504. if (!sibling) continue;
  1505. if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') {
  1506. break; // non-decorator separator → stop consuming
  1507. }
  1508. consider(sibling);
  1509. }
  1510. }
  1511. }
  1512. }
  1513. /**
  1514. * Visit function body and extract calls (and structural nodes).
  1515. *
  1516. * In addition to call expressions, this also detects class/struct/enum
  1517. * definitions inside function bodies. This handles two cases:
  1518. * 1. Local class/struct/enum definitions (valid in C++, Java, etc.)
  1519. * 2. C++ macro misparsing — macros like NLOHMANN_JSON_NAMESPACE_BEGIN cause
  1520. * tree-sitter to interpret the namespace block as a function_definition,
  1521. * hiding real class/struct/enum nodes inside the "function body".
  1522. */
  1523. private visitFunctionBody(body: SyntaxNode, _functionId: string): void {
  1524. if (!this.extractor) return;
  1525. const visitForCallsAndStructure = (node: SyntaxNode): void => {
  1526. const nodeType = node.type;
  1527. if (this.extractor!.callTypes.includes(nodeType)) {
  1528. this.extractCall(node);
  1529. } else if (INSTANTIATION_KINDS.has(nodeType)) {
  1530. // `new Foo()` inside a function body — emit an `instantiates`
  1531. // reference. Without this branch the body walker only knew
  1532. // about `call_expression`, so constructor invocations
  1533. // produced no graph edges at all.
  1534. this.extractInstantiation(node);
  1535. } else if (this.extractor!.extractBareCall) {
  1536. const calleeName = this.extractor!.extractBareCall(node, this.source);
  1537. if (calleeName && this.nodeStack.length > 0) {
  1538. const callerId = this.nodeStack[this.nodeStack.length - 1];
  1539. if (callerId) {
  1540. this.unresolvedReferences.push({
  1541. fromNodeId: callerId,
  1542. referenceName: calleeName,
  1543. referenceKind: 'calls',
  1544. line: node.startPosition.row + 1,
  1545. column: node.startPosition.column,
  1546. });
  1547. }
  1548. }
  1549. }
  1550. // Nested NAMED functions inside a body — function declarations and named
  1551. // function expressions like `.on('mount', function onmount(){})` — become
  1552. // their own nodes so the graph can link to them (callback handlers, local
  1553. // helpers). Anonymous arrows/expressions fall through to the default
  1554. // recursion below, keeping their inner calls attributed to the enclosing
  1555. // function: this bounds the new nodes to NAMED functions only (no explosion,
  1556. // no lost edges). extractFunction walks the nested body itself, so we return.
  1557. if (this.extractor!.functionTypes.includes(nodeType)) {
  1558. const nestedName = extractName(node, this.source, this.extractor!);
  1559. if (nestedName && nestedName !== '<anonymous>') {
  1560. this.extractFunction(node);
  1561. return;
  1562. }
  1563. }
  1564. // Extract structural nodes found inside function bodies.
  1565. // Each extract method visits its own children, so we return after extracting.
  1566. if (this.extractor!.classTypes.includes(nodeType)) {
  1567. const classification = this.extractor!.classifyClassNode?.(node) ?? 'class';
  1568. if (classification === 'struct') this.extractStruct(node);
  1569. else if (classification === 'enum') this.extractEnum(node);
  1570. else if (classification === 'interface') this.extractInterface(node);
  1571. else if (classification === 'trait') this.extractClass(node, 'trait');
  1572. else this.extractClass(node);
  1573. return;
  1574. }
  1575. if (this.extractor!.structTypes.includes(nodeType)) {
  1576. this.extractStruct(node);
  1577. return;
  1578. }
  1579. if (this.extractor!.enumTypes.includes(nodeType)) {
  1580. this.extractEnum(node);
  1581. return;
  1582. }
  1583. if (this.extractor!.interfaceTypes.includes(nodeType)) {
  1584. this.extractInterface(node);
  1585. return;
  1586. }
  1587. for (let i = 0; i < node.namedChildCount; i++) {
  1588. const child = node.namedChild(i);
  1589. if (child) {
  1590. visitForCallsAndStructure(child);
  1591. }
  1592. }
  1593. };
  1594. visitForCallsAndStructure(body);
  1595. }
  1596. /**
  1597. * Extract inheritance relationships
  1598. */
  1599. private extractInheritance(node: SyntaxNode, classId: string): void {
  1600. // Look for extends/implements clauses
  1601. for (let i = 0; i < node.namedChildCount; i++) {
  1602. const child = node.namedChild(i);
  1603. if (!child) continue;
  1604. if (
  1605. child.type === 'extends_clause' ||
  1606. child.type === 'superclass' ||
  1607. child.type === 'base_clause' || // PHP class extends
  1608. child.type === 'extends_interfaces' // Java interface extends
  1609. ) {
  1610. // Extract parent class/interface names
  1611. // Java uses type_list wrapper: superclass -> type_identifier, extends_interfaces -> type_list -> type_identifier
  1612. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  1613. const targets = typeList ? typeList.namedChildren : [child.namedChild(0)];
  1614. for (const target of targets) {
  1615. if (target) {
  1616. const name = getNodeText(target, this.source);
  1617. this.unresolvedReferences.push({
  1618. fromNodeId: classId,
  1619. referenceName: name,
  1620. referenceKind: 'extends',
  1621. line: target.startPosition.row + 1,
  1622. column: target.startPosition.column,
  1623. });
  1624. }
  1625. }
  1626. }
  1627. if (
  1628. child.type === 'implements_clause' ||
  1629. child.type === 'class_interface_clause' ||
  1630. child.type === 'super_interfaces' || // Java class implements
  1631. child.type === 'interfaces' // Dart
  1632. ) {
  1633. // Extract implemented interfaces
  1634. // Java uses type_list wrapper: super_interfaces -> type_list -> type_identifier
  1635. const typeList = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_list');
  1636. const targets = typeList ? typeList.namedChildren : child.namedChildren;
  1637. for (const iface of targets) {
  1638. if (iface) {
  1639. const name = getNodeText(iface, this.source);
  1640. this.unresolvedReferences.push({
  1641. fromNodeId: classId,
  1642. referenceName: name,
  1643. referenceKind: 'implements',
  1644. line: iface.startPosition.row + 1,
  1645. column: iface.startPosition.column,
  1646. });
  1647. }
  1648. }
  1649. }
  1650. // Python superclass list: `class Flask(Scaffold, Mixin):`
  1651. // argument_list contains identifier children for each parent class
  1652. if (child.type === 'argument_list' && node.type === 'class_definition') {
  1653. for (const arg of child.namedChildren) {
  1654. if (arg.type === 'identifier' || arg.type === 'attribute') {
  1655. const name = getNodeText(arg, this.source);
  1656. this.unresolvedReferences.push({
  1657. fromNodeId: classId,
  1658. referenceName: name,
  1659. referenceKind: 'extends',
  1660. line: arg.startPosition.row + 1,
  1661. column: arg.startPosition.column,
  1662. });
  1663. }
  1664. }
  1665. }
  1666. // Go interface embedding: `type Querier interface { LabelQuerier; ... }`
  1667. // constraint_elem wraps the embedded interface type identifier
  1668. if (child.type === 'constraint_elem') {
  1669. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  1670. if (typeId) {
  1671. const name = getNodeText(typeId, this.source);
  1672. this.unresolvedReferences.push({
  1673. fromNodeId: classId,
  1674. referenceName: name,
  1675. referenceKind: 'extends',
  1676. line: typeId.startPosition.row + 1,
  1677. column: typeId.startPosition.column,
  1678. });
  1679. }
  1680. }
  1681. // Go struct embedding: field_declaration without field_identifier
  1682. // e.g. `type DB struct { *Head; Queryable }` — no field name means embedded type
  1683. if (child.type === 'field_declaration') {
  1684. const hasFieldIdentifier = child.namedChildren.some((c: SyntaxNode) => c.type === 'field_identifier');
  1685. if (!hasFieldIdentifier) {
  1686. const typeId = child.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  1687. if (typeId) {
  1688. const name = getNodeText(typeId, this.source);
  1689. this.unresolvedReferences.push({
  1690. fromNodeId: classId,
  1691. referenceName: name,
  1692. referenceKind: 'extends',
  1693. line: typeId.startPosition.row + 1,
  1694. column: typeId.startPosition.column,
  1695. });
  1696. }
  1697. }
  1698. }
  1699. // Rust trait supertraits: `trait SubTrait: SuperTrait + Display { ... }`
  1700. // trait_bounds contains type_identifier, generic_type, or higher_ranked_trait_bound children
  1701. if (child.type === 'trait_bounds') {
  1702. for (const bound of child.namedChildren) {
  1703. let typeName: string | undefined;
  1704. let posNode: SyntaxNode | undefined;
  1705. if (bound.type === 'type_identifier') {
  1706. typeName = getNodeText(bound, this.source);
  1707. posNode = bound;
  1708. } else if (bound.type === 'generic_type') {
  1709. // e.g. `Deserialize<'de>`
  1710. const inner = bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  1711. if (inner) { typeName = getNodeText(inner, this.source); posNode = inner; }
  1712. } else if (bound.type === 'higher_ranked_trait_bound') {
  1713. // e.g. `for<'de> Deserialize<'de>`
  1714. const generic = bound.namedChildren.find((c: SyntaxNode) => c.type === 'generic_type');
  1715. const typeId = generic?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  1716. ?? bound.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  1717. if (typeId) { typeName = getNodeText(typeId, this.source); posNode = typeId; }
  1718. }
  1719. if (typeName && posNode) {
  1720. this.unresolvedReferences.push({
  1721. fromNodeId: classId,
  1722. referenceName: typeName,
  1723. referenceKind: 'extends',
  1724. line: posNode.startPosition.row + 1,
  1725. column: posNode.startPosition.column,
  1726. });
  1727. }
  1728. }
  1729. }
  1730. // C#: `class Movie : BaseItem, IPlugin` → base_list with identifier children
  1731. // base_list combines both base class and interfaces in a single colon-separated list.
  1732. // We emit all as 'extends' since the syntax doesn't distinguish them.
  1733. if (child.type === 'base_list') {
  1734. for (const baseType of child.namedChildren) {
  1735. if (baseType) {
  1736. // For generic base types like `ClientBase<T>`, extract just the type name
  1737. const name = baseType.type === 'generic_name'
  1738. ? getNodeText(baseType.namedChildren.find((c: SyntaxNode) => c.type === 'identifier') ?? baseType, this.source)
  1739. : getNodeText(baseType, this.source);
  1740. this.unresolvedReferences.push({
  1741. fromNodeId: classId,
  1742. referenceName: name,
  1743. referenceKind: 'extends',
  1744. line: baseType.startPosition.row + 1,
  1745. column: baseType.startPosition.column,
  1746. });
  1747. }
  1748. }
  1749. }
  1750. // Kotlin: `class Foo : Bar, Baz` → delegation_specifier > user_type > type_identifier
  1751. // Also handles `class Foo : Bar()` → delegation_specifier > constructor_invocation > user_type
  1752. if (child.type === 'delegation_specifier') {
  1753. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  1754. const constructorInvocation = child.namedChildren.find((c: SyntaxNode) => c.type === 'constructor_invocation');
  1755. const target = userType ?? constructorInvocation;
  1756. if (target) {
  1757. const typeId = target.type === 'user_type'
  1758. ? target.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier') ?? target
  1759. : target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type')?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier')
  1760. ?? target.namedChildren.find((c: SyntaxNode) => c.type === 'user_type') ?? target;
  1761. const name = getNodeText(typeId, this.source);
  1762. this.unresolvedReferences.push({
  1763. fromNodeId: classId,
  1764. referenceName: name,
  1765. referenceKind: 'extends',
  1766. line: typeId.startPosition.row + 1,
  1767. column: typeId.startPosition.column,
  1768. });
  1769. }
  1770. }
  1771. // Swift: inheritance_specifier > user_type > type_identifier
  1772. // Used for class inheritance, protocol conformance, and protocol inheritance
  1773. if (child.type === 'inheritance_specifier') {
  1774. const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type');
  1775. const typeId = userType?.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier');
  1776. if (typeId) {
  1777. const name = getNodeText(typeId, this.source);
  1778. this.unresolvedReferences.push({
  1779. fromNodeId: classId,
  1780. referenceName: name,
  1781. referenceKind: 'extends',
  1782. line: typeId.startPosition.row + 1,
  1783. column: typeId.startPosition.column,
  1784. });
  1785. }
  1786. }
  1787. // JavaScript class_heritage has bare identifier without extends_clause wrapper
  1788. // e.g. `class Foo extends Bar {}` → class_heritage → identifier("Bar")
  1789. if (
  1790. (child.type === 'identifier' || child.type === 'type_identifier') &&
  1791. node.type === 'class_heritage'
  1792. ) {
  1793. const name = getNodeText(child, this.source);
  1794. this.unresolvedReferences.push({
  1795. fromNodeId: classId,
  1796. referenceName: name,
  1797. referenceKind: 'extends',
  1798. line: child.startPosition.row + 1,
  1799. column: child.startPosition.column,
  1800. });
  1801. }
  1802. // Recurse into container nodes (e.g. field_declaration_list in Go structs,
  1803. // class_heritage in TypeScript which wraps extends_clause/implements_clause)
  1804. if (child.type === 'field_declaration_list' || child.type === 'class_heritage') {
  1805. this.extractInheritance(child, classId);
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * Rust `impl Trait for Type` — creates an implements edge from Type to Trait.
  1811. * For plain `impl Type { ... }` (no trait), no inheritance edge is needed.
  1812. */
  1813. private extractRustImplItem(node: SyntaxNode): void {
  1814. // Check if this is `impl Trait for Type` by looking for a `for` keyword
  1815. const hasFor = node.children.some(
  1816. (c: SyntaxNode) => c.type === 'for' && !c.isNamed
  1817. );
  1818. if (!hasFor) return;
  1819. // In `impl Trait for Type`, the type_identifiers are:
  1820. // first = Trait name, last = implementing Type name
  1821. // Also handle generic types like `impl<T> Trait for MyStruct<T>`
  1822. const typeIdents = node.namedChildren.filter(
  1823. (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'generic_type' || c.type === 'scoped_type_identifier'
  1824. );
  1825. if (typeIdents.length < 2) return;
  1826. const traitNode = typeIdents[0]!;
  1827. const typeNode = typeIdents[typeIdents.length - 1]!;
  1828. // Get the trait name (handle scoped paths like std::fmt::Display)
  1829. const traitName = traitNode.type === 'scoped_type_identifier'
  1830. ? this.source.substring(traitNode.startIndex, traitNode.endIndex)
  1831. : getNodeText(traitNode, this.source);
  1832. // Get the implementing type name (extract inner type_identifier for generics)
  1833. let typeName: string;
  1834. if (typeNode.type === 'generic_type') {
  1835. const inner = typeNode.namedChildren.find(
  1836. (c: SyntaxNode) => c.type === 'type_identifier'
  1837. );
  1838. typeName = inner ? getNodeText(inner, this.source) : getNodeText(typeNode, this.source);
  1839. } else {
  1840. typeName = getNodeText(typeNode, this.source);
  1841. }
  1842. // Find the struct/type node for the implementing type
  1843. const typeNodeId = this.findNodeByName(typeName);
  1844. if (typeNodeId) {
  1845. this.unresolvedReferences.push({
  1846. fromNodeId: typeNodeId,
  1847. referenceName: traitName,
  1848. referenceKind: 'implements',
  1849. line: traitNode.startPosition.row + 1,
  1850. column: traitNode.startPosition.column,
  1851. });
  1852. }
  1853. }
  1854. /**
  1855. * Find a previously-extracted node by name (used for back-references like impl blocks)
  1856. */
  1857. private findNodeByName(name: string): string | undefined {
  1858. for (const node of this.nodes) {
  1859. if (node.name === name && (node.kind === 'struct' || node.kind === 'enum' || node.kind === 'class')) {
  1860. return node.id;
  1861. }
  1862. }
  1863. return undefined;
  1864. }
  1865. /**
  1866. * Languages that support type annotations (TypeScript, etc.)
  1867. */
  1868. private readonly TYPE_ANNOTATION_LANGUAGES = new Set([
  1869. 'typescript', 'tsx', 'dart', 'kotlin', 'swift', 'rust', 'go', 'java', 'csharp',
  1870. ]);
  1871. /**
  1872. * Built-in/primitive type names that shouldn't create references
  1873. */
  1874. private readonly BUILTIN_TYPES = new Set([
  1875. 'string', 'number', 'boolean', 'void', 'null', 'undefined', 'never', 'any', 'unknown',
  1876. 'object', 'symbol', 'bigint', 'true', 'false',
  1877. // Rust
  1878. 'str', 'bool', 'i8', 'i16', 'i32', 'i64', 'i128', 'isize',
  1879. 'u8', 'u16', 'u32', 'u64', 'u128', 'usize', 'f32', 'f64', 'char',
  1880. // Java/C#
  1881. 'int', 'long', 'short', 'byte', 'float', 'double', 'char',
  1882. // Go
  1883. 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64',
  1884. 'float32', 'float64', 'complex64', 'complex128', 'rune', 'error',
  1885. ]);
  1886. /**
  1887. * Extract type references from type annotations on a function/method/field node.
  1888. * Creates 'references' edges for parameter types, return types, and field types.
  1889. */
  1890. private extractTypeAnnotations(node: SyntaxNode, nodeId: string): void {
  1891. if (!this.extractor) return;
  1892. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  1893. // Extract parameter type annotations
  1894. const params = getChildByField(node, this.extractor.paramsField || 'parameters');
  1895. if (params) {
  1896. this.extractTypeRefsFromSubtree(params, nodeId);
  1897. }
  1898. // Extract return type annotation
  1899. const returnType = getChildByField(node, this.extractor.returnField || 'return_type');
  1900. if (returnType) {
  1901. this.extractTypeRefsFromSubtree(returnType, nodeId);
  1902. }
  1903. // Extract direct type annotation (for class fields like `model: ITextModel`)
  1904. const typeAnnotation = node.namedChildren.find(
  1905. (c: SyntaxNode) => c.type === 'type_annotation'
  1906. );
  1907. if (typeAnnotation) {
  1908. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  1909. }
  1910. }
  1911. /**
  1912. * Extract type references from a variable's type annotation.
  1913. */
  1914. private extractVariableTypeAnnotation(node: SyntaxNode, nodeId: string): void {
  1915. if (!this.TYPE_ANNOTATION_LANGUAGES.has(this.language)) return;
  1916. // Find type_annotation child (covers TS `: Type`, Rust `: Type`, etc.)
  1917. const typeAnnotation = node.namedChildren.find(
  1918. (c: SyntaxNode) => c.type === 'type_annotation'
  1919. );
  1920. if (typeAnnotation) {
  1921. this.extractTypeRefsFromSubtree(typeAnnotation, nodeId);
  1922. }
  1923. }
  1924. /**
  1925. * Recursively walk a subtree and extract all type_identifier references.
  1926. * Handles unions, intersections, generics, arrays, etc.
  1927. */
  1928. private extractTypeRefsFromSubtree(node: SyntaxNode, fromNodeId: string): void {
  1929. if (node.type === 'type_identifier') {
  1930. const typeName = getNodeText(node, this.source);
  1931. if (typeName && !this.BUILTIN_TYPES.has(typeName)) {
  1932. this.unresolvedReferences.push({
  1933. fromNodeId,
  1934. referenceName: typeName,
  1935. referenceKind: 'references',
  1936. line: node.startPosition.row + 1,
  1937. column: node.startPosition.column,
  1938. });
  1939. }
  1940. return; // type_identifier is a leaf
  1941. }
  1942. // Recurse into children (handles union_type, intersection_type, generic_type, etc.)
  1943. for (let i = 0; i < node.namedChildCount; i++) {
  1944. const child = node.namedChild(i);
  1945. if (child) {
  1946. this.extractTypeRefsFromSubtree(child, fromNodeId);
  1947. }
  1948. }
  1949. }
  1950. /**
  1951. * Handle Pascal-specific AST structures.
  1952. * Returns true if the node was fully handled and children should be skipped.
  1953. */
  1954. private visitPascalNode(node: SyntaxNode): boolean {
  1955. const nodeType = node.type;
  1956. // Unit/Program/Library → module node
  1957. if (nodeType === 'unit' || nodeType === 'program' || nodeType === 'library') {
  1958. const moduleNameNode = node.namedChildren.find(
  1959. (c: SyntaxNode) => c.type === 'moduleName'
  1960. );
  1961. const name = moduleNameNode ? getNodeText(moduleNameNode, this.source) : '';
  1962. // Fallback to filename without extension if module name is empty
  1963. const moduleName = name || path.basename(this.filePath).replace(/\.[^.]+$/, '');
  1964. this.createNode('module', moduleName, node);
  1965. // Continue visiting children (interface/implementation sections)
  1966. for (let i = 0; i < node.namedChildCount; i++) {
  1967. const child = node.namedChild(i);
  1968. if (child) this.visitNode(child);
  1969. }
  1970. return true;
  1971. }
  1972. // declType wraps declClass/declIntf/declEnum/type-alias
  1973. // The name lives on declType, the inner node determines the kind
  1974. if (nodeType === 'declType') {
  1975. this.extractPascalDeclType(node);
  1976. return true;
  1977. }
  1978. // declUses → import nodes for each unit name
  1979. if (nodeType === 'declUses') {
  1980. this.extractPascalUses(node);
  1981. return true;
  1982. }
  1983. // declConsts → container; visit children for individual declConst
  1984. if (nodeType === 'declConsts') {
  1985. for (let i = 0; i < node.namedChildCount; i++) {
  1986. const child = node.namedChild(i);
  1987. if (child?.type === 'declConst') {
  1988. this.extractPascalConst(child);
  1989. }
  1990. }
  1991. return true;
  1992. }
  1993. // declConst at top level (outside declConsts)
  1994. if (nodeType === 'declConst') {
  1995. this.extractPascalConst(node);
  1996. return true;
  1997. }
  1998. // declTypes → container for type declarations
  1999. if (nodeType === 'declTypes') {
  2000. for (let i = 0; i < node.namedChildCount; i++) {
  2001. const child = node.namedChild(i);
  2002. if (child) this.visitNode(child);
  2003. }
  2004. return true;
  2005. }
  2006. // declVars → container for variable declarations
  2007. if (nodeType === 'declVars') {
  2008. for (let i = 0; i < node.namedChildCount; i++) {
  2009. const child = node.namedChild(i);
  2010. if (child?.type === 'declVar') {
  2011. const nameNode = getChildByField(child, 'name');
  2012. if (nameNode) {
  2013. const name = getNodeText(nameNode, this.source);
  2014. this.createNode('variable', name, child);
  2015. }
  2016. }
  2017. }
  2018. return true;
  2019. }
  2020. // defProc in implementation section → extract calls but don't create duplicate nodes
  2021. if (nodeType === 'defProc') {
  2022. this.extractPascalDefProc(node);
  2023. return true;
  2024. }
  2025. // declProp → property node
  2026. if (nodeType === 'declProp') {
  2027. const nameNode = getChildByField(node, 'name');
  2028. if (nameNode) {
  2029. const name = getNodeText(nameNode, this.source);
  2030. const visibility = this.extractor!.getVisibility?.(node);
  2031. this.createNode('property', name, node, { visibility });
  2032. }
  2033. return true;
  2034. }
  2035. // declField → field node
  2036. if (nodeType === 'declField') {
  2037. const nameNode = getChildByField(node, 'name');
  2038. if (nameNode) {
  2039. const name = getNodeText(nameNode, this.source);
  2040. const visibility = this.extractor!.getVisibility?.(node);
  2041. this.createNode('field', name, node, { visibility });
  2042. }
  2043. return true;
  2044. }
  2045. // declSection → visit children (propagates visibility via getVisibility)
  2046. if (nodeType === 'declSection') {
  2047. for (let i = 0; i < node.namedChildCount; i++) {
  2048. const child = node.namedChild(i);
  2049. if (child) this.visitNode(child);
  2050. }
  2051. return true;
  2052. }
  2053. // exprCall → extract function call reference
  2054. if (nodeType === 'exprCall') {
  2055. this.extractPascalCall(node);
  2056. return true;
  2057. }
  2058. // interface/implementation sections → visit children
  2059. if (nodeType === 'interface' || nodeType === 'implementation') {
  2060. for (let i = 0; i < node.namedChildCount; i++) {
  2061. const child = node.namedChild(i);
  2062. if (child) this.visitNode(child);
  2063. }
  2064. return true;
  2065. }
  2066. // block (begin..end) → visit for calls
  2067. if (nodeType === 'block') {
  2068. this.visitPascalBlock(node);
  2069. return true;
  2070. }
  2071. return false;
  2072. }
  2073. /**
  2074. * Extract a Pascal declType node (class, interface, enum, or type alias)
  2075. */
  2076. private extractPascalDeclType(node: SyntaxNode): void {
  2077. const nameNode = getChildByField(node, 'name');
  2078. if (!nameNode) return;
  2079. const name = getNodeText(nameNode, this.source);
  2080. // Find the inner type declaration
  2081. const declClass = node.namedChildren.find(
  2082. (c: SyntaxNode) => c.type === 'declClass'
  2083. );
  2084. const declIntf = node.namedChildren.find(
  2085. (c: SyntaxNode) => c.type === 'declIntf'
  2086. );
  2087. const typeChild = node.namedChildren.find(
  2088. (c: SyntaxNode) => c.type === 'type'
  2089. );
  2090. if (declClass) {
  2091. const classNode = this.createNode('class', name, node);
  2092. if (classNode) {
  2093. // Extract inheritance from typeref children of declClass
  2094. this.extractPascalInheritance(declClass, classNode.id);
  2095. // Visit class body
  2096. this.nodeStack.push(classNode.id);
  2097. for (let i = 0; i < declClass.namedChildCount; i++) {
  2098. const child = declClass.namedChild(i);
  2099. if (child) this.visitNode(child);
  2100. }
  2101. this.nodeStack.pop();
  2102. }
  2103. } else if (declIntf) {
  2104. const ifaceNode = this.createNode('interface', name, node);
  2105. if (ifaceNode) {
  2106. // Visit interface members
  2107. this.nodeStack.push(ifaceNode.id);
  2108. for (let i = 0; i < declIntf.namedChildCount; i++) {
  2109. const child = declIntf.namedChild(i);
  2110. if (child) this.visitNode(child);
  2111. }
  2112. this.nodeStack.pop();
  2113. }
  2114. } else if (typeChild) {
  2115. // Check if it contains a declEnum
  2116. const declEnum = typeChild.namedChildren.find(
  2117. (c: SyntaxNode) => c.type === 'declEnum'
  2118. );
  2119. if (declEnum) {
  2120. const enumNode = this.createNode('enum', name, node);
  2121. if (enumNode) {
  2122. // Extract enum members
  2123. this.nodeStack.push(enumNode.id);
  2124. for (let i = 0; i < declEnum.namedChildCount; i++) {
  2125. const child = declEnum.namedChild(i);
  2126. if (child?.type === 'declEnumValue') {
  2127. const memberName = getChildByField(child, 'name');
  2128. if (memberName) {
  2129. this.createNode('enum_member', getNodeText(memberName, this.source), child);
  2130. }
  2131. }
  2132. }
  2133. this.nodeStack.pop();
  2134. }
  2135. } else {
  2136. // Simple type alias: type TFoo = string / type TFoo = Integer
  2137. this.createNode('type_alias', name, node);
  2138. }
  2139. } else {
  2140. // Fallback: could be a forward declaration or simple alias
  2141. this.createNode('type_alias', name, node);
  2142. }
  2143. }
  2144. /**
  2145. * Extract Pascal uses clause into individual import nodes
  2146. */
  2147. private extractPascalUses(node: SyntaxNode): void {
  2148. const importText = getNodeText(node, this.source).trim();
  2149. for (let i = 0; i < node.namedChildCount; i++) {
  2150. const child = node.namedChild(i);
  2151. if (child?.type === 'moduleName') {
  2152. const unitName = getNodeText(child, this.source);
  2153. this.createNode('import', unitName, child, {
  2154. signature: importText,
  2155. });
  2156. // Create unresolved reference for resolution
  2157. if (this.nodeStack.length > 0) {
  2158. const parentId = this.nodeStack[this.nodeStack.length - 1];
  2159. if (parentId) {
  2160. this.unresolvedReferences.push({
  2161. fromNodeId: parentId,
  2162. referenceName: unitName,
  2163. referenceKind: 'imports',
  2164. line: child.startPosition.row + 1,
  2165. column: child.startPosition.column,
  2166. });
  2167. }
  2168. }
  2169. }
  2170. }
  2171. }
  2172. /**
  2173. * Extract a Pascal constant declaration
  2174. */
  2175. private extractPascalConst(node: SyntaxNode): void {
  2176. const nameNode = getChildByField(node, 'name');
  2177. if (!nameNode) return;
  2178. const name = getNodeText(nameNode, this.source);
  2179. const defaultValue = node.namedChildren.find(
  2180. (c: SyntaxNode) => c.type === 'defaultValue'
  2181. );
  2182. const sig = defaultValue ? getNodeText(defaultValue, this.source) : undefined;
  2183. this.createNode('constant', name, node, { signature: sig });
  2184. }
  2185. /**
  2186. * Extract Pascal inheritance (extends/implements) from declClass typeref children
  2187. */
  2188. private extractPascalInheritance(declClass: SyntaxNode, classId: string): void {
  2189. const typerefs = declClass.namedChildren.filter(
  2190. (c: SyntaxNode) => c.type === 'typeref'
  2191. );
  2192. for (let i = 0; i < typerefs.length; i++) {
  2193. const ref = typerefs[i]!;
  2194. const name = getNodeText(ref, this.source);
  2195. this.unresolvedReferences.push({
  2196. fromNodeId: classId,
  2197. referenceName: name,
  2198. referenceKind: i === 0 ? 'extends' : 'implements',
  2199. line: ref.startPosition.row + 1,
  2200. column: ref.startPosition.column,
  2201. });
  2202. }
  2203. }
  2204. /**
  2205. * Extract calls and resolve method context from a Pascal defProc (implementation body).
  2206. * Does not create a new node — the declaration was already captured from the interface section.
  2207. */
  2208. private extractPascalDefProc(node: SyntaxNode): void {
  2209. // Find the matching declaration node by name to use as call parent
  2210. const declProc = node.namedChildren.find(
  2211. (c: SyntaxNode) => c.type === 'declProc'
  2212. );
  2213. if (!declProc) return;
  2214. const nameNode = getChildByField(declProc, 'name');
  2215. if (!nameNode) return;
  2216. const fullName = getNodeText(nameNode, this.source).trim();
  2217. // fullName is like "TAuthService.Create"
  2218. const shortName = fullName.includes('.') ? fullName.split('.').pop()! : fullName;
  2219. const fullNameKey = fullName.toLowerCase();
  2220. const shortNameKey = shortName.toLowerCase();
  2221. // Build method index on first use (O(n) once, then O(1) per lookup)
  2222. if (!this.methodIndex) {
  2223. this.methodIndex = new Map();
  2224. for (const n of this.nodes) {
  2225. if (n.kind === 'method' || n.kind === 'function') {
  2226. const nameKey = n.name.toLowerCase();
  2227. // Keep first seen short-name mapping to avoid silently overwriting earlier entries.
  2228. if (!this.methodIndex.has(nameKey)) {
  2229. this.methodIndex.set(nameKey, n.id);
  2230. }
  2231. // For Pascal methods, also index qualified forms (e.g. TAuthService.Create).
  2232. if (n.kind === 'method') {
  2233. const qualifiedParts = n.qualifiedName.split('::');
  2234. if (qualifiedParts.length >= 2) {
  2235. // Create suffix keys so both "Module.Class.Method" and "Class.Method" can resolve.
  2236. for (let i = 0; i < qualifiedParts.length - 1; i++) {
  2237. const scopedName = qualifiedParts.slice(i).join('.').toLowerCase();
  2238. this.methodIndex.set(scopedName, n.id);
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. }
  2245. const parentId =
  2246. this.methodIndex.get(fullNameKey) ||
  2247. this.methodIndex.get(shortNameKey) ||
  2248. this.nodeStack[this.nodeStack.length - 1];
  2249. if (!parentId) return;
  2250. // Visit the block for calls
  2251. const block = node.namedChildren.find(
  2252. (c: SyntaxNode) => c.type === 'block'
  2253. );
  2254. if (block) {
  2255. this.nodeStack.push(parentId);
  2256. this.visitPascalBlock(block);
  2257. this.nodeStack.pop();
  2258. }
  2259. }
  2260. /**
  2261. * Extract function calls from a Pascal expression
  2262. */
  2263. private extractPascalCall(node: SyntaxNode): void {
  2264. if (this.nodeStack.length === 0) return;
  2265. const callerId = this.nodeStack[this.nodeStack.length - 1];
  2266. if (!callerId) return;
  2267. // Get the callee name — first child is typically the identifier or exprDot
  2268. const firstChild = node.namedChild(0);
  2269. if (!firstChild) return;
  2270. let calleeName = '';
  2271. if (firstChild.type === 'exprDot') {
  2272. // Qualified call: Obj.Method(...)
  2273. const identifiers = firstChild.namedChildren.filter(
  2274. (c: SyntaxNode) => c.type === 'identifier'
  2275. );
  2276. if (identifiers.length > 0) {
  2277. calleeName = identifiers.map((id: SyntaxNode) => getNodeText(id, this.source)).join('.');
  2278. }
  2279. } else if (firstChild.type === 'identifier') {
  2280. calleeName = getNodeText(firstChild, this.source);
  2281. }
  2282. if (calleeName) {
  2283. this.unresolvedReferences.push({
  2284. fromNodeId: callerId,
  2285. referenceName: calleeName,
  2286. referenceKind: 'calls',
  2287. line: node.startPosition.row + 1,
  2288. column: node.startPosition.column,
  2289. });
  2290. }
  2291. // Also visit arguments for nested calls
  2292. const args = node.namedChildren.find(
  2293. (c: SyntaxNode) => c.type === 'exprArgs'
  2294. );
  2295. if (args) {
  2296. this.visitPascalBlock(args);
  2297. }
  2298. }
  2299. /**
  2300. * Recursively visit a Pascal block/statement tree for call expressions
  2301. */
  2302. private visitPascalBlock(node: SyntaxNode): void {
  2303. for (let i = 0; i < node.namedChildCount; i++) {
  2304. const child = node.namedChild(i);
  2305. if (!child) continue;
  2306. if (child.type === 'exprCall') {
  2307. this.extractPascalCall(child);
  2308. } else if (child.type === 'exprDot') {
  2309. // Check if exprDot contains an exprCall
  2310. for (let j = 0; j < child.namedChildCount; j++) {
  2311. const grandchild = child.namedChild(j);
  2312. if (grandchild?.type === 'exprCall') {
  2313. this.extractPascalCall(grandchild);
  2314. }
  2315. }
  2316. } else {
  2317. this.visitPascalBlock(child);
  2318. }
  2319. }
  2320. }
  2321. }
  2322. /**
  2323. * Extract nodes and edges from source code.
  2324. *
  2325. * If `frameworkNames` is provided, framework-specific extractors matching
  2326. * those names and the file's language are run after the tree-sitter pass.
  2327. * Their nodes/references/errors are merged into the returned result.
  2328. */
  2329. export function extractFromSource(
  2330. filePath: string,
  2331. source: string,
  2332. language?: Language,
  2333. frameworkNames?: string[]
  2334. ): ExtractionResult {
  2335. const detectedLanguage = language || detectLanguage(filePath, source);
  2336. const fileExtension = path.extname(filePath).toLowerCase();
  2337. let result: ExtractionResult;
  2338. // Use custom extractor for Svelte
  2339. if (detectedLanguage === 'svelte') {
  2340. const extractor = new SvelteExtractor(filePath, source);
  2341. result = extractor.extract();
  2342. } else if (detectedLanguage === 'vue') {
  2343. // Use custom extractor for Vue
  2344. const extractor = new VueExtractor(filePath, source);
  2345. result = extractor.extract();
  2346. } else if (detectedLanguage === 'liquid') {
  2347. // Use custom extractor for Liquid
  2348. const extractor = new LiquidExtractor(filePath, source);
  2349. result = extractor.extract();
  2350. } else if (detectedLanguage === 'yaml' || detectedLanguage === 'twig') {
  2351. // No symbol extraction — file is tracked at the file-record level only.
  2352. // Framework extractors (e.g. Drupal routing resolver) run below and may
  2353. // add route nodes / references for yaml files such as *.routing.yml.
  2354. result = { nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: 0 };
  2355. } else if (
  2356. detectedLanguage === 'pascal' &&
  2357. (fileExtension === '.dfm' || fileExtension === '.fmx')
  2358. ) {
  2359. // Use custom extractor for DFM/FMX form files
  2360. const extractor = new DfmExtractor(filePath, source);
  2361. result = extractor.extract();
  2362. } else {
  2363. const extractor = new TreeSitterExtractor(filePath, source, detectedLanguage);
  2364. result = extractor.extract();
  2365. }
  2366. // Framework-specific extraction (routes, middleware, etc.)
  2367. if (frameworkNames && frameworkNames.length > 0) {
  2368. const allResolvers = getAllFrameworkResolvers();
  2369. const applicable = getApplicableFrameworks(
  2370. allResolvers.filter((r) => frameworkNames.includes(r.name)),
  2371. detectedLanguage
  2372. );
  2373. for (const fw of applicable) {
  2374. if (!fw.extract) continue;
  2375. try {
  2376. const fwResult = fw.extract(filePath, source);
  2377. result.nodes.push(...fwResult.nodes);
  2378. result.unresolvedReferences.push(...fwResult.references);
  2379. } catch (err) {
  2380. result.errors.push({
  2381. message: `Framework extractor '${fw.name}' failed: ${
  2382. err instanceof Error ? err.message : String(err)
  2383. }`,
  2384. filePath,
  2385. severity: 'warning',
  2386. });
  2387. }
  2388. }
  2389. }
  2390. return result;
  2391. }