tree-sitter.ts 81 KB

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