callback-synthesizer.ts 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. /**
  2. * Callback / observer edge synthesis — Phase 1 + 2.
  3. *
  4. * Closes dynamic-dispatch holes where a dispatcher invokes callbacks registered
  5. * elsewhere. Two channel shapes:
  6. *
  7. * (1) Field-backed observer (Phase 1):
  8. * onUpdate(cb) { this.callbacks.add(cb); } // registrar
  9. * triggerUpdate() { for (cb of this.callbacks) cb(); } // dispatcher
  10. * scene.onUpdate(this.triggerRender) // registration
  11. * → synthesize triggerUpdate → triggerRender
  12. *
  13. * (2) String-keyed EventEmitter (Phase 2):
  14. * this.on('mount', function onmount(){...}) // registration
  15. * fn.emit('mount', this) // dispatch
  16. * → synthesize (method containing emit('mount')) → onmount
  17. *
  18. * Whole-graph pass after base resolution. High-precision/low-recall by design:
  19. * named callbacks only; field channels paired by file+field; EventEmitter
  20. * channels capped by event fan-out (generic names like 'error' skipped — they
  21. * need receiver-type matching, deferred to Phase 3). All synthesized edges are
  22. * tagged `provenance:'heuristic'`. See docs/design/callback-edge-synthesis.md.
  23. */
  24. import type { Edge, Node, NodeKind } from '../types';
  25. import type { QueryBuilder } from '../db/queries';
  26. import type { ResolutionContext } from './types';
  27. import { isGeneratedFile } from '../extraction/generated-detection';
  28. import { stripCommentsForRegex } from './strip-comments';
  29. const REGISTRAR_NAME = /^(on[A-Z]\w*|subscribe|addListener|addEventListener|register|watch|listen|addCallback)$/;
  30. const DISPATCHER_NAME = /(emit|trigger|notify|dispatch|fire|publish|flush)/i;
  31. const MAX_CALLBACKS_PER_CHANNEL = 40;
  32. const EVENT_FANOUT_CAP = 6; // skip events with more handlers/dispatchers than this (too generic without type info)
  33. const ON_RE = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:function\s+(\w+)|(?:this\.)?(\w+))/g;
  34. const EMIT_RE = /\.(?:emit|fire|dispatchEvent)\(\s*['"]([^'"]+)['"]/g;
  35. const SETSTATE_RE = /this\.setState\s*\(/;
  36. const FLUTTER_SETSTATE_RE = /\bsetState\s*\(/; // Flutter: setState((){…}) / this.setState
  37. const JSX_TAG_RE = /<([A-Z][A-Za-z0-9_]*)[\s/>]/g;
  38. const MAX_JSX_CHILDREN = 30;
  39. // Vue SFC templates: kebab-case child components (<el-button> → ElButton) and
  40. // event bindings (@click="fn" / v-on:click="fn"). PascalCase children (<VPNav/>)
  41. // are already caught by JSX_TAG_RE via the SFC component node.
  42. const VUE_KEBAB_RE = /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)[\s/>]/g;
  43. // PascalCase component tags — `<MediaCard ...>`, `<NavBar/>`. HTML elements are
  44. // lowercase, so an uppercase-initial tag is a component usage; built-ins
  45. // (`<NuxtLink>`, `<Transition>`) simply resolve to nothing and emit no edge.
  46. const VUE_PASCAL_RE = /<([A-Z][A-Za-z0-9]*)[\s/>]/g;
  47. const VUE_HANDLER_RE = /(?:@|v-on:)([a-zA-Z][\w-]*)(?:\.[\w]+)*\s*=\s*"([^"]+)"/g;
  48. // Composable/hook destructure: `const { close: closeSidebar } = useSidebarControl()`.
  49. // Captures the destructure body + the called composable; only `use*` calls qualify.
  50. const VUE_DESTRUCTURE_RE = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*(\w+)\s*\(/g;
  51. // Closure-collection dynamic dispatch (language-agnostic, Swift-first). A method
  52. // appends a closure to a collection property; another method iterates that
  53. // property *invoking each element* (`coll.forEach { $0() }` / `{ it() }`). The
  54. // element-invoke (`$0(` / `it(`) PROVES the collection holds closures, so pairing
  55. // a dispatcher to same-named registrars (`.append`/`.add`/`.push`/`.insert`,
  56. // incl. Swift `prop.write { $0.append }`) is high-precision. Cross-file/class by
  57. // design: Alamofire appends in `DataRequest.validate` but iterates in the base
  58. // `Request.didCompleteTask` — neither same-file nor same-class pairing reaches it.
  59. const CC_DISPATCH_RE = /(\w+)\.forEach\s*\{\s*(?:\$0|it)\s*\(/g;
  60. const CC_APPEND_WRITE_RE = /(\w+)\.write\s*\{\s*\$0(?:\.(\w+))?\.(?:append|add|push|insert)\s*\(/g;
  61. const CC_APPEND_DIRECT_RE = /(\w+)\.(?:append|add|push|insert)\s*\(/g;
  62. const CC_FANOUT_CAP = 8; // skip a field name with more dispatchers/registrars than this (too generic to pair confidently)
  63. function kebabToPascal(s: string): string {
  64. return s.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
  65. }
  66. /**
  67. * Nuxt auto-import name for a component, derived from its path UNDER `components/`:
  68. * `components/media/Card.vue` → `MediaCard`, `components/base/foo/Bar.vue` →
  69. * `BaseFooBar`. Each directory segment and the filename is PascalCased and
  70. * concatenated; a directory whose PascalCase name prefixes the next segment is
  71. * collapsed (Nuxt's de-dup: `base/BaseButton.vue` → `BaseButton`, not
  72. * `BaseBaseButton`). Returns null for a flat component (`components/NavBar.vue`)
  73. * — its node is already named by basename, so a direct tag match finds it.
  74. */
  75. function nuxtComponentName(filePath: string): string | null {
  76. const marker = filePath.lastIndexOf('components/');
  77. if (marker === -1) return null;
  78. const rel = filePath.slice(marker + 'components/'.length).replace(/\.(vue|ts|tsx|js|jsx)$/i, '');
  79. const segs = rel.split('/').filter(Boolean).map(kebabToPascal);
  80. if (segs.length < 2) return null;
  81. const out: string[] = [];
  82. for (const s of segs) {
  83. const prev = out[out.length - 1];
  84. if (prev && s.startsWith(prev)) out[out.length - 1] = s;
  85. else out.push(s);
  86. }
  87. return out.join('');
  88. }
  89. function sliceLines(content: string, startLine?: number, endLine?: number): string | null {
  90. if (!startLine || !endLine) return null;
  91. return content.split('\n').slice(startLine - 1, endLine).join('\n');
  92. }
  93. function registrarField(src: string): string | null {
  94. const m = src.match(/this\.(\w+)\.(?:add|push|set)\(/);
  95. return m ? m[1]! : null;
  96. }
  97. function dispatcherField(src: string): string | null {
  98. const forOf = src.match(/\bof\s+(?:Array\.from\(\s*)?this\.(\w+)/);
  99. if (forOf && /\b\w+\s*\(/.test(src)) return forOf[1]!;
  100. const forEach = src.match(/this\.(\w+)\.forEach\(/);
  101. if (forEach) return forEach[1]!;
  102. return null;
  103. }
  104. const FN_KINDS = new Set(['method', 'function', 'component']);
  105. /** Innermost function/method node whose line range contains `line`. */
  106. function enclosingFn(nodesInFile: Node[], line: number): Node | null {
  107. let best: Node | null = null;
  108. for (const n of nodesInFile) {
  109. if (!FN_KINDS.has(n.kind)) continue;
  110. const end = n.endLine ?? n.startLine;
  111. if (n.startLine <= line && end >= line) {
  112. if (!best || n.startLine >= best.startLine) best = n; // prefer the tightest (latest-starting) encloser
  113. }
  114. }
  115. return best;
  116. }
  117. /**
  118. * Stream method + function nodes lazily. The synthesizers only scan-and-filter
  119. * down to a tiny matched subset, so materializing every function/method (which
  120. * is gigabytes on a symbol-dense project) just to iterate it once is what OOM'd
  121. * #610. Iterating keeps memory O(1) in the node count.
  122. */
  123. function* methodAndFunctionNodes(queries: QueryBuilder): IterableIterator<Node> {
  124. yield* queries.iterateNodesByKind('method');
  125. yield* queries.iterateNodesByKind('function');
  126. }
  127. /** Phase 1: field-backed observer channels (registrar/dispatcher share a store). */
  128. function fieldChannelEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  129. const registrars: Array<{ node: Node; field: string }> = [];
  130. const dispatchers: Array<{ node: Node; field: string }> = [];
  131. for (const m of methodAndFunctionNodes(queries)) {
  132. const isReg = REGISTRAR_NAME.test(m.name);
  133. const isDisp = DISPATCHER_NAME.test(m.name);
  134. if (!isReg && !isDisp) continue;
  135. const content = ctx.readFile(m.filePath);
  136. const src = content && sliceLines(content, m.startLine, m.endLine);
  137. if (!src) continue;
  138. if (isReg) { const f = registrarField(src); if (f) registrars.push({ node: m, field: f }); }
  139. if (isDisp) { const f = dispatcherField(src); if (f) dispatchers.push({ node: m, field: f }); }
  140. }
  141. const edges: Edge[] = [];
  142. const seen = new Set<string>();
  143. for (const reg of registrars) {
  144. const chDispatchers = dispatchers.filter(
  145. (d) => d.node.filePath === reg.node.filePath && d.field === reg.field
  146. );
  147. if (chDispatchers.length === 0) continue;
  148. const argRe = new RegExp(`${reg.node.name}\\s*\\(\\s*(?:this\\.)?(\\w+)`);
  149. let added = 0;
  150. for (const e of queries.getIncomingEdges(reg.node.id, ['calls'])) {
  151. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  152. if (!e.line) continue;
  153. const caller = queries.getNodeById(e.source);
  154. if (!caller) continue;
  155. const line = ctx.readFile(caller.filePath)?.split('\n')[e.line - 1];
  156. const am = line?.match(argRe);
  157. if (!am) continue;
  158. const fn = ctx.getNodesByName(am[1]!).find((n) => n.kind === 'method' || n.kind === 'function');
  159. if (!fn) continue;
  160. for (const disp of chDispatchers) {
  161. if (disp.node.id === fn.id) continue;
  162. const key = `${disp.node.id}>${fn.id}`;
  163. if (seen.has(key)) continue;
  164. seen.add(key);
  165. edges.push({
  166. source: disp.node.id, target: fn.id, kind: 'calls', line: disp.node.startLine,
  167. provenance: 'heuristic',
  168. metadata: {
  169. synthesizedBy: 'callback', via: reg.node.name, field: reg.field,
  170. // Where the callback was wired up (`scene.onUpdate(this.triggerRender)`).
  171. // This is the #1 thing an agent reads/greps to explain the flow — surface
  172. // it so node/trace/context can show it without a callers() + Read round-trip.
  173. registeredAt: `${caller.filePath}:${e.line}`,
  174. },
  175. });
  176. added++;
  177. }
  178. }
  179. }
  180. return edges;
  181. }
  182. /**
  183. * Closure-collection dispatch: dispatcher iterates a closure-collection property
  184. * invoking each element; registrar appends a closure to the same-named property.
  185. * Emits dispatcher → registrar so a flow reaches the registration site (where the
  186. * appended closure's body — and its callers — live). High-precision: the
  187. * dispatcher's element-invoke is the gate (a `.forEach` that does NOT invoke its
  188. * element is ignored), so a repo with no closure-collection dispatch yields zero
  189. * edges regardless of how many `.append`/`.push` sites it has.
  190. *
  191. * Pairs globally by field name (cross-file/class is required — see Alamofire's
  192. * base-class `Request.didCompleteTask` iterating `validators` appended by the
  193. * subclass `DataRequest.validate`), bounded by a fan-out cap so a generic field
  194. * name shared across unrelated classes can't fan out into noise.
  195. */
  196. function closureCollectionEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  197. const dispatchers = new Map<string, Array<{ node: Node; line: number }>>(); // field → dispatcher methods + forEach line
  198. const registrars = new Map<string, Array<{ node: Node; line: number }>>(); // field → registrar methods + append line
  199. const addReg = (field: string | undefined, node: Node, absLine: number) => {
  200. if (!field || /^\d+$/.test(field)) return; // `$0.append` mis-captures the `0`; the write-RE owns that field
  201. const arr = registrars.get(field) ?? [];
  202. if (!arr.some((r) => r.node.id === node.id)) arr.push({ node, line: absLine });
  203. registrars.set(field, arr);
  204. };
  205. for (const m of methodAndFunctionNodes(queries)) {
  206. const content = ctx.readFile(m.filePath);
  207. const src = content && sliceLines(content, m.startLine, m.endLine);
  208. if (!src) continue;
  209. const hasForEach = src.includes('.forEach');
  210. const hasAppend = src.includes('.append(') || src.includes('.add(') || src.includes('.push(') || src.includes('.insert(');
  211. if (!hasForEach && !hasAppend) continue;
  212. const lineAt = (idx: number) => (m.startLine ?? 1) + src.slice(0, idx).split('\n').length - 1;
  213. if (hasForEach) {
  214. CC_DISPATCH_RE.lastIndex = 0;
  215. let d: RegExpExecArray | null;
  216. while ((d = CC_DISPATCH_RE.exec(src))) {
  217. const arr = dispatchers.get(d[1]!) ?? [];
  218. if (!arr.some((n) => n.node.id === m.id)) arr.push({ node: m, line: lineAt(d.index) });
  219. dispatchers.set(d[1]!, arr);
  220. }
  221. }
  222. if (hasAppend) {
  223. CC_APPEND_WRITE_RE.lastIndex = 0;
  224. let w: RegExpExecArray | null;
  225. while ((w = CC_APPEND_WRITE_RE.exec(src))) addReg(w[2] || w[1], m, lineAt(w.index)); // nested `$0.streams` else the `.write` receiver
  226. CC_APPEND_DIRECT_RE.lastIndex = 0;
  227. let a: RegExpExecArray | null;
  228. while ((a = CC_APPEND_DIRECT_RE.exec(src))) addReg(a[1], m, lineAt(a.index));
  229. }
  230. }
  231. const edges: Edge[] = [];
  232. const seen = new Set<string>();
  233. for (const [field, disps] of dispatchers) {
  234. const regs = registrars.get(field);
  235. if (!regs || regs.length === 0) continue;
  236. if (disps.length > CC_FANOUT_CAP || regs.length > CC_FANOUT_CAP) continue; // generic field — can't pair confidently
  237. for (const disp of disps) for (const reg of regs) {
  238. if (disp.node.id === reg.node.id) continue;
  239. const key = `${disp.node.id}>${reg.node.id}`;
  240. if (seen.has(key)) continue;
  241. seen.add(key);
  242. edges.push({
  243. source: disp.node.id, target: reg.node.id, kind: 'calls', line: disp.line,
  244. provenance: 'heuristic',
  245. metadata: { synthesizedBy: 'closure-collection', field, registeredAt: `${reg.node.filePath}:${reg.line}` },
  246. });
  247. }
  248. }
  249. return edges;
  250. }
  251. /** Phase 2: string-keyed EventEmitter channels (on('e', fn) ↔ emit('e')). */
  252. function eventEmitterEdges(ctx: ResolutionContext): Edge[] {
  253. const emitsByEvent = new Map<string, Set<string>>(); // event → dispatcher node ids
  254. const handlersByEvent = new Map<string, Map<string, string>>(); // event → handler id → registration site (file:line)
  255. for (const file of ctx.getAllFiles()) {
  256. const content = ctx.readFile(file);
  257. if (!content) continue;
  258. const hasEmit = content.includes('.emit(') || content.includes('.fire(') || content.includes('.dispatchEvent(');
  259. const hasOn = content.includes('.on(') || content.includes('.once(') || content.includes('.addListener(');
  260. if (!hasEmit && !hasOn) continue;
  261. const nodesInFile = ctx.getNodesInFile(file);
  262. const lineOf = (idx: number) => content.slice(0, idx).split('\n').length;
  263. if (hasEmit) {
  264. EMIT_RE.lastIndex = 0;
  265. let m: RegExpExecArray | null;
  266. while ((m = EMIT_RE.exec(content))) {
  267. const disp = enclosingFn(nodesInFile, lineOf(m.index));
  268. if (!disp) continue;
  269. const set = emitsByEvent.get(m[1]!) ?? new Set<string>();
  270. set.add(disp.id); emitsByEvent.set(m[1]!, set);
  271. }
  272. }
  273. if (hasOn) {
  274. ON_RE.lastIndex = 0;
  275. let m: RegExpExecArray | null;
  276. while ((m = ON_RE.exec(content))) {
  277. const handlerName = m[2] || m[3];
  278. if (!handlerName) continue;
  279. const handler = ctx.getNodesByName(handlerName).find((n) => n.kind === 'function' || n.kind === 'method');
  280. if (!handler) continue;
  281. const map = handlersByEvent.get(m[1]!) ?? new Map<string, string>();
  282. map.set(handler.id, `${file}:${lineOf(m.index)}`); handlersByEvent.set(m[1]!, map);
  283. }
  284. }
  285. }
  286. const edges: Edge[] = [];
  287. const seen = new Set<string>();
  288. for (const [event, dispatchers] of emitsByEvent) {
  289. const handlers = handlersByEvent.get(event);
  290. if (!handlers) continue;
  291. // Precision guard: a generic event name with many handlers/dispatchers can't
  292. // be matched without receiver-type info (Phase 3) — skip rather than over-link.
  293. if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue;
  294. for (const d of dispatchers) for (const [h, registeredAt] of handlers) {
  295. if (d === h) continue;
  296. const key = `${d}>${h}`;
  297. if (seen.has(key)) continue;
  298. seen.add(key);
  299. edges.push({ source: d, target: h, kind: 'calls', provenance: 'heuristic', metadata: { synthesizedBy: 'event-emitter', event, registeredAt } });
  300. }
  301. }
  302. return edges;
  303. }
  304. /**
  305. * Phase 4: React class-component re-render. `this.setState(...)` re-runs the
  306. * component's `render()`, but that hop is React-internal — no static edge — so a
  307. * flow like "mutation → setState → canvas repaint" dead-ends at setState even
  308. * though `render → getRenderableElements → …` is fully call-connected after it.
  309. * Bridge it: for each class that has a `render` method, link every sibling method
  310. * whose body calls `this.setState(` → `render`. The setState gate keeps this to
  311. * React class components (a non-React class with a `render` method won't call
  312. * `this.setState`). Over-approximation (all setState methods reach render) is
  313. * accepted — it's reachability-correct, like the callback channels.
  314. */
  315. function reactRenderEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  316. const edges: Edge[] = [];
  317. const seen = new Set<string>();
  318. for (const cls of queries.getNodesByKind('class')) {
  319. const children = queries.getOutgoingEdges(cls.id, ['contains'])
  320. .map((e) => queries.getNodeById(e.target))
  321. .filter((n): n is Node => !!n && n.kind === 'method');
  322. const render = children.find((n) => n.name === 'render');
  323. if (!render) continue;
  324. let added = 0;
  325. for (const m of children) {
  326. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  327. if (m.id === render.id) continue;
  328. const content = ctx.readFile(m.filePath);
  329. const src = content && sliceLines(content, m.startLine, m.endLine);
  330. if (!src || !SETSTATE_RE.test(src)) continue;
  331. const key = `${m.id}>${render.id}`;
  332. if (seen.has(key)) continue;
  333. seen.add(key);
  334. edges.push({
  335. source: m.id, target: render.id, kind: 'calls', line: m.startLine,
  336. provenance: 'heuristic',
  337. metadata: { synthesizedBy: 'react-render', via: 'setState', registeredAt: `${render.filePath}:${render.startLine}` },
  338. });
  339. added++;
  340. }
  341. }
  342. return edges;
  343. }
  344. /**
  345. * Phase 4b: Flutter setState → build (the Dart analog of react-render). In a
  346. * StatefulWidget's State class, `setState(() {…})` re-runs `build(context)`, but
  347. * that hop is framework-internal (Flutter calls build), so a flow like
  348. * "onPressed → _increment → setState → rebuilt UI" dead-ends at setState. Bridge
  349. * it: for each Dart class with a `build` method, link every sibling method whose
  350. * body calls `setState(` → `build`. The setState gate + `.dart` file keep this to
  351. * Flutter State classes. Over-approximation accepted (reachability-correct).
  352. */
  353. function flutterBuildEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  354. const edges: Edge[] = [];
  355. const seen = new Set<string>();
  356. for (const cls of queries.getNodesByKind('class')) {
  357. const children = queries.getOutgoingEdges(cls.id, ['contains'])
  358. .map((e) => queries.getNodeById(e.target))
  359. .filter((n): n is Node => !!n && n.kind === 'method');
  360. const build = children.find((n) => n.name === 'build');
  361. if (!build || !build.filePath.endsWith('.dart')) continue;
  362. let added = 0;
  363. for (const m of children) {
  364. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  365. if (m.id === build.id) continue;
  366. const content = ctx.readFile(m.filePath);
  367. const src = content && sliceLines(content, m.startLine, m.endLine);
  368. if (!src || !FLUTTER_SETSTATE_RE.test(src)) continue;
  369. const key = `${m.id}>${build.id}`;
  370. if (seen.has(key)) continue;
  371. seen.add(key);
  372. edges.push({
  373. source: m.id, target: build.id, kind: 'calls', line: m.startLine,
  374. provenance: 'heuristic',
  375. metadata: { synthesizedBy: 'flutter-build', via: 'setState', registeredAt: `${build.filePath}:${build.startLine}` },
  376. });
  377. added++;
  378. }
  379. }
  380. return edges;
  381. }
  382. /**
  383. * Phase 4c: C++ virtual override. A call through a base/interface pointer
  384. * (`db->Get(...)`, `iter->Next()`) dispatches at runtime to a subclass override,
  385. * but that hop is a vtable indirection — no static call edge — so a flow stops at
  386. * the abstract base method. Bridge it like react-render: for each C++ class that
  387. * `extends` a base, link each base method → the subclass method of the same name
  388. * (the override), so trace/callees from the interface method reach the
  389. * implementation(s). Over-approximation accepted (reachability-correct); capped
  390. * per class and gated to C++ to avoid touching other languages' dispatch.
  391. */
  392. function cppOverrideEdges(queries: QueryBuilder): Edge[] {
  393. const edges: Edge[] = [];
  394. const seen = new Set<string>();
  395. const methodsOf = (classId: string): Node[] =>
  396. queries
  397. .getOutgoingEdges(classId, ['contains'])
  398. .map((e) => queries.getNodeById(e.target))
  399. .filter((n): n is Node => !!n && n.kind === 'method');
  400. for (const cls of queries.getNodesByKind('class')) {
  401. const subMethods = methodsOf(cls.id).filter((n) => n.language === 'cpp');
  402. if (subMethods.length === 0) continue;
  403. for (const ext of queries.getOutgoingEdges(cls.id, ['extends'])) {
  404. const base = queries.getNodeById(ext.target);
  405. if (!base || base.language !== 'cpp' || base.id === cls.id) continue;
  406. const baseMethods = new Map(methodsOf(base.id).map((m) => [m.name, m]));
  407. let added = 0;
  408. for (const m of subMethods) {
  409. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  410. const bm = baseMethods.get(m.name);
  411. if (!bm || bm.id === m.id) continue;
  412. const key = `${bm.id}>${m.id}`;
  413. if (seen.has(key)) continue;
  414. seen.add(key);
  415. edges.push({
  416. source: bm.id,
  417. target: m.id,
  418. kind: 'calls',
  419. line: bm.startLine,
  420. provenance: 'heuristic',
  421. metadata: { synthesizedBy: 'cpp-override', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` },
  422. });
  423. added++;
  424. }
  425. }
  426. }
  427. return edges;
  428. }
  429. /**
  430. * Phase 5.5: interface / abstract dispatch (Java, Kotlin). A call through an
  431. * injected interface (`@Autowired FooService svc; svc.list()`) or an abstract
  432. * base dispatches at runtime to the implementing class's override — a vtable
  433. * indirection with no static call edge — so a request→service flow stops at the
  434. * interface method. Bridge it like cpp-override: for each class that
  435. * `implements` an interface (or `extends` an abstract base), link each
  436. * base/interface method → the class's same-name method (the override) so
  437. * trace/callees reach the implementation. Over-approximation accepted
  438. * (reachability-correct); capped per class, gated to JVM languages.
  439. */
  440. // Languages whose static `implements`/`extends` edges should bridge an
  441. // interface (or abstract base) method to the matching concrete-class method.
  442. // The set is "languages with explicit nominal subtyping and a single class
  443. // kind that holds methods" — i.e. the shape this loop expects. Swift and
  444. // Scala fit shape-wise (Swift `protocol`/`class`, Scala `trait`/`class`)
  445. // and are added below; their concrete-side nodes can be a `struct` (Swift)
  446. // or an `object` (Scala) so the loop also iterates those kinds.
  447. const IFACE_OVERRIDE_LANGS = new Set([
  448. 'java', 'kotlin', 'csharp', 'typescript', 'javascript', 'swift', 'scala', 'go', 'rust',
  449. ]);
  450. /**
  451. * Go implicit interface satisfaction (#584). Go has no `implements` keyword — a
  452. * struct satisfies an interface structurally when its method set covers the
  453. * interface's. Synthesize the missing `implements` edge (struct → interface) by
  454. * matching method-NAME sets, so impl-navigation works and the interface-dispatch
  455. * bridge ({@link interfaceOverrideEdges}, now 'go'-enabled) can link an interface
  456. * method call to the concrete overrides.
  457. *
  458. * Name-only matching (signatures ignored) — over-approximation accepted, in line
  459. * with the other dispatch synthesizers; capped per interface. Empty interfaces
  460. * (`any`) are skipped so they don't match every struct.
  461. */
  462. function goImplementsEdges(queries: QueryBuilder): Edge[] {
  463. const edges: Edge[] = [];
  464. const seen = new Set<string>();
  465. const methodNameSet = (id: string): Set<string> =>
  466. new Set(
  467. queries
  468. .getOutgoingEdges(id, ['contains'])
  469. .map((e) => queries.getNodeById(e.target))
  470. .filter((n): n is Node => !!n && n.kind === 'method')
  471. .map((n) => n.name),
  472. );
  473. const goStructs = queries.getNodesByKind('struct').filter((s) => s.language === 'go');
  474. const structMethods = new Map<string, Set<string>>();
  475. for (const s of goStructs) structMethods.set(s.id, methodNameSet(s.id));
  476. for (const iface of queries.getNodesByKind('interface')) {
  477. if (iface.language !== 'go') continue;
  478. const want = methodNameSet(iface.id);
  479. if (want.size === 0) continue; // empty interface (`any`) — would match everything
  480. let added = 0;
  481. for (const s of goStructs) {
  482. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  483. const have = structMethods.get(s.id);
  484. if (!have || have.size < want.size) continue;
  485. let all = true;
  486. for (const m of want) {
  487. if (!have.has(m)) { all = false; break; }
  488. }
  489. if (!all) continue;
  490. const key = `${s.id}>${iface.id}`;
  491. if (seen.has(key)) continue;
  492. seen.add(key);
  493. edges.push({
  494. source: s.id,
  495. target: iface.id,
  496. kind: 'implements',
  497. line: s.startLine,
  498. provenance: 'heuristic',
  499. metadata: { synthesizedBy: 'go-implements', via: iface.name, registeredAt: `${s.filePath}:${s.startLine}` },
  500. });
  501. added++;
  502. }
  503. }
  504. return edges;
  505. }
  506. /**
  507. * Cross-file Go method → receiver-type `contains` edges. In Go a type's methods
  508. * are commonly declared in a different file from the `type` declaration itself
  509. * (`type User struct{…}` in `user.go`, `func (u *User) Save()` in
  510. * `user_store.go`). Extraction attaches the struct→method `contains` edge only
  511. * when the receiver type is in the SAME file — the owner lookup in
  512. * `tree-sitter.ts` is scoped to the file being parsed — so a cross-file method
  513. * is left orphaned from its type (it's still `contains`ed by its file, just not
  514. * its struct). That breaks `codegraph_node` member outlines, any
  515. * callers/callees/impact traversal that goes through the type's `contains`
  516. * edges, and the {@link goImplementsEdges} method-set computation (which derives
  517. * a struct's method set from those same edges, so it under-counts interfaces a
  518. * cross-file struct satisfies).
  519. *
  520. * Go guarantees a method's receiver type is declared in the SAME PACKAGE as the
  521. * method, and a Go package is a single directory — so this is a deterministic
  522. * structural link, not a heuristic: find the same-named type in the method's own
  523. * directory and add the missing `contains` edge (no `provenance: 'heuristic'`,
  524. * matching the same-file edges extraction already emits). Skips methods that
  525. * already have a type parent (the same-file case). (#583, cross-file half)
  526. */
  527. function goCrossFileMethodContainsEdges(queries: QueryBuilder): Edge[] {
  528. const edges: Edge[] = [];
  529. const seen = new Set<string>();
  530. const TYPE_KINDS = new Set<NodeKind>(['struct', 'class', 'interface', 'enum', 'type_alias']);
  531. const dirOf = (p: string): string => {
  532. const i = p.replace(/\\/g, '/').lastIndexOf('/');
  533. return i >= 0 ? p.slice(0, i) : '';
  534. };
  535. for (const method of queries.getNodesByKind('method')) {
  536. if (method.language !== 'go') continue;
  537. // The receiver type is encoded in the method's qualifiedName as `Recv::name`
  538. // (extraction sets `${receiverType}::${name}` for receiver methods).
  539. const qn = method.qualifiedName;
  540. if (!qn) continue;
  541. const sep = qn.lastIndexOf('::');
  542. if (sep <= 0) continue;
  543. const receiver = qn.slice(0, sep);
  544. if (!receiver) continue;
  545. // Already attached to its type (same-file case handled at extraction)?
  546. const hasTypeParent = queries
  547. .getIncomingEdges(method.id, ['contains'])
  548. .some((e) => {
  549. const src = queries.getNodeById(e.source);
  550. return src != null && TYPE_KINDS.has(src.kind);
  551. });
  552. if (hasTypeParent) continue;
  553. // Find the receiver type in the SAME directory (= same Go package). Go forbids
  554. // duplicate type names within a package, so a same-name same-dir match is
  555. // unambiguous; scoping to the directory avoids linking to a same-named type
  556. // in another package.
  557. const dir = dirOf(method.filePath);
  558. const owner = queries
  559. .getNodesByName(receiver)
  560. .find((n) => n.language === 'go' && TYPE_KINDS.has(n.kind) && dirOf(n.filePath) === dir);
  561. if (!owner) continue;
  562. const key = `${owner.id}>${method.id}`;
  563. if (seen.has(key)) continue;
  564. seen.add(key);
  565. edges.push({ source: owner.id, target: method.id, kind: 'contains', line: method.startLine });
  566. }
  567. return edges;
  568. }
  569. /**
  570. * Kotlin Multiplatform `expect`/`actual` linking. A `common` source set declares
  571. * `expect fun foo()` / `expect class Bar`; each platform source set (jvm, native,
  572. * js, …) provides an `actual` implementation with the IDENTICAL fully-qualified
  573. * name in a different file. Callers in common code resolve to the `expect`
  574. * declaration, so every `actual` impl ends up with zero dependents — invisible to
  575. * impact/affected even though editing it can break every caller of the API.
  576. *
  577. * Synthesize a `calls` edge from the common declaration to each platform `actual`
  578. * (mirroring the interface-impl bridge: abstract → concrete), so editing a
  579. * platform impl surfaces the common `expect` and its callers, and the impl file
  580. * participates in the graph.
  581. *
  582. * `expect`/`actual` are captured onto the node's `decorators` list at extraction
  583. * (kotlin.ts `extractModifiers`). Members of an `expect class` are NOT themselves
  584. * keyword-marked, so the declaration side is matched as the same-FQN, same-kind
  585. * node that is NOT marked `actual`. Requiring an `actual`-marked counterpart also
  586. * gates out plain cross-file overloads (neither side is marked).
  587. */
  588. // Kinds that an `expect`/`actual` pair may legitimately straddle. `expect class`
  589. // is routinely fulfilled by an `actual typealias` (e.g. `actual typealias
  590. // CancellationException = …`, `actual typealias SchedulerTask = Task`), so a
  591. // strict kind match would miss those one-line alias files. Same-FQN + the
  592. // `actual` marker already gates out unrelated symbols, so widening to the
  593. // type-like kinds is safe.
  594. const KMP_TYPE_KINDS = new Set(['class', 'interface', 'struct', 'enum', 'type_alias']);
  595. function kmpKindsCompatible(a: string, b: string): boolean {
  596. return a === b || (KMP_TYPE_KINDS.has(a) && KMP_TYPE_KINDS.has(b));
  597. }
  598. function kotlinExpectActualEdges(queries: QueryBuilder): Edge[] {
  599. const edges: Edge[] = [];
  600. const seen = new Set<string>();
  601. const actuals = queries
  602. .getAllNodes()
  603. .filter((n) => n.language === 'kotlin' && !!n.decorators?.includes('actual'));
  604. for (const act of actuals) {
  605. let added = 0;
  606. for (const cand of queries.getNodesByQualifiedNameExact(act.qualifiedName)) {
  607. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  608. // The declaration side: same FQN + compatible kind, a different file, NOT
  609. // itself an `actual` (that would be a sibling platform impl, not the decl).
  610. if (cand.language !== 'kotlin' || cand.id === act.id) continue;
  611. if (!kmpKindsCompatible(cand.kind, act.kind) || cand.filePath === act.filePath) continue;
  612. if (cand.decorators?.includes('actual')) continue;
  613. const key = `${cand.id}>${act.id}`;
  614. if (seen.has(key)) continue;
  615. seen.add(key);
  616. edges.push({
  617. source: cand.id,
  618. target: act.id,
  619. kind: 'calls',
  620. line: cand.startLine,
  621. provenance: 'heuristic',
  622. metadata: {
  623. synthesizedBy: 'kotlin-expect-actual',
  624. via: act.name,
  625. registeredAt: `${act.filePath}:${act.startLine}`,
  626. },
  627. });
  628. added++;
  629. }
  630. }
  631. return edges;
  632. }
  633. function interfaceOverrideEdges(queries: QueryBuilder): Edge[] {
  634. const edges: Edge[] = [];
  635. const seen = new Set<string>();
  636. const methodsOf = (classId: string): Node[] =>
  637. queries
  638. .getOutgoingEdges(classId, ['contains'])
  639. .map((e) => queries.getNodeById(e.target))
  640. .filter((n): n is Node => !!n && n.kind === 'method');
  641. // Concrete-side kinds vary by language: `class` covers Java / Kotlin /
  642. // C# / TS / Swift-classes / Scala-classes; `struct` covers Swift value
  643. // types that conform to protocols. Iterate both.
  644. const concreteKinds = ['class', 'struct'] as const;
  645. for (const kind of concreteKinds) {
  646. for (const cls of queries.getNodesByKind(kind)) {
  647. const implMethods = methodsOf(cls.id).filter((n) => IFACE_OVERRIDE_LANGS.has(n.language));
  648. if (implMethods.length === 0) continue;
  649. for (const sup of queries.getOutgoingEdges(cls.id, ['implements', 'extends'])) {
  650. const base = queries.getNodeById(sup.target);
  651. if (!base || !IFACE_OVERRIDE_LANGS.has(base.language) || base.id === cls.id) continue;
  652. // Group impl methods by name to handle OVERLOADS: an interface `list()` and
  653. // `list(params)` are distinct nodes and a call may resolve to either, so
  654. // link every base overload → every same-name impl overload (keying by name
  655. // alone would drop all but one and miss the resolved overload).
  656. const implByName = new Map<string, Node[]>();
  657. for (const m of implMethods) {
  658. const arr = implByName.get(m.name);
  659. if (arr) arr.push(m); else implByName.set(m.name, [m]);
  660. }
  661. let added = 0;
  662. for (const bm of methodsOf(base.id)) {
  663. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  664. for (const m of implByName.get(bm.name) ?? []) {
  665. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  666. if (bm.id === m.id) continue;
  667. const key = `${bm.id}>${m.id}`;
  668. if (seen.has(key)) continue;
  669. seen.add(key);
  670. edges.push({
  671. source: bm.id,
  672. target: m.id,
  673. kind: 'calls',
  674. line: bm.startLine,
  675. provenance: 'heuristic',
  676. metadata: { synthesizedBy: 'interface-impl', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` },
  677. });
  678. added++;
  679. }
  680. }
  681. }
  682. }
  683. }
  684. return edges;
  685. }
  686. /**
  687. * Go gRPC stub → impl bridge. The protoc-gen-go-grpc codegen emits an
  688. * `UnimplementedXxxServer` struct in `*_grpc.pb.go` carrying one method
  689. * per service RPC; the real handler is a hand-written struct in another
  690. * file (`x/bank/keeper/msg_server.go::msgServer.Send` in cosmos-sdk).
  691. * Go's structural typing means no `implements` edge exists for our
  692. * resolver to follow, so `trace("Send","SendCoins")` lands on the
  693. * empty stub and reports "no path" (validated empirically — the cosmos
  694. * Q1 r1 trace failure that drove this work).
  695. *
  696. * Bridge: for each `UnimplementedXxxServer` whose RPC-method names are
  697. * a SUBSET of some other Go struct's method names, emit `calls` edges
  698. * `stub.method → impl.method` (paired by name). Excludes the gRPC
  699. * internal markers `mustEmbedUnimplementedXxxServer` and
  700. * `testEmbeddedByValue`, and skips candidate impls that themselves
  701. * live in a generated file (their `xxxClient` / sibling stubs would
  702. * otherwise look like impls).
  703. *
  704. * Multiple candidates is allowed and capped at MAX_CALLBACKS_PER_CHANNEL —
  705. * a service often has both a production impl and one or more test
  706. * mocks; linking to all preserves trace utility without false-favoring.
  707. *
  708. * Provenance: `heuristic`, `synthesizedBy: 'go-grpc-stub-impl'`. The
  709. * stub's source line is the wiring site shown in the trace trail.
  710. */
  711. function goGrpcStubImplEdges(queries: QueryBuilder): Edge[] {
  712. const edges: Edge[] = [];
  713. const seen = new Set<string>();
  714. const STUB_RE = /^Unimplemented.*Server$/;
  715. // gRPC internal-helper methods that appear on every Unimplemented*Server;
  716. // not part of the service contract, so exclude when computing the RPC-method
  717. // signature used to match impls.
  718. const isInternalMarker = (n: string) => n.startsWith('mustEmbed') || n === 'testEmbeddedByValue';
  719. // Methods directly contained by each Go struct, name-only. Built once.
  720. const methodNamesByStruct = new Map<string, Set<string>>();
  721. const methodNodesByStruct = new Map<string, Node[]>();
  722. const goStructs: Node[] = [];
  723. for (const s of queries.getNodesByKind('struct')) {
  724. if (s.language !== 'go') continue;
  725. goStructs.push(s);
  726. const ms = queries
  727. .getOutgoingEdges(s.id, ['contains'])
  728. .map((e) => queries.getNodeById(e.target))
  729. .filter((n): n is Node => !!n && n.kind === 'method');
  730. methodNodesByStruct.set(s.id, ms);
  731. methodNamesByStruct.set(s.id, new Set(ms.map((m) => m.name)));
  732. }
  733. for (const stub of goStructs) {
  734. if (!STUB_RE.test(stub.name)) continue;
  735. // The stub MUST live in a generated file — that's what tells us this is
  736. // a protoc-emitted scaffold rather than someone naming a struct
  737. // `UnimplementedXxxServer` by hand. Without this gate we'd also bridge
  738. // such hand-written structs and create misleading edges.
  739. if (!isGeneratedFile(stub.filePath)) continue;
  740. const stubMethods = (methodNodesByStruct.get(stub.id) ?? []).filter(
  741. (m) => !isInternalMarker(m.name),
  742. );
  743. if (stubMethods.length === 0) continue;
  744. const stubMethodNames = stubMethods.map((m) => m.name);
  745. for (const cand of goStructs) {
  746. if (cand.id === stub.id) continue;
  747. // Skip generated-file candidates — they're siblings (msgClient,
  748. // UnsafeMsgServer, …) whose method sets coincidentally match.
  749. if (isGeneratedFile(cand.filePath)) continue;
  750. const candNames = methodNamesByStruct.get(cand.id);
  751. if (!candNames) continue;
  752. // Subset: every RPC method must exist on the candidate by name.
  753. // Signature-level match would tighten this further, but name-match
  754. // alone already gives one-to-one pairing in real codebases because
  755. // gRPC method-name sets are highly distinctive (Send + MultiSend +
  756. // UpdateParams + SetSendEnabled is unique to bank's MsgServer).
  757. if (!stubMethodNames.every((n) => candNames.has(n))) continue;
  758. const candMethods = methodNodesByStruct.get(cand.id) ?? [];
  759. let added = 0;
  760. for (const sm of stubMethods) {
  761. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  762. for (const cm of candMethods) {
  763. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  764. if (cm.name !== sm.name) continue;
  765. const key = `${sm.id}>${cm.id}`;
  766. if (seen.has(key)) continue;
  767. seen.add(key);
  768. edges.push({
  769. source: sm.id,
  770. target: cm.id,
  771. kind: 'calls',
  772. line: sm.startLine,
  773. provenance: 'heuristic',
  774. metadata: {
  775. synthesizedBy: 'go-grpc-stub-impl',
  776. via: cm.name,
  777. registeredAt: `${cm.filePath}:${cm.startLine}`,
  778. },
  779. });
  780. added++;
  781. }
  782. }
  783. }
  784. }
  785. return edges;
  786. }
  787. /**
  788. * Phase 5: React JSX child rendering. A component that returns `<Child .../>`
  789. * mounts Child — React calls it — but JSX instantiation isn't a static call edge,
  790. * so a render tree (App.render → StaticCanvas → renderStaticScene) breaks at the
  791. * JSX hop. Link parent → each capitalized JSX child it renders. File-oriented
  792. * (read each JSX file once). Precision gate: the child name must resolve to a
  793. * component/function/class node — TS generics like `Array<Foo>` resolve to a type
  794. * (or nothing) and are dropped.
  795. */
  796. function reactJsxChildEdges(ctx: ResolutionContext): Edge[] {
  797. const edges: Edge[] = [];
  798. const seen = new Set<string>();
  799. const PARENT_KINDS = new Set(['method', 'function', 'component']);
  800. for (const file of ctx.getAllFiles()) {
  801. const content = ctx.readFile(file);
  802. if (!content || (!content.includes('</') && !content.includes('/>'))) continue; // JSX-file gate
  803. const parents = ctx.getNodesInFile(file).filter((n) => PARENT_KINDS.has(n.kind));
  804. for (const parent of parents) {
  805. const src = sliceLines(content, parent.startLine, parent.endLine);
  806. if (!src || (!src.includes('</') && !src.includes('/>'))) continue;
  807. const names = new Set<string>();
  808. JSX_TAG_RE.lastIndex = 0;
  809. let m: RegExpExecArray | null;
  810. while ((m = JSX_TAG_RE.exec(src))) names.add(m[1]!);
  811. let added = 0;
  812. for (const name of names) {
  813. if (added >= MAX_JSX_CHILDREN) break;
  814. const child = ctx.getNodesByName(name).find(
  815. (n) => n.kind === 'component' || n.kind === 'function' || n.kind === 'class'
  816. );
  817. if (!child || child.id === parent.id) continue;
  818. const key = `${parent.id}>${child.id}`;
  819. if (seen.has(key)) continue;
  820. seen.add(key);
  821. edges.push({
  822. source: parent.id, target: child.id, kind: 'calls', line: parent.startLine,
  823. provenance: 'heuristic',
  824. metadata: { synthesizedBy: 'jsx-render', via: name },
  825. });
  826. added++;
  827. }
  828. }
  829. }
  830. return edges;
  831. }
  832. /**
  833. * Phase 6: Vue SFC templates. The `.vue` extractor only parses `<script>`, so
  834. * template usage is invisible — child components and event handlers used ONLY in
  835. * the template have no edge to them. PascalCase children (`<VPNav/>`) are already
  836. * caught by reactJsxChildEdges (which scans the SFC component node), so this adds
  837. * the two Vue-specific shapes:
  838. * - kebab-case children: `<el-button>` → `ElButton` component (renders).
  839. * - event bindings: `@click="onClick"` / `v-on:submit="save"` → handler method.
  840. * Scoped to the `<template>` block of `.vue` files; resolution gate (kebab→
  841. * component, handler→function/method) keeps precision; inline arrows / `$emit`
  842. * skipped.
  843. */
  844. function vueTemplateEdges(ctx: ResolutionContext): Edge[] {
  845. const edges: Edge[] = [];
  846. const seen = new Set<string>();
  847. const COMPONENT_KINDS = new Set(['component', 'function', 'class']);
  848. const HANDLER_KINDS = new Set(['method', 'function']);
  849. // A composable's returned member may be a fn (`function close(){}`) or an
  850. // arrow assigned to a const (`const close = () => {}`).
  851. const RETURN_KINDS = new Set(['method', 'function', 'variable', 'constant']);
  852. // Nuxt auto-imports nested components by a DIRECTORY-PREFIXED name —
  853. // `components/media/Card.vue` is used as `<MediaCard/>`, not `<Card/>` — but
  854. // the component node is named by basename (`Card`), so a direct tag match
  855. // misses it (flat components match by basename and don't need this). Map each
  856. // nested component's Nuxt name → node so those template usages resolve.
  857. const nuxtComponents = new Map<string, Node>();
  858. for (const c of ctx.getNodesByKind('component')) {
  859. const nn = nuxtComponentName(c.filePath);
  860. if (nn && !nuxtComponents.has(nn)) nuxtComponents.set(nn, c);
  861. }
  862. for (const file of ctx.getAllFiles()) {
  863. if (!file.endsWith('.vue')) continue;
  864. const content = ctx.readFile(file);
  865. const tpl = content && content.match(/<template[^>]*>([\s\S]*)<\/template>/i)?.[1];
  866. if (!tpl) continue;
  867. const comp = ctx.getNodesInFile(file).find((n) => n.kind === 'component');
  868. if (!comp) continue;
  869. // Composable-destructure map: alias → { composable, key }. Lets us resolve a
  870. // template handler that isn't a local function but a destructured composable
  871. // return (`@click="closeSidebar"` ← `const { close: closeSidebar } = useSidebarControl()`).
  872. const script = content.match(/<script[^>]*>([\s\S]*?)<\/script>/i)?.[1] ?? '';
  873. const destructured = new Map<string, { composable: string; key: string }>();
  874. VUE_DESTRUCTURE_RE.lastIndex = 0;
  875. let dm: RegExpExecArray | null;
  876. while ((dm = VUE_DESTRUCTURE_RE.exec(script))) {
  877. if (!/^use[A-Z]/.test(dm[2]!)) continue; // composables / hooks only
  878. for (const part of dm[1]!.split(',')) {
  879. const pm = part.trim().match(/^(\w+)\s*(?::\s*(\w+))?$/); // key | key: alias
  880. if (pm) destructured.set(pm[2] || pm[1]!, { composable: dm[2]!, key: pm[1]! });
  881. }
  882. }
  883. let added = 0;
  884. const addEdge = (target: Node | undefined, meta: Record<string, unknown>) => {
  885. if (added >= MAX_JSX_CHILDREN || !target || target.id === comp.id) return;
  886. const k = `${comp.id}>${target.id}>${meta.synthesizedBy}`;
  887. if (seen.has(k)) return;
  888. seen.add(k);
  889. edges.push({ source: comp.id, target: target.id, kind: 'calls', line: comp.startLine, provenance: 'heuristic', metadata: meta });
  890. added++;
  891. };
  892. // Prefer a target in THIS SFC (handlers live in the same file's script) —
  893. // avoids cross-file mis-match when a name repeats across a monorepo.
  894. const resolve = (name: string, kinds: Set<string>): Node | undefined => {
  895. const matches = ctx.getNodesByName(name).filter((n) => kinds.has(n.kind));
  896. return matches.find((n) => n.filePath === file) ?? matches[0];
  897. };
  898. let m: RegExpExecArray | null;
  899. VUE_KEBAB_RE.lastIndex = 0;
  900. while ((m = VUE_KEBAB_RE.exec(tpl))) {
  901. const tag = kebabToPascal(m[1]!);
  902. addEdge(resolve(tag, COMPONENT_KINDS) ?? nuxtComponents.get(tag), { synthesizedBy: 'jsx-render', via: m[1] });
  903. }
  904. // PascalCase component tags. Try a direct name match first (flat components
  905. // and explicit registrations), then the Nuxt dir-prefixed auto-import name
  906. // (`<MediaCard>` → components/media/Card.vue). Built-ins match neither → no edge.
  907. VUE_PASCAL_RE.lastIndex = 0;
  908. while ((m = VUE_PASCAL_RE.exec(tpl))) {
  909. const tag = m[1]!;
  910. addEdge(resolve(tag, COMPONENT_KINDS) ?? nuxtComponents.get(tag), { synthesizedBy: 'jsx-render', via: tag });
  911. }
  912. VUE_HANDLER_RE.lastIndex = 0;
  913. while ((m = VUE_HANDLER_RE.exec(tpl))) {
  914. const event = m[1]!;
  915. const expr = m[2]!.trim();
  916. if (expr.includes('=>') || expr.startsWith('$')) continue; // inline arrow / $emit
  917. const name = expr.match(/^([A-Za-z_]\w*)/)?.[1];
  918. if (!name) continue;
  919. const direct = resolve(name, HANDLER_KINDS);
  920. if (direct) { addEdge(direct, { synthesizedBy: 'vue-handler', event }); continue; }
  921. // Composable-destructure handler → resolve to the composable's returned fn.
  922. const d = destructured.get(name);
  923. if (!d) continue;
  924. const composable = resolve(d.composable, HANDLER_KINDS);
  925. // Resolve to the SPECIFIC returned member (e.g. `close`) defined in the
  926. // composable's file. No fallback to the composable itself — the component
  927. // already has a static `useX()` call edge, so that would just be redundant
  928. // and less precise.
  929. const keyFn = composable
  930. ? ctx.getNodesByName(d.key).find((n) => RETURN_KINDS.has(n.kind) && n.filePath === composable.filePath)
  931. : undefined;
  932. if (keyFn) addEdge(keyFn, { synthesizedBy: 'vue-handler', event, via: d.composable });
  933. }
  934. }
  935. return edges;
  936. }
  937. /**
  938. * React Native cross-language event channel (Phase 3 of the mixed-iOS/RN
  939. * bridging effort). Same shape as `eventEmitterEdges` but cross-language:
  940. *
  941. * Native (ObjC, on RCTEventEmitter subclass):
  942. * [self sendEventWithName:@"locationUpdate" body:@{...}];
  943. *
  944. * Native (Java/Kotlin, via the JS module dispatcher):
  945. * emitter.emit("locationUpdate", body);
  946. * reactContext.getJSModule(RCTDeviceEventEmitter.class).emit("locationUpdate", body);
  947. *
  948. * JS (subscriber):
  949. * new NativeEventEmitter(NativeModules.Geo).addListener("locationUpdate", handler);
  950. * DeviceEventEmitter.addListener("locationUpdate", handler);
  951. *
  952. * Synthesize: native dispatch site → JS handler, keyed by the literal
  953. * event name. Only matches NAMED handlers (the existing `ON_RE` named-
  954. * capture form). Inline arrow handlers like `addListener('x', d => …)`
  955. * aren't named at extraction time and would need link-through-body
  956. * support; matches the deliberate scope of the in-language synthesizer.
  957. *
  958. * Provenance `'heuristic'`, synthesizedBy `'rn-event-channel'`.
  959. */
  960. // ObjC's `[self sendEventWithName:@"X" body:...]` shape (bracket syntax,
  961. // `@` string literals).
  962. const RN_OBJC_SEND_RE = /\bsendEventWithName\s*:\s*@"([^"]+)"/g;
  963. // Swift's `sendEvent(withName: "X", body: ...)` shape — same RCTEventEmitter
  964. // method, different call syntax. Both Objective-C and Swift subclass
  965. // RCTEventEmitter so this catches the Swift-side equivalent emission sites
  966. // (e.g. RNFusedLocation.swift's `sendEvent(withName: "geolocationDidChange",
  967. // body: locationData)`).
  968. const RN_SWIFT_SEND_RE = /\bsendEvent\s*\(\s*withName\s*:\s*"([^"]+)"/g;
  969. // JVM-side emitter calls: `emitter.emit("X", body)`. Matches both Java
  970. // and Kotlin syntax because the call form is identical. Restricted to
  971. // JVM source files in the consumer so we don't re-process JS emits
  972. // (which `eventEmitterEdges` already handles).
  973. const RN_JVM_EMIT_RE = /\.emit\s*\(\s*"([^"]+)"\s*,/g;
  974. // Custom `sendEvent(reactContext, "X", body)` wrapper — extremely common
  975. // (react-native-device-info and many libs wrap `DeviceEventManagerModule…emit`
  976. // behind a helper whose `.emit(eventName, …)` uses a VARIABLE, so RN_JVM_EMIT_RE
  977. // misses it; the literal lives in the wrapper CALL instead). Captures the first
  978. // string literal inside a `sendEvent(...)` call. `[^;{}]*?` keeps it on one
  979. // statement and stops at a block boundary, so the wrapper DEFINITION (whose `(`
  980. // is followed by `… ) {`) never matches. Multi-line tolerant. (java/kotlin/swift)
  981. const RN_NATIVE_SENDEVENT_RE = /\bsendEvent\s*\([^;{}]*?"([^"]+)"/g;
  982. function rnEventEdges(ctx: ResolutionContext): Edge[] {
  983. // Native dispatchers (source = the native method whose body sends the
  984. // event) and JS handlers (target = the function/method registered as
  985. // the listener) keyed by event name.
  986. const nativeDispatchersByEvent = new Map<string, Set<string>>();
  987. const jsHandlersByEvent = new Map<string, Map<string, string>>();
  988. for (const file of ctx.getAllFiles()) {
  989. const content = ctx.readFile(file);
  990. if (!content) continue;
  991. const nodesInFile = ctx.getNodesInFile(file);
  992. const lineOf = (idx: number) => content.slice(0, idx).split('\n').length;
  993. const addDispatcher = (event: string, line: number) => {
  994. const disp = enclosingFn(nodesInFile, line);
  995. if (!disp) return;
  996. const set = nativeDispatchersByEvent.get(event) ?? new Set<string>();
  997. set.add(disp.id);
  998. nativeDispatchersByEvent.set(event, set);
  999. };
  1000. // ObjC side: `sendEventWithName:@"X"` only fires inside `.m`/`.mm`
  1001. // files (RCTEventEmitter subclasses).
  1002. if (file.endsWith('.m') || file.endsWith('.mm')) {
  1003. RN_OBJC_SEND_RE.lastIndex = 0;
  1004. let m: RegExpExecArray | null;
  1005. while ((m = RN_OBJC_SEND_RE.exec(content))) {
  1006. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1007. }
  1008. }
  1009. // Swift side: same RCTEventEmitter method, parens/named-args syntax.
  1010. if (file.endsWith('.swift')) {
  1011. RN_SWIFT_SEND_RE.lastIndex = 0;
  1012. let m: RegExpExecArray | null;
  1013. while ((m = RN_SWIFT_SEND_RE.exec(content))) {
  1014. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1015. }
  1016. RN_NATIVE_SENDEVENT_RE.lastIndex = 0;
  1017. while ((m = RN_NATIVE_SENDEVENT_RE.exec(content))) {
  1018. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1019. }
  1020. }
  1021. // JVM side: `.emit("X", …)` in Java/Kotlin, plus the common
  1022. // `sendEvent(ctx, "X", body)` wrapper. (We pattern-match anywhere in the
  1023. // file; the JS in-language path uses a separate emitter object pattern and
  1024. // is already handled by eventEmitterEdges.)
  1025. if (file.endsWith('.java') || file.endsWith('.kt')) {
  1026. let m: RegExpExecArray | null;
  1027. RN_JVM_EMIT_RE.lastIndex = 0;
  1028. while ((m = RN_JVM_EMIT_RE.exec(content))) {
  1029. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1030. }
  1031. RN_NATIVE_SENDEVENT_RE.lastIndex = 0;
  1032. while ((m = RN_NATIVE_SENDEVENT_RE.exec(content))) {
  1033. if (m[1]) addDispatcher(m[1], lineOf(m.index));
  1034. }
  1035. }
  1036. // JS subscribers (.addListener("X", handler)). Restrict to JS-family
  1037. // files so a native file's `addListener:` (the ObjC method) doesn't
  1038. // get mistaken for a JS subscription — they're entirely different
  1039. // things despite sharing a name.
  1040. if (
  1041. file.endsWith('.js') ||
  1042. file.endsWith('.jsx') ||
  1043. file.endsWith('.ts') ||
  1044. file.endsWith('.tsx') ||
  1045. file.endsWith('.mjs') ||
  1046. file.endsWith('.cjs')
  1047. ) {
  1048. // Match BOTH the named-handler form (`.addListener('x', fn)`) and
  1049. // an unnamed-handler form (`.addListener('x', listener)` where
  1050. // `listener` is a parameter — common in RN wrapper APIs like
  1051. // RNFirebase's `messaging().onMessageReceived(listener)`). For the
  1052. // unnamed case we attribute the subscription to the ENCLOSING JS
  1053. // function (the abstraction layer), giving a reachability-correct
  1054. // hop even when the actual user-side handler lives one call up.
  1055. const ADDLISTENER_ANY = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*([A-Za-z_][\w.]*)/g;
  1056. ADDLISTENER_ANY.lastIndex = 0;
  1057. let m: RegExpExecArray | null;
  1058. while ((m = ADDLISTENER_ANY.exec(content))) {
  1059. const event = m[1];
  1060. const arg = m[2];
  1061. if (!event || !arg) continue;
  1062. const bareName = arg.includes('.') ? arg.slice(arg.lastIndexOf('.') + 1) : arg;
  1063. // Try a named-symbol match first (matches the in-language semantic).
  1064. const namedHandler = ctx
  1065. .getNodesByName(bareName)
  1066. .find((n) => n.kind === 'function' || n.kind === 'method');
  1067. let targetId: string | null = namedHandler?.id ?? null;
  1068. if (!targetId) {
  1069. // Fall back to the enclosing function — the subscribe-wrapper
  1070. // pattern means the event fires THROUGH this function on its
  1071. // way to user code. Reachability-correct attribution.
  1072. const enclosing = enclosingFn(nodesInFile, lineOf(m.index));
  1073. targetId = enclosing?.id ?? null;
  1074. }
  1075. if (!targetId) {
  1076. // Broader fallback for JS object-literal API shape
  1077. // (`const Foo = { watchX(...) { … addListener(...) … } }`):
  1078. // method shorthand inside an object literal isn't extracted
  1079. // as a method node, so enclosingFn returns null. Attribute to
  1080. // the smallest enclosing `constant` / `variable` node — that's
  1081. // the API surface a downstream caller would `import` and
  1082. // invoke. Reachability-correct.
  1083. const line = lineOf(m.index);
  1084. let smallest: typeof nodesInFile[number] | null = null;
  1085. for (const n of nodesInFile) {
  1086. if (n.kind !== 'constant' && n.kind !== 'variable') continue;
  1087. const end = n.endLine ?? n.startLine;
  1088. if (n.startLine <= line && end >= line) {
  1089. if (!smallest || n.startLine >= smallest.startLine) smallest = n;
  1090. }
  1091. }
  1092. targetId = smallest?.id ?? null;
  1093. }
  1094. if (!targetId) continue;
  1095. const map = jsHandlersByEvent.get(event) ?? new Map<string, string>();
  1096. map.set(targetId, `${file}:${lineOf(m.index)}`);
  1097. jsHandlersByEvent.set(event, map);
  1098. }
  1099. }
  1100. }
  1101. const edges: Edge[] = [];
  1102. const seen = new Set<string>();
  1103. for (const [event, dispatchers] of nativeDispatchersByEvent) {
  1104. const handlers = jsHandlersByEvent.get(event);
  1105. if (!handlers) continue;
  1106. // Same fan-out guard as the in-language channel: generic event names
  1107. // (e.g. 'change', 'error', 'data') with many handlers/dispatchers
  1108. // can't be matched precisely without receiver-type info.
  1109. if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue;
  1110. for (const d of dispatchers) {
  1111. for (const [h, registeredAt] of handlers) {
  1112. if (d === h) continue;
  1113. const key = `${d}>${h}`;
  1114. if (seen.has(key)) continue;
  1115. seen.add(key);
  1116. edges.push({
  1117. source: d,
  1118. target: h,
  1119. kind: 'calls',
  1120. provenance: 'heuristic',
  1121. metadata: { synthesizedBy: 'rn-event-channel', event, registeredAt },
  1122. });
  1123. }
  1124. }
  1125. }
  1126. return edges;
  1127. }
  1128. /**
  1129. * Phase 6 — React Native Fabric/Codegen view component bridge.
  1130. *
  1131. * The Fabric framework extractor (`frameworks/fabric.ts`) emits
  1132. * `component` nodes named after the JS-visible component (e.g.
  1133. * `RNSScreenStack`) from each `codegenNativeComponent<Props>('Name')`
  1134. * spec declaration. The native implementation lives in an ObjC++/.mm or
  1135. * Kotlin/Java class whose name follows one of RN's conventions:
  1136. *
  1137. * - Exact: `RNSScreenStack`
  1138. * - With suffix: `RNSScreenStackView`, `RNSScreenStackViewManager`,
  1139. * `RNSScreenStackComponentView`, `RNSScreenStackManager`
  1140. *
  1141. * This synthesizer walks every Fabric component node and looks for a
  1142. * native class matching one of those names; when found, emits a
  1143. * `calls` edge `component → native class` (provenance `'heuristic'`,
  1144. * `synthesizedBy:'fabric-native-impl'`) so trace from JSX usage of the
  1145. * component continues into native.
  1146. *
  1147. * The convention-based suffix lookup is precise: there's no name
  1148. * collision in RN view-manager codebases by design (Codegen output would
  1149. * conflict otherwise).
  1150. */
  1151. const FABRIC_NATIVE_SUFFIXES = ['', 'View', 'ViewManager', 'ComponentView', 'Manager'];
  1152. /**
  1153. * Expo Modules cross-platform pairing. An Expo Module exposes the SAME
  1154. * JS-visible method (`AsyncFunction("getBatteryLevelAsync")`) from BOTH an iOS
  1155. * (Swift) and an Android (Kotlin) implementation. A JS callsite name-resolves to
  1156. * only ONE of them, so the other platform's impl looked like nothing called it
  1157. * (and editing it showed no blast radius). Link the iOS and Android impls of the
  1158. * same `<module>.<method>` to each other (both directions), so a JS call that
  1159. * reaches one platform reaches the other, and editing either surfaces the JS
  1160. * caller. The Expo method nodes are id-prefixed `expo-module:` and qualified
  1161. * `<file>::<module>.<method>` by the framework extractor.
  1162. */
  1163. function expoCrossPlatformEdges(queries: QueryBuilder): Edge[] {
  1164. const edges: Edge[] = [];
  1165. const seen = new Set<string>();
  1166. const byKey = new Map<string, Node[]>();
  1167. for (const m of queries.getNodesByKind('method')) {
  1168. if (!m.id.startsWith('expo-module:')) continue;
  1169. const key = m.qualifiedName.split('::').pop(); // `<module>.<method>`
  1170. if (!key) continue;
  1171. const arr = byKey.get(key);
  1172. if (arr) arr.push(m);
  1173. else byKey.set(key, [m]);
  1174. }
  1175. for (const group of byKey.values()) {
  1176. if (group.length < 2) continue;
  1177. for (const a of group) {
  1178. for (const b of group) {
  1179. if (a.id === b.id || a.language === b.language) continue; // cross-platform only
  1180. const key = `${a.id}>${b.id}`;
  1181. if (seen.has(key)) continue;
  1182. seen.add(key);
  1183. edges.push({
  1184. source: a.id,
  1185. target: b.id,
  1186. kind: 'calls',
  1187. line: a.startLine,
  1188. provenance: 'heuristic',
  1189. metadata: { synthesizedBy: 'expo-cross-platform', via: a.name },
  1190. });
  1191. }
  1192. }
  1193. }
  1194. return edges;
  1195. }
  1196. /**
  1197. * Classic React Native NativeModules cross-platform pairing. A native module
  1198. * method (`@ReactMethod` on Android, `RCT_EXPORT_METHOD` on iOS) is implemented
  1199. * on BOTH platforms, but a JS callsite name-resolves to only ONE — so the other
  1200. * platform's impl looked like nothing called it. A native method that HAS a JS
  1201. * caller is a confirmed bridge method; link it to the same-named native method
  1202. * in another language (the other platform's impl) so a JS call reaching one
  1203. * platform reaches the other, and editing either surfaces the JS caller.
  1204. *
  1205. * Names are normalized to the first selector keyword (`getFreeDiskStorage:` →
  1206. * `getFreeDiskStorage`) — that's the JS-visible name, and how the iOS selector
  1207. * lines up with the bare Android method name.
  1208. */
  1209. function rnCrossPlatformEdges(queries: QueryBuilder): Edge[] {
  1210. const edges: Edge[] = [];
  1211. const seen = new Set<string>();
  1212. const NATIVE = new Set(['java', 'kotlin', 'objc', 'cpp']);
  1213. const JS = new Set(['typescript', 'tsx', 'javascript', 'jsx']);
  1214. // RN module INFRASTRUCTURE methods exist on every native module (called by the
  1215. // RN runtime, not user JS), so pairing them by name would cross-link unrelated
  1216. // modules in a multi-module repo. Skip them — they aren't user-facing methods.
  1217. const RN_INFRA = new Set([
  1218. 'addListener', 'removeListeners', 'getConstants', 'constantsToExport', 'getName',
  1219. 'invalidate', 'initialize', 'getDefaultEventTypes', 'supportedEvents',
  1220. 'requiresMainQueueSetup', 'methodQueue',
  1221. ]);
  1222. const norm = (name: string): string => {
  1223. const i = name.indexOf(':');
  1224. return i >= 0 ? name.slice(0, i) : name;
  1225. };
  1226. // Index native methods by their JS-visible (normalized) name. Only names with
  1227. // impls in ≥2 native languages can pair, so the per-method JS-caller check
  1228. // below only runs for genuine cross-platform candidates.
  1229. const byName = new Map<string, Node[]>();
  1230. for (const m of queries.iterateNodesByKind('method')) {
  1231. if (!NATIVE.has(m.language)) continue;
  1232. const key = norm(m.name);
  1233. const arr = byName.get(key);
  1234. if (arr) arr.push(m);
  1235. else byName.set(key, [m]);
  1236. }
  1237. for (const [groupName, group] of byName) {
  1238. if (RN_INFRA.has(groupName)) continue;
  1239. const langs = new Set(group.map((m) => m.language));
  1240. if (langs.size < 2) continue; // single-platform — nothing to pair
  1241. for (const m of group) {
  1242. // Is m a bridge method? (a JS-language `calls` edge points at it)
  1243. const incoming = queries.getIncomingEdges(m.id, ['calls']);
  1244. if (incoming.length === 0) continue;
  1245. const sources = queries.getNodesByIds(incoming.map((e) => e.source));
  1246. const isBridge = incoming.some((e) => {
  1247. const s = sources.get(e.source);
  1248. return !!s && JS.has(s.language);
  1249. });
  1250. if (!isBridge) continue;
  1251. // Link to the other-platform impls (both directions).
  1252. for (const sib of group) {
  1253. if (sib.id === m.id || sib.language === m.language) continue;
  1254. for (const [a, b] of [[m, sib], [sib, m]] as const) {
  1255. const key = `${a.id}>${b.id}`;
  1256. if (seen.has(key)) continue;
  1257. seen.add(key);
  1258. edges.push({
  1259. source: a.id,
  1260. target: b.id,
  1261. kind: 'calls',
  1262. line: a.startLine,
  1263. provenance: 'heuristic',
  1264. metadata: { synthesizedBy: 'rn-cross-platform', via: norm(m.name) },
  1265. });
  1266. }
  1267. }
  1268. }
  1269. }
  1270. return edges;
  1271. }
  1272. function fabricNativeImplEdges(ctx: ResolutionContext): Edge[] {
  1273. const edges: Edge[] = [];
  1274. const seen = new Set<string>();
  1275. // The Fabric extractor IDs are prefixed `fabric-component:` so we can
  1276. // filter to just those without iterating all `component` nodes.
  1277. const components = ctx.getNodesByKind('component').filter((n) => n.id.startsWith('fabric-component:'));
  1278. if (components.length === 0) return edges;
  1279. // Pre-index native classes by name for O(1) lookup.
  1280. const nativeClassesByName = new Map<string, Node[]>();
  1281. for (const n of ctx.getNodesByKind('class')) {
  1282. if (n.language !== 'objc' && n.language !== 'kotlin' && n.language !== 'java' && n.language !== 'cpp') continue;
  1283. const arr = nativeClassesByName.get(n.name);
  1284. if (arr) arr.push(n);
  1285. else nativeClassesByName.set(n.name, [n]);
  1286. }
  1287. for (const component of components) {
  1288. for (const suffix of FABRIC_NATIVE_SUFFIXES) {
  1289. const candidate = component.name + suffix;
  1290. const matches = nativeClassesByName.get(candidate);
  1291. if (!matches || matches.length === 0) continue;
  1292. // Link the component node to every matching native class (iOS +
  1293. // Android each have one).
  1294. for (const native of matches) {
  1295. const key = `${component.id}>${native.id}`;
  1296. if (seen.has(key)) continue;
  1297. seen.add(key);
  1298. edges.push({
  1299. source: component.id,
  1300. target: native.id,
  1301. kind: 'calls',
  1302. provenance: 'heuristic',
  1303. metadata: {
  1304. synthesizedBy: 'fabric-native-impl',
  1305. viaSuffix: suffix || '(exact)',
  1306. componentName: component.name,
  1307. },
  1308. });
  1309. }
  1310. }
  1311. }
  1312. return edges;
  1313. }
  1314. /**
  1315. * MyBatis: link a Java mapper interface method to the XML statement that holds
  1316. * its SQL. The XML extractor (`src/extraction/mybatis-extractor.ts`) qualifies
  1317. * each `<select|insert|update|delete|sql id="X">` as `<namespace>::<id>` where
  1318. * `<namespace>` is the Java FQN of the mapper interface. A Java method's
  1319. * qualifiedName ends with `<ClassName>::<methodName>`, so we suffix-match the
  1320. * last two segments of the XML qualified name to find a unique Java method by
  1321. * `<ClassName>::<methodName>` (`ClassName` = last dotted segment of the XML
  1322. * namespace). Cross-mapper `<include refid="other.X">` references go through
  1323. * the normal qualified-name resolver — only the Java↔XML bridge is synthetic.
  1324. *
  1325. * Precision over recall: ambiguous mappers (multiple Java classes with the
  1326. * same simple name) are dropped. We need-not bridge by package because Java
  1327. * mapper interfaces are typically uniquely named within a project.
  1328. */
  1329. function mybatisJavaXmlEdges(queries: QueryBuilder): Edge[] {
  1330. const edges: Edge[] = [];
  1331. const seen = new Set<string>();
  1332. // Index Java methods by `<ClassName>::<methodName>` for O(1) lookup.
  1333. const javaIndex = new Map<string, Node[]>();
  1334. for (const m of queries.iterateNodesByKind('method')) {
  1335. if (m.language !== 'java' && m.language !== 'kotlin') continue;
  1336. const parts = m.qualifiedName.split('::');
  1337. const last = parts[parts.length - 1];
  1338. const cls = parts[parts.length - 2];
  1339. if (!last || !cls) continue;
  1340. const key = `${cls}::${last}`;
  1341. const arr = javaIndex.get(key);
  1342. if (arr) arr.push(m); else javaIndex.set(key, [m]);
  1343. }
  1344. for (const xml of queries.iterateNodesByKind('method')) {
  1345. if (xml.language !== 'xml') continue;
  1346. // Qualified name: `<namespace>::<id>`. Extract the simple class name.
  1347. const colonIdx = xml.qualifiedName.lastIndexOf('::');
  1348. if (colonIdx < 0) continue;
  1349. const namespace = xml.qualifiedName.slice(0, colonIdx);
  1350. const id = xml.qualifiedName.slice(colonIdx + 2);
  1351. if (!namespace || !id) continue;
  1352. const dotIdx = namespace.lastIndexOf('.');
  1353. const className = dotIdx >= 0 ? namespace.slice(dotIdx + 1) : namespace;
  1354. const candidates = javaIndex.get(`${className}::${id}`);
  1355. if (!candidates || candidates.length === 0) continue;
  1356. // Drop ambiguous matches (multiple same-name classes); the user can
  1357. // disambiguate by adding the package-suffix match in a future enhancement.
  1358. if (candidates.length > 1) continue;
  1359. const java = candidates[0]!;
  1360. const key = `${java.id}>${xml.id}`;
  1361. if (seen.has(key)) continue;
  1362. seen.add(key);
  1363. edges.push({
  1364. source: java.id,
  1365. target: xml.id,
  1366. kind: 'calls',
  1367. line: java.startLine,
  1368. provenance: 'heuristic',
  1369. metadata: {
  1370. synthesizedBy: 'mybatis-java-xml',
  1371. via: `${className}.${id}`,
  1372. registeredAt: `${xml.filePath}:${xml.startLine}`,
  1373. },
  1374. });
  1375. }
  1376. return edges;
  1377. }
  1378. /**
  1379. * Gin middleware chain. Gin runs its entire handler chain through one dynamic
  1380. * line in `(*Context).Next`:
  1381. * for c.index < len(c.handlers) { c.handlers[c.index](c); c.index++ }
  1382. * `c.handlers` is a `HandlersChain` (`[]HandlerFunc`) assembled at registration
  1383. * time by `combineHandlers` from the funcs passed to `r.Use(...)` /
  1384. * `r.GET("/path", h...)` / `r.Handle(...)`. Because the call is a computed index
  1385. * into a runtime-built slice, tree-sitter resolves `c.handlers[c.index](c)` to
  1386. * NOTHING — so `callees(Next)` is just the `len()` helper and the flow
  1387. * `ServeHTTP → handleHTTPRequest → Next` dead-ends at the exact symbol the
  1388. * "how do requests flow through the middleware chain" question is about. The
  1389. * agent then re-queries Next and falls back to Read/grep (validated: the gin
  1390. * WITH-arm rabbit-holed on precisely this dead-end).
  1391. *
  1392. * Bridge it: find the chain DISPATCHER (a Go method whose body invokes a
  1393. * `handlers` slice by index) and link it → every HandlerFunc registered via a
  1394. * gin registration call, so `callees(Next)` and `trace(ServeHTTP, <handler>)`
  1395. * connect end-to-end. Named handlers only (`gin.Logger()` → `Logger`,
  1396. * `authMiddleware`); inline closures are anonymous and skipped. Like
  1397. * react-render / interface-impl this is a deliberate over-approximation —
  1398. * reachability-correct (any registered handler CAN run for some route), capped,
  1399. * and gated on the dispatcher existing so it never runs on non-gin Go repos.
  1400. * Provenance `heuristic`, `synthesizedBy:'gin-middleware-chain'`; `registeredAt`
  1401. * is the `.Use`/`.GET` site an agent would otherwise grep for.
  1402. */
  1403. const GIN_DISPATCH_RE = /\.handlers\s*\[[^\]]*\]\s*\(/; // c.handlers[c.index](c)
  1404. const GIN_REG_RE = /\.(?:Use|GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Any|Handle)\s*\(/g;
  1405. /** Balanced `(...)` body starting at the '(' index; null if unbalanced. */
  1406. function goBalancedArgs(s: string, openIdx: number): string | null {
  1407. let depth = 0;
  1408. for (let i = openIdx; i < s.length; i++) {
  1409. const c = s[i];
  1410. if (c === '(') depth++;
  1411. else if (c === ')') { depth--; if (depth === 0) return s.slice(openIdx + 1, i); }
  1412. }
  1413. return null;
  1414. }
  1415. /** Split a top-level comma list, respecting nested () [] {}. */
  1416. function goSplitArgs(args: string): string[] {
  1417. const out: string[] = [];
  1418. let depth = 0, cur = '';
  1419. for (const c of args) {
  1420. if (c === '(' || c === '[' || c === '{') { depth++; cur += c; }
  1421. else if (c === ')' || c === ']' || c === '}') { depth--; cur += c; }
  1422. else if (c === ',' && depth === 0) { out.push(cur); cur = ''; }
  1423. else cur += c;
  1424. }
  1425. if (cur.trim()) out.push(cur);
  1426. return out;
  1427. }
  1428. /** Tail ident of a handler arg: `gin.Logger()`→`Logger`, `mw`→`mw`; null for string paths / closures. */
  1429. function goHandlerIdent(expr: string): string | null {
  1430. const cleaned = expr.trim().replace(/\(\s*\)$/, ''); // drop a trailing call ()
  1431. if (!cleaned || cleaned.startsWith('"') || cleaned.startsWith('`') || cleaned.startsWith('func')) return null;
  1432. const m = cleaned.match(/(?:\.|^)([A-Za-z_]\w*)$/);
  1433. return m ? m[1]! : null;
  1434. }
  1435. function ginMiddlewareChainEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  1436. // 1. Find the chain dispatcher(s): a Go method that invokes a `handlers` slice by index.
  1437. const dispatchers: Node[] = [];
  1438. for (const n of queries.iterateNodesByKind('method')) {
  1439. if (n.language !== 'go') continue;
  1440. const content = ctx.readFile(n.filePath);
  1441. const src = content && sliceLines(content, n.startLine, n.endLine);
  1442. if (src && GIN_DISPATCH_RE.test(src)) dispatchers.push(n);
  1443. }
  1444. if (dispatchers.length === 0) return []; // not a gin repo — bail
  1445. // 2. Collect handler identifiers registered via gin registration calls
  1446. // (.Use / .GET / … / .Handle). String args (paths/methods) and inline
  1447. // closures are dropped by goHandlerIdent; the rest are HandlerFuncs.
  1448. const registered = new Map<string, string>(); // name → registeredAt (file:line)
  1449. for (const file of ctx.getAllFiles()) {
  1450. if (!file.endsWith('.go')) continue;
  1451. const content = ctx.readFile(file);
  1452. if (!content || (!content.includes('.Use(') && !/\.(?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Any|Handle)\(/.test(content))) continue;
  1453. const safe = stripCommentsForRegex(content, 'go');
  1454. GIN_REG_RE.lastIndex = 0;
  1455. let m: RegExpExecArray | null;
  1456. while ((m = GIN_REG_RE.exec(safe))) {
  1457. const parenIdx = m.index + m[0].length - 1;
  1458. const argStr = goBalancedArgs(safe, parenIdx);
  1459. if (!argStr) continue;
  1460. const line = safe.slice(0, m.index).split('\n').length;
  1461. for (const arg of goSplitArgs(argStr)) {
  1462. const name = goHandlerIdent(arg);
  1463. if (name && !registered.has(name)) registered.set(name, `${file}:${line}`);
  1464. }
  1465. }
  1466. }
  1467. if (registered.size === 0) return [];
  1468. // 3. Link each dispatcher → each registered handler node (dedup, capped).
  1469. const edges: Edge[] = [];
  1470. const seen = new Set<string>();
  1471. for (const disp of dispatchers) {
  1472. let added = 0;
  1473. for (const [name, registeredAt] of registered) {
  1474. if (added >= MAX_CALLBACKS_PER_CHANNEL) break;
  1475. const handler = ctx.getNodesByName(name).find(
  1476. (n) => (n.kind === 'function' || n.kind === 'method') && n.language === 'go'
  1477. );
  1478. if (!handler || handler.id === disp.id) continue;
  1479. const key = `${disp.id}>${handler.id}`;
  1480. if (seen.has(key)) continue;
  1481. seen.add(key);
  1482. edges.push({
  1483. source: disp.id, target: handler.id, kind: 'calls', line: disp.startLine,
  1484. provenance: 'heuristic',
  1485. metadata: { synthesizedBy: 'gin-middleware-chain', via: name, registeredAt },
  1486. });
  1487. added++;
  1488. }
  1489. }
  1490. return edges;
  1491. }
  1492. /**
  1493. * Delphi form code-behind: a form unit `UFRMAbout.pas` owns its visual form
  1494. * definition `UFRMAbout.dfm` (VCL) / `.fmx` (FireMonkey) — paired by basename in
  1495. * the same directory, wired by the `{$R *.dfm}` directive rather than a `uses`
  1496. * clause. Link the unit → its form so a `.dfm`/`.fmx` used only as a form
  1497. * definition isn't orphaned, and editing the form surfaces its code-behind unit.
  1498. */
  1499. function pascalFormEdges(ctx: ResolutionContext): Edge[] {
  1500. const edges: Edge[] = [];
  1501. const allFiles = new Set(ctx.getAllFiles());
  1502. for (const file of allFiles) {
  1503. if (!/\.(dfm|fmx)$/i.test(file)) continue;
  1504. const pasFile = file.replace(/\.(dfm|fmx)$/i, '.pas');
  1505. if (!allFiles.has(pasFile)) continue;
  1506. const formNode = ctx.getNodesInFile(file).find((n) => n.kind === 'file');
  1507. const unitNode = ctx.getNodesInFile(pasFile).find((n) => n.kind === 'file');
  1508. if (!formNode || !unitNode) continue;
  1509. edges.push({
  1510. source: unitNode.id,
  1511. target: formNode.id,
  1512. kind: 'references',
  1513. line: unitNode.startLine,
  1514. provenance: 'heuristic',
  1515. metadata: { synthesizedBy: 'pascal-form', registeredAt: pasFile },
  1516. });
  1517. }
  1518. return edges;
  1519. }
  1520. /**
  1521. * SvelteKit file-convention data flow. A route directory's `+page.svelte` (a
  1522. * `component` node) receives its `data` from the sibling `+page.server.{ts,js}`
  1523. * / `+page.{ts,js}` `load` function and posts forms to its `actions` — wired by
  1524. * the framework BY FILE PATH, with no static import between them. So editing a
  1525. * `load` shows no impact on the page it feeds, and the page looks like it has no
  1526. * server-side dependency. Link the page component to its sibling loader's
  1527. * `load` / `actions` (same for `+layout`). The pairing is path-deterministic
  1528. * (same directory, matching `+page`/`+layout` prefix), so it's precise — but
  1529. * it's a framework-convention edge, so provenance stays `heuristic`.
  1530. *
  1531. * Direction: page → load, so `getImpactRadius(load)` surfaces the page (editing
  1532. * a loader's data shows the page it feeds) and the page's dependencies include
  1533. * its loader.
  1534. */
  1535. function svelteKitLoadEdges(ctx: ResolutionContext): Edge[] {
  1536. const edges: Edge[] = [];
  1537. const allFiles = new Set(ctx.getAllFiles());
  1538. const HOOKS = new Set(['load', 'actions']);
  1539. const HOOK_KINDS = new Set(['function', 'method', 'constant', 'variable']);
  1540. for (const file of allFiles) {
  1541. const m = file.match(/(.*\/)(\+(?:page|layout))\.svelte$/);
  1542. if (!m) continue;
  1543. const dir = m[1]!;
  1544. const prefix = m[2]!;
  1545. const page = ctx.getNodesInFile(file).find((n) => n.kind === 'component');
  1546. if (!page) continue;
  1547. for (const ext of ['.server.ts', '.server.js', '.ts', '.js']) {
  1548. const loaderFile = `${dir}${prefix}${ext}`;
  1549. if (!allFiles.has(loaderFile)) continue;
  1550. for (const hook of ctx.getNodesInFile(loaderFile)) {
  1551. if (!HOOK_KINDS.has(hook.kind) || !HOOKS.has(hook.name)) continue;
  1552. edges.push({
  1553. source: page.id,
  1554. target: hook.id,
  1555. kind: 'references',
  1556. line: page.startLine,
  1557. provenance: 'heuristic',
  1558. metadata: {
  1559. synthesizedBy: 'sveltekit-load',
  1560. via: hook.name,
  1561. registeredAt: `${loaderFile}:${hook.startLine ?? 0}`,
  1562. },
  1563. });
  1564. }
  1565. }
  1566. }
  1567. return edges;
  1568. }
  1569. /**
  1570. * Redux-thunk dispatch chain. `export const X = createAsyncThunk(prefix, async (a, api) => {...})`
  1571. * (or a wrapper like trezor's `createThunk(...)`) passes the async body as an ARGUMENT, so
  1572. * tree-sitter never extracts it as a function node: `X` is a `constant` whose body's calls are
  1573. * ORPHANED. The `dispatch(nextThunk(...))` calls that drive a thunk chain forward therefore produce
  1574. * no edges, so `callees(X)` is empty and a flow `dispatch(X(...)) → X → nextThunk` dead-ends at the
  1575. * constant (validated on trezor-suite: the signXxxThunk constants had ZERO outgoing edges). Bridge
  1576. * it: body-scan each thunk constant for `dispatch(Y(...))` and link `X → Y`, so the dispatch chain
  1577. * connects. High-precision — the `dispatch(` keyword plus `Y` must resolve to a function/constant/
  1578. * method node; capped; gated on thunk constants existing so it never runs on non-RTK repos.
  1579. * Cross-file by design (a suite thunk dispatches a wallet-core thunk). Provenance `heuristic`,
  1580. * `synthesizedBy:'redux-thunk'`; `registeredAt` is the dispatch site.
  1581. */
  1582. const THUNK_DECL_RE = /create(?:Async)?Thunk/;
  1583. const THUNK_DISPATCH_RE = /\bdispatch\s*\(\s*([A-Za-z_]\w*)\s*[(),]/g;
  1584. const THUNK_FANOUT_CAP = 24;
  1585. function reduxThunkEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
  1586. const edges: Edge[] = [];
  1587. const seen = new Set<string>();
  1588. for (const node of queries.iterateNodesByKind('constant')) {
  1589. // Cheap gate: the initializer (captured in `signature`) must be a create(Async)Thunk call —
  1590. // avoids reading every constant's body on a large repo.
  1591. if (!node.signature || !THUNK_DECL_RE.test(node.signature)) continue;
  1592. const content = ctx.readFile(node.filePath);
  1593. const src = content && sliceLines(content, node.startLine, node.endLine);
  1594. if (!src) continue;
  1595. // Thunks are TS/JS-family (same // and /* */ comment syntax); map to a CommentLang.
  1596. const safe = stripCommentsForRegex(src, node.language === 'javascript' || node.language === 'jsx' ? 'javascript' : 'typescript');
  1597. THUNK_DISPATCH_RE.lastIndex = 0;
  1598. let m: RegExpExecArray | null;
  1599. let added = 0;
  1600. while ((m = THUNK_DISPATCH_RE.exec(safe)) && added < THUNK_FANOUT_CAP) {
  1601. const name = m[1]!;
  1602. if (name === node.name) continue; // self-dispatch (recursive thunk) — skip
  1603. const target = ctx
  1604. .getNodesByName(name)
  1605. .find((n) => n.kind === 'constant' || n.kind === 'function' || n.kind === 'method');
  1606. if (!target || target.id === node.id) continue;
  1607. const key = `${node.id}>${target.id}`;
  1608. if (seen.has(key)) continue;
  1609. seen.add(key);
  1610. const line = node.startLine + safe.slice(0, m.index).split('\n').length - 1;
  1611. edges.push({
  1612. source: node.id,
  1613. target: target.id,
  1614. kind: 'calls',
  1615. line,
  1616. provenance: 'heuristic',
  1617. metadata: { synthesizedBy: 'redux-thunk', via: name, registeredAt: `${node.filePath}:${line}` },
  1618. });
  1619. added++;
  1620. }
  1621. }
  1622. return edges;
  1623. }
  1624. /**
  1625. * Synthesize dispatcher→callback edges (field observers + EventEmitters +
  1626. * React re-render + JSX children + Vue templates + SvelteKit load + RN event
  1627. * channel + Fabric native-impl + MyBatis Java↔XML + Gin middleware chain +
  1628. * Redux-thunk dispatch chain).
  1629. * Returns the count added. Never throws into indexing — callers wrap in try/catch.
  1630. */
  1631. export function synthesizeCallbackEdges(queries: QueryBuilder, ctx: ResolutionContext): number {
  1632. // Cross-file Go method→type `contains` edges must be synthesized AND persisted
  1633. // FIRST: a method declared in a different file from its receiver type is
  1634. // otherwise orphaned from the struct, and goImplementsEdges (next) derives a
  1635. // struct's method set from its `contains` edges — so without this it would
  1636. // under-count the interfaces a cross-file struct satisfies. (#583)
  1637. const goMethodContains = goCrossFileMethodContainsEdges(queries);
  1638. if (goMethodContains.length > 0) queries.insertEdges(goMethodContains);
  1639. // Go implicit `implements` edges must be synthesized AND persisted next: the
  1640. // interface-dispatch bridge below reads `implements` edges from the DB, and
  1641. // Go has none statically. (Other languages already have static implements
  1642. // edges from extraction, so they don't need this pre-pass.)
  1643. const goImpl = goImplementsEdges(queries);
  1644. if (goImpl.length > 0) queries.insertEdges(goImpl);
  1645. const fieldEdges = fieldChannelEdges(queries, ctx);
  1646. const closureCollEdges = closureCollectionEdges(queries, ctx);
  1647. const emitterEdges = eventEmitterEdges(ctx);
  1648. const renderEdges = reactRenderEdges(queries, ctx);
  1649. const jsxEdges = reactJsxChildEdges(ctx);
  1650. const vueEdges = vueTemplateEdges(ctx);
  1651. const svelteKitEdges = svelteKitLoadEdges(ctx);
  1652. const pascalEdges = pascalFormEdges(ctx);
  1653. const flutterEdges = flutterBuildEdges(queries, ctx);
  1654. const cppEdges = cppOverrideEdges(queries);
  1655. const ifaceEdges = interfaceOverrideEdges(queries);
  1656. const kotlinExpectActual = kotlinExpectActualEdges(queries);
  1657. const goGrpcEdges = goGrpcStubImplEdges(queries);
  1658. const rnEventEdgesList = rnEventEdges(ctx);
  1659. const fabricNativeEdges = fabricNativeImplEdges(ctx);
  1660. const expoXPlatEdges = expoCrossPlatformEdges(queries);
  1661. const rnXPlatEdges = rnCrossPlatformEdges(queries);
  1662. const mybatisEdges = mybatisJavaXmlEdges(queries);
  1663. const ginEdges = ginMiddlewareChainEdges(queries, ctx);
  1664. const thunkEdges = reduxThunkEdges(queries, ctx);
  1665. const merged: Edge[] = [];
  1666. const seen = new Set<string>();
  1667. for (const e of [
  1668. ...fieldEdges,
  1669. ...closureCollEdges,
  1670. ...emitterEdges,
  1671. ...renderEdges,
  1672. ...jsxEdges,
  1673. ...vueEdges,
  1674. ...svelteKitEdges,
  1675. ...pascalEdges,
  1676. ...flutterEdges,
  1677. ...cppEdges,
  1678. ...ifaceEdges,
  1679. ...kotlinExpectActual,
  1680. ...goGrpcEdges,
  1681. ...rnEventEdgesList,
  1682. ...fabricNativeEdges,
  1683. ...expoXPlatEdges,
  1684. ...rnXPlatEdges,
  1685. ...mybatisEdges,
  1686. ...ginEdges,
  1687. ...thunkEdges,
  1688. ]) {
  1689. const key = `${e.source}>${e.target}`;
  1690. if (seen.has(key)) continue;
  1691. seen.add(key);
  1692. merged.push(e);
  1693. }
  1694. if (merged.length > 0) queries.insertEdges(merged);
  1695. return merged.length + goImpl.length + goMethodContains.length;
  1696. }