/** * Callback / observer edge synthesis — Phase 1 + 2. * * Closes dynamic-dispatch holes where a dispatcher invokes callbacks registered * elsewhere. Two channel shapes: * * (1) Field-backed observer (Phase 1): * onUpdate(cb) { this.callbacks.add(cb); } // registrar * triggerUpdate() { for (cb of this.callbacks) cb(); } // dispatcher * scene.onUpdate(this.triggerRender) // registration * → synthesize triggerUpdate → triggerRender * * (2) String-keyed EventEmitter (Phase 2): * this.on('mount', function onmount(){...}) // registration * fn.emit('mount', this) // dispatch * → synthesize (method containing emit('mount')) → onmount * * Whole-graph pass after base resolution. High-precision/low-recall by design: * named callbacks only; field channels paired by file+field; EventEmitter * channels capped by event fan-out (generic names like 'error' skipped — they * need receiver-type matching, deferred to Phase 3). All synthesized edges are * tagged `provenance:'heuristic'`. See docs/design/callback-edge-synthesis.md. */ import type { Edge, Language, Node, NodeKind } from '../types'; import { SynthSkips, SYNTH_SKIPS_VERSION, skipped, recordSkip } from './synth-skips'; import type { NodeScanFilter, QueryBuilder } from '../db/queries'; import type { ResolutionContext } from './types'; import { isGeneratedFile } from '../extraction/generated-detection'; import { stripCommentsForRegex, withStripMemo } from './strip-comments'; import { escapeRegExp } from '../utils'; import { cFnPointerDispatchEdges } from './c-fnptr-synthesizer'; import { goFuncFieldEdges } from './go-func-field-synthesizer'; import { drupalHookEdges } from './drupal-hook-synthesizer'; import { goframeRouteEdges } from './goframe-synthesizer'; import { expoRouterReturnEdges } from './expo-router-synthesizer'; import { nextLinkEdges } from './next-router-synthesizer'; import { reactRouterLinkEdges } from './react-router-synthesizer'; import { tanstackLinkEdges } from './tanstack-router-synthesizer'; import { vueRouterLinkEdges } from './vue-router-synthesizer'; import { angularTemplateEdges } from './angular-template-synthesizer'; import { svelteKitLinkEdges, svelteKitPageComponentEdges } from './sveltekit-synthesizer'; import { createYielder, type MaybeYield } from './cooperative-yield'; import { crossTierEdges, endpointNodesFor, hasCrossTierPattern, hasTestRequestPattern, testRequestEdges } from './tier-synthesizer'; import { enclosingFn, enclosingValue, makeLineAt, matchBalanced } from './synth-utils'; import { rnModuleMethods } from './frameworks/react-native'; import { resolveImportPath } from './import-resolver'; import { isDistinctiveIdentifier, isManualMockHiddenFrom, isManualMockPath, isTestPath } from '../search/query-utils'; import { crossesCodeBoundary, innermostBinding } from './gates'; import { cppSpecializationArguments } from './cpp-specializations'; import { goRefQualification } from './go-type-visibility'; import { goStdlibMethods } from './go-stdlib-methods'; import { overrideFilter } from './override-parameters'; import { declaredComponent, exportedComponent, wrappedComponentName } from './frameworks/react'; import { jsxCode } from './jsx-code'; import { goPackageReader, type GoPackageOf } from '../graph/go-package'; const REGISTRAR_NAME = /^(on[A-Z]\w*|subscribe|addListener|addEventListener|register|watch|listen|addCallback)$/; const DISPATCHER_NAME = /(emit|trigger|notify|dispatch|fire|publish|flush)/i; const MAX_CALLBACKS_PER_CHANNEL = 40; const EVENT_FANOUT_CAP = 6; // skip events with more handlers/dispatchers than this (too generic without type info) const ON_RE = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:(?:async\s+)?function\s+(\w+)|(?:this\.)?(\w+))/g; const EMIT_RE = /\.(?:emit|fire|dispatchEvent)\(\s*['"]([^'"]+)['"]/g; // Inline listeners — `.on('x', (e) => {…})`, `.on('x', e => …)`, // `.on('x', function () {…})` (incl. `async` forms). Anonymous handlers have // no node (extraction deliberately attributes an inline closure's calls to // its enclosing function), so the registration is attributed to that same // enclosing function — where the event's work demonstrably happens — or to // the smallest enclosing constant/variable for an object-literal API site // (the rn-event-channel cross-language arm already does exactly this). const ON_INLINE_RE = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:async\s+)?(?:\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>|function\s*\()/g; const SETSTATE_RE = /this\.setState\s*\(/; const FLUTTER_SETSTATE_RE = /\bsetState\s*\(/; // Flutter: setState((){…}) / this.setState const JS_FAMILY = ['typescript', 'javascript', 'tsx', 'jsx']; /** The languages that can write JSX: not TypeScript's `.ts` files. */ const JSX_FAMILY = ['tsx', 'jsx', 'javascript']; // A tag's name ends at whitespace, `/` or `>`, or at the `<` of the type // arguments a generic component's tag passes: ` // items={…} />` renders PaginatedList. The lookahead leaves that `<` to open // the next match, which `opensTag` reads as a type argument, not a tag. const JSX_TAG_RE = /<([A-Z][A-Za-z0-9_]*)(?=[\s/><])/g; const MAX_JSX_CHILDREN = 30; // A wrapper around a component — `styled(ActionButton)`, `memo(Button)`, // `forwardRef(Render)` — renders it without a tag (`wrappedComponentName`). const WRAPPER_CALL_RE = /\b(?:styled|memo|forwardRef)\s*\(\s*[A-Z]/; // Vue SFC templates: kebab-case child components ( → ElButton) and // event bindings (@click="fn" / v-on:click="fn"). PascalCase children () // are already caught by JSX_TAG_RE via the SFC component node. const VUE_KEBAB_RE = /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)[\s/>]/g; // PascalCase component tags — ``, ``. HTML elements are // lowercase, so an uppercase-initial tag is a component usage; built-ins // (``, ``) simply resolve to nothing and emit no edge. const VUE_PASCAL_RE = /<([A-Z][A-Za-z0-9]*)[\s/>]/g; const VUE_HANDLER_RE = /(?:@|v-on:)([a-zA-Z][\w-]*)(?:\.[\w]+)*\s*=\s*"([^"]+)"/g; // Composable/hook destructure: `const { close: closeSidebar } = useSidebarControl()`. // Captures the destructure body + the called composable; only `use*` calls qualify. const VUE_DESTRUCTURE_RE = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*(\w+)\s*\(/g; // Vue component registrations — a template tag resolves through the REGISTERED // name before the PascalCase guess: `app.component('fancy-widget', FancyThing)` // (global, Vue 3 entry / `Vue.component` in Vue 2 / `nuxtApp.vueApp` in Nuxt // plugins) and an SFC's own `components: { 'my-comp': MyComp }` (local, // options API). Both map a kebab name onto a component whose own name may be // spelled differently, which a kebab→Pascal lookup can never find. const VUE_APP_GATE_RE = /\bcreateApp\s*\(|\bVue\.component\s*\(|\.vueApp\b/; const VUE_APP_COMPONENT_RE = /(?:[\w$]+\s*\([^()]*\)|[\w$]+(?:\.[\w$]+)*)\s*\.\s*component\s*\(\s*['"]([^'"]+)['"]\s*,\s*(?:defineAsyncComponent\s*\(\s*)?(\(\s*\)\s*=>\s*import\s*\(\s*['"]([^'"]+)['"]|[A-Za-z_$][\w$]*)/g; const VUE_COMPONENTS_BLOCK_RE = /\bcomponents\s*:\s*\{/g; // Entries inside a `components: { … }` block: `'my-comp': Comp`, `myComp: Comp`, // `Comp` shorthand, or a lazy `x: () => import('./X.vue')` / // `x: defineAsyncComponent(() => import('./X.vue'))`. const VUE_COMP_ENTRY_RE = /(['"])([\w$-]+)\1\s*:\s*(?:(?:defineAsyncComponent\s*\(\s*)?\(\s*\)\s*=>\s*import\s*\(\s*['"]([^'"]+)['"]|([A-Za-z_$][\w$]*))|\b([A-Za-z_$][\w$]*)\s*:\s*(?:(?:defineAsyncComponent\s*\(\s*)?\(\s*\)\s*=>\s*import\s*\(\s*['"]([^'"]+)['"]|([A-Za-z_$][\w$]*))|\b([A-Za-z_$][\w$]*)\s*(?=[,}])/g; /** A tag's registration-key spellings — Vue's resolveAsset tries the raw name, its camelCase, its PascalCase, and its hyphenated form. */ function vueTagVariants(tag: string): string[] { const camel = tag.replace(/-([a-z0-9])/g, (_s, c: string) => c.toUpperCase()); const pascal = camel.charAt(0).toUpperCase() + camel.slice(1); const kebab = camel.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); return [...new Set([tag, camel, pascal, kebab])]; } // Closure-collection dynamic dispatch (language-agnostic, Swift-first). A method // appends a closure to a collection property; another method iterates that // property *invoking each element* (`coll.forEach { $0() }` / `{ it() }`). The // element-invoke (`$0(` / `it(`) PROVES the collection holds closures, so pairing // a dispatcher to same-named registrars (`.append`/`.add`/`.push`/`.insert`, // incl. Swift `prop.write { $0.append }`) is high-precision. Cross-file/class by // design: Alamofire appends in `DataRequest.validate` but iterates in the base // `Request.didCompleteTask` — neither same-file nor same-class pairing reaches it. const CC_DISPATCH_RE = /(\w+)\.forEach\s*\{\s*(?:\$0|it)\s*\(/g; const CC_APPEND_WRITE_RE = /(\w+)\.write\s*\{\s*\$0(?:\.(\w+))?\.(?:append|add|push|insert)\s*\(/g; const CC_APPEND_DIRECT_RE = /(\w+)\.(?:append|add|push|insert)\s*\(/g; const CC_FANOUT_CAP = 8; // skip a field name with more dispatchers/registrars than this (too generic to pair confidently) // The dispatcher gate — `{ $0( ` / `{ it( ` element-invocation — is Swift/Kotlin // trailing-closure syntax, so ONLY those languages can ever contribute a // dispatcher, and a cross-language registrar pairing (a JS `.push(` against a // Swift dispatcher's field name) would be a wrong edge, not a missed one. // Gating both sides here isn't just precision: `.push(`/`.add(` is everywhere // in JS/PHP, so an ungated scan slices + regexes nearly every function on repos // where the pass cannot emit a single edge — on a 12k-file PHP/JS app that was // 20+ minutes of the "Resolving refs" tail and a #850 watchdog kill (#1235). const CC_LANGUAGES = new Set(['swift', 'kotlin']); function kebabToPascal(s: string): string { return s.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(''); } /** * Nuxt auto-import name for a component, derived from its path UNDER `components/`: * `components/media/Card.vue` → `MediaCard`, `components/base/foo/Bar.vue` → * `BaseFooBar`. Each directory segment and the filename is PascalCased and * concatenated; a directory whose PascalCase name prefixes the next segment is * collapsed (Nuxt's de-dup: `base/BaseButton.vue` → `BaseButton`, not * `BaseBaseButton`). Returns null for a flat component (`components/NavBar.vue`) * — its node is already named by basename, so a direct tag match finds it. */ function nuxtComponentName(filePath: string): string | null { const marker = filePath.lastIndexOf('components/'); if (marker === -1) return null; const rel = filePath.slice(marker + 'components/'.length).replace(/\.(vue|ts|tsx|js|jsx)$/i, ''); const segs = rel.split('/').filter(Boolean).map(kebabToPascal); if (segs.length < 2) return null; const out: string[] = []; for (const s of segs) { const prev = out[out.length - 1]; if (prev && s.startsWith(prev)) out[out.length - 1] = s; else out.push(s); } return out.join(''); } // Callers walk one file's nodes in a row, so the last file's lines are kept: // splitting the whole file once per node was the JSX and render passes' top // cost (466 ms of a 2.8 s pretix run). let sliceLinesSource: string | null = null; let sliceLinesSplit: string[] = []; function sliceLines(content: string, startLine?: number, endLine?: number): string | null { if (!startLine || !endLine) return null; if (content !== sliceLinesSource) { sliceLinesSource = content; sliceLinesSplit = content.split('\n'); } return sliceLinesSplit.slice(startLine - 1, endLine).join('\n'); } // `src.slice(0, idx).split('\n').length` per match is quadratic on a file with // many matches (the registry pass's top cost). The line index is built once // per text, and the last text's index is kept. let lineOfSource: string | null = null; let lineOfIndex: (idx: number) => number = () => 1; function lineOf(src: string, idx: number): number { if (src !== lineOfSource) { lineOfSource = src; lineOfIndex = makeLineAt(src, 1); } return lineOfIndex(idx); } function registrarField(src: string): string | null { const m = src.match(/this\.(\w+)\.(?:add|push|set)\(/); return m ? m[1]! : null; } function dispatcherField(src: string): string | null { const forOf = src.match(/\bof\s+(?:Array\.from\(\s*)?this\.(\w+)/); if (forOf && /\b\w+\s*\(/.test(src)) return forOf[1]!; const forEach = src.match(/this\.(\w+)\.forEach\(/); if (forEach) return forEach[1]!; return null; } /** * Stream method + function nodes lazily. The synthesizers only scan-and-filter * down to a tiny matched subset, so materializing every function/method (which * is gigabytes on a symbol-dense project) just to iterate it once is what OOM'd * #610. Iterating keeps memory O(1) in the node count. */ function* methodAndFunctionNodes(queries: QueryBuilder, filter?: NodeScanFilter): IterableIterator { yield* queries.iterateNodesByKind('method', filter); yield* queries.iterateNodesByKind('function', filter); } // SQL superset of REGISTRAR_NAME | DISPATCHER_NAME, so the observer pass reads // only candidate rows; the regexes still decide. const FIELD_CHANNEL_NAMES: NodeScanFilter = { nameLike: [ 'on%', 'subscribe', 'addListener', 'addEventListener', 'register', 'watch', 'listen', 'addCallback', '%emit%', '%trigger%', '%notify%', '%dispatch%', '%fire%', '%publish%', '%flush%', ], }; /** Phase 1: field-backed observer channels (registrar/dispatcher share a store). */ async function fieldChannelEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { const registrars: Array<{ node: Node; field: string }> = []; const dispatchers: Array<{ node: Node; field: string }> = []; let scanned = 0; for (const m of methodAndFunctionNodes(queries, FIELD_CHANNEL_NAMES)) { if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs const isReg = REGISTRAR_NAME.test(m.name); const isDisp = DISPATCHER_NAME.test(m.name); if (!isReg && !isDisp) continue; const content = ctx.readFile(m.filePath); const src = content && sliceLines(content, m.startLine, m.endLine); if (!src) continue; if (isReg) { const f = registrarField(src); if (f) registrars.push({ node: m, field: f }); } if (isDisp) { const f = dispatcherField(src); if (f) dispatchers.push({ node: m, field: f }); } } const edges: Edge[] = []; const seen = new Set(); for (const reg of registrars) { const chDispatchers = dispatchers.filter( (d) => d.node.filePath === reg.node.filePath && d.field === reg.field ); if (chDispatchers.length === 0) continue; const argRe = new RegExp(`${escapeRegExp(reg.node.name)}\\s*\\(\\s*(this\\.\\w+|\\w+)\\s*(?=[,)])`); let added = 0; for (const e of queries.getIncomingEdges(reg.node.id, ['calls'])) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (!e.line) continue; const caller = queries.getNodeById(e.source); if (!caller) continue; const line = ctx.readFile(caller.filePath)?.split('\n')[e.line - 1]; const am = line?.match(argRe); if (!am) continue; // Reuse the resolved value at this registration site: it retains the // receiver's class/inheritance and import binding, unlike a name lookup. const refs = queries.getOutgoingEdges(caller.id, ['references']).filter( (r) => r.line === e.line && r.metadata?.fnRef === true && r.metadata.refName === am[1] ); if (refs.length !== 1) continue; const fn = queries.getNodeById(refs[0]!.target); if (!fn || (fn.kind !== 'method' && fn.kind !== 'function')) continue; if (!am[1]!.startsWith('this.') && fn.filePath !== caller.filePath && refs[0]!.metadata?.resolvedBy !== 'import') continue; for (const disp of chDispatchers) { if (disp.node.id === fn.id) continue; const key = `${disp.node.id}>${fn.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: disp.node.id, target: fn.id, kind: 'calls', line: disp.node.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'callback', via: reg.node.name, field: reg.field, // Where the callback was wired up (`scene.onUpdate(this.triggerRender)`). // This is the #1 thing an agent reads/greps to explain the flow — surface // it so node/trace/context can show it without a callers() + Read round-trip. registeredAt: `${caller.filePath}:${e.line}`, }, }); added++; } } } return edges; } /** * Closure-collection dispatch: dispatcher iterates a closure-collection property * invoking each element; registrar appends a closure to the same-named property. * Emits dispatcher → registrar so a flow reaches the registration site (where the * appended closure's body — and its callers — live). High-precision: the * dispatcher's element-invoke is the gate (a `.forEach` that does NOT invoke its * element is ignored), so a repo with no closure-collection dispatch yields zero * edges regardless of how many `.append`/`.push` sites it has. * * Pairs globally by field name (cross-file/class is required — see Alamofire's * base-class `Request.didCompleteTask` iterating `validators` appended by the * subclass `DataRequest.validate`), bounded by a fan-out cap so a generic field * name shared across unrelated classes can't fan out into noise. */ async function closureCollectionEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { const dispatchers = new Map>(); // field → dispatcher methods + forEach line const registrars = new Map>(); // field → registrar methods + append line const addReg = (field: string | undefined, node: Node, absLine: number) => { if (!field || /^\d+$/.test(field)) return; // `$0.append` mis-captures the `0`; the write-RE owns that field const arr = registrars.get(field) ?? []; if (!arr.some((r) => r.node.id === node.id)) arr.push({ node, line: absLine }); registrars.set(field, arr); }; // Slices EVERY Swift/Kotlin method/function's source (no cheap name-gate), so // on a repo with a huge file this is the heaviest synthesis pass — yield // mid-scan (and mid-match-loop below: a single generated function dense with // matches must not starve the watchdog either) so it can't wedge the #850 // watchdog on its own (#1091, #1235). let scanned = 0; let matchTick = 0; for (const m of methodAndFunctionNodes(queries, { languages: [...CC_LANGUAGES] as Language[] })) { if ((++scanned & 127) === 0) await onYield(); if (!CC_LANGUAGES.has(m.language)) continue; const content = ctx.readFile(m.filePath); const src = content && sliceLines(content, m.startLine, m.endLine); if (!src) continue; const hasForEach = src.includes('.forEach'); const hasAppend = src.includes('.append(') || src.includes('.add(') || src.includes('.push(') || src.includes('.insert('); if (!hasForEach && !hasAppend) continue; const lineAt = makeLineAt(src, m.startLine ?? 1); if (hasForEach) { CC_DISPATCH_RE.lastIndex = 0; let d: RegExpExecArray | null; while ((d = CC_DISPATCH_RE.exec(src))) { if ((++matchTick & 255) === 0) await onYield(); const arr = dispatchers.get(d[1]!) ?? []; if (!arr.some((n) => n.node.id === m.id)) arr.push({ node: m, line: lineAt(d.index) }); dispatchers.set(d[1]!, arr); } } if (hasAppend) { CC_APPEND_WRITE_RE.lastIndex = 0; let w: RegExpExecArray | null; while ((w = CC_APPEND_WRITE_RE.exec(src))) { if ((++matchTick & 255) === 0) await onYield(); addReg(w[2] || w[1], m, lineAt(w.index)); // nested `$0.streams` else the `.write` receiver } CC_APPEND_DIRECT_RE.lastIndex = 0; let a: RegExpExecArray | null; while ((a = CC_APPEND_DIRECT_RE.exec(src))) { if ((++matchTick & 255) === 0) await onYield(); addReg(a[1], m, lineAt(a.index)); } } } const edges: Edge[] = []; const seen = new Set(); for (const [field, disps] of dispatchers) { const regs = registrars.get(field); if (!regs || regs.length === 0) continue; if (disps.length > CC_FANOUT_CAP || regs.length > CC_FANOUT_CAP) continue; // generic field — can't pair confidently for (const disp of disps) for (const reg of regs) { if (disp.node.id === reg.node.id) continue; const key = `${disp.node.id}>${reg.node.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: disp.node.id, target: reg.node.id, kind: 'calls', line: disp.line, provenance: 'heuristic', metadata: { synthesizedBy: 'closure-collection', field, registeredAt: `${reg.node.filePath}:${reg.line}` }, }); } } return edges; } /** Phase 2: string-keyed EventEmitter channels (on('e', fn) ↔ emit('e')). */ async function eventEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise { let scannedFiles = 0; const emitsByEvent = new Map>(); // event → dispatcher node ids const handlersByEvent = new Map>(); // event → handler id → registration site (file:line) let scanned = 0; for (const file of ctx.getAllFiles()) { if ((++scannedFiles & 15) === 0) await onYield(); if ((++scanned & 255) === 0) await onYield(); // #1091: yield mid-scan on huge graphs if (skipped(ctx, 'emitterEdges', file)) continue; const content = ctx.readFile(file); if (!content) continue; const hasEmit = content.includes('.emit(') || content.includes('.fire(') || content.includes('.dispatchEvent('); const hasOn = content.includes('.on(') || content.includes('.once(') || content.includes('.addListener('); if (!hasEmit && !hasOn) { recordSkip(ctx, 'emitterEdges', file, content); continue; } const nodesInFile = ctx.getNodesInFile(file); const lineOf = makeLineAt(content, 1); if (hasEmit) { EMIT_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = EMIT_RE.exec(content))) { const disp = enclosingFn(nodesInFile, lineOf(m.index)); if (!disp) continue; const set = emitsByEvent.get(m[1]!) ?? new Set(); set.add(disp.id); emitsByEvent.set(m[1]!, set); } } if (hasOn) { ON_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = ON_RE.exec(content))) { const handlerName = m[2] || m[3]; if (!handlerName) continue; // A manual mock's function is a handler only test code registers (#2455). const handler = ctx.getNodesByName(handlerName).find((n) => (n.kind === 'function' || n.kind === 'method') && !isManualMockHiddenFrom(n.filePath, file)); if (!handler) continue; const map = handlersByEvent.get(m[1]!) ?? new Map(); map.set(handler.id, `${file}:${lineOf(m.index)}`); handlersByEvent.set(m[1]!, map); } // Inline listeners: the anonymous arrow/function can't be looked up by // name (extraction attributes its calls to the enclosing function), so // the edge lands on the enclosing function — the same node the // listener's own calls attribute to — or on the smallest enclosing // constant/variable for an object-literal API's registration site. ON_INLINE_RE.lastIndex = 0; while ((m = ON_INLINE_RE.exec(content))) { const handler = enclosingFn(nodesInFile, lineOf(m.index)) ?? enclosingValue(nodesInFile, lineOf(m.index)); if (!handler) continue; const map = handlersByEvent.get(m[1]!) ?? new Map(); if (!map.has(handler.id)) map.set(handler.id, `${file}:${lineOf(m.index)}`); handlersByEvent.set(m[1]!, map); } } } const edges: Edge[] = []; const seen = new Set(); for (const [event, dispatchers] of emitsByEvent) { const handlers = handlersByEvent.get(event); if (!handlers) continue; // Precision guard: a generic event name with many handlers/dispatchers can't // be matched without receiver-type info (Phase 3) — skip rather than over-link. if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue; for (const d of dispatchers) for (const [h, registeredAt] of handlers) { if (d === h) continue; const key = `${d}>${h}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: d, target: h, kind: 'calls', provenance: 'heuristic', metadata: { synthesizedBy: 'event-emitter', event, registeredAt } }); } } return edges; } /** * Window `postMessage` ↔ `addEventListener('message')` keyed on a payload * discriminator (`source: CONST` / `data.source === CONST`). The DOM event * name is always `message`, so pairing on that string would fan out. Skip * generic names and cap fan-out like the EventEmitter pass. */ const WINDOW_MSG_GENERIC = new Set(['message', 'data', 'event', 'source', 'type', 'error', 'ping', 'pong']); const POSTMESSAGE_RE = /\.postMessage\s*\(/g; const MESSAGE_LISTEN_RE = /\.addEventListener\s*\(\s*['"]message['"]\s*,\s*/g; const SOURCE_FIELD_RE = /\bsource\s*:\s*(?:(['"])([^'"\n]+)\1|((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*))/g; const SOURCE_CMP_RE = /\.source\s*(?:!==|===|!=|==)\s*(?:(['"])([^'"\n]+)\1|((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*))/g; const SOURCE_CMP_REV_RE = /(?:(['"])([^'"\n]+)\1|((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*))\s*(?:!==|===|!=|==)\s*[\w.$]*\.source/g; const NAMED_LISTEN_HANDLER_RE = /^(?:async\s+)?([A-Za-z_$][\w$]*)\s*[,)]/; function windowMessageKey(lit: string | undefined, mem: string | undefined): string | null { if (lit) { if (lit.length < 4 || WINDOW_MSG_GENERIC.has(lit.toLowerCase())) return null; return `lit:${lit}`; } const name = mem?.split('.').pop(); if (!name || WINDOW_MSG_GENERIC.has(name.toLowerCase()) || !isDistinctiveIdentifier(name)) return null; return `mem:${name}`; } function windowMessageKeys(chunk: string, field: boolean): string[] { const keys = new Set(); const add = (lit?: string, mem?: string) => { const key = windowMessageKey(lit, mem); if (key) keys.add(key); }; if (field) { SOURCE_FIELD_RE.lastIndex = 0; for (let m; (m = SOURCE_FIELD_RE.exec(chunk)); ) add(m[2], m[3]); } else { SOURCE_CMP_RE.lastIndex = 0; for (let m; (m = SOURCE_CMP_RE.exec(chunk)); ) add(m[2], m[3]); SOURCE_CMP_REV_RE.lastIndex = 0; for (let m; (m = SOURCE_CMP_REV_RE.exec(chunk)); ) add(m[2], m[3]); } return [...keys]; } function nodeSource(ctx: ResolutionContext, node: Node): string { const content = ctx.readFile(node.filePath); if (!content) return ''; return content.split('\n').slice(node.startLine - 1, node.endLine).join('\n'); } async function windowMessageEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise { const posts = new Map>(); const listeners = new Map>(); let scannedFiles = 0; for (const file of ctx.getAllFiles()) { if ((++scannedFiles & 15) === 0) await onYield(); if (skipped(ctx, 'windowMessageEdges', file)) continue; const content = ctx.readFile(file); if (!content || (!content.includes('postMessage') && !content.includes('addEventListener'))) { recordSkip(ctx, 'windowMessageEdges', file, content); continue; } const nodesInFile = ctx.getNodesInFile(file); if (!nodesInFile.some((n) => n.language && JS_FAMILY.includes(n.language))) continue; const lineOf = makeLineAt(content, 1); POSTMESSAGE_RE.lastIndex = 0; for (let m; (m = POSTMESSAGE_RE.exec(content)); ) { const disp = enclosingFn(nodesInFile, lineOf(m.index)); if (!disp) continue; for (const key of windowMessageKeys(content.slice(m.index, m.index + 500), true)) { const set = posts.get(key) ?? new Set(); set.add(disp.id); posts.set(key, set); } } MESSAGE_LISTEN_RE.lastIndex = 0; for (let m; (m = MESSAGE_LISTEN_RE.exec(content)); ) { const rest = content.slice(m.index + m[0].length); const named = rest.match(NAMED_LISTEN_HANDLER_RE)?.[1]; const line = lineOf(m.index); let handler = named ? ctx.getNodesByName(named).find((n) => n.kind === 'function' || n.kind === 'method') : null; if (!handler) handler = enclosingFn(nodesInFile, line); if (!handler) continue; for (const key of windowMessageKeys(nodeSource(ctx, handler), false)) { const map = listeners.get(key) ?? new Map(); map.set(handler.id, `${file}:${line}`); listeners.set(key, map); } } } const edges: Edge[] = []; const seen = new Set(); for (const [key, dispatchers] of posts) { const handlers = listeners.get(key); if (!handlers) continue; if (dispatchers.size > EVENT_FANOUT_CAP || handlers.size > EVENT_FANOUT_CAP) continue; const event = key.slice(key.indexOf(':') + 1); for (const d of dispatchers) for (const [h, registeredAt] of handlers) { if (d === h) continue; const pair = `${d}>${h}`; if (seen.has(pair)) continue; seen.add(pair); edges.push({ source: d, target: h, kind: 'calls', provenance: 'heuristic', metadata: { synthesizedBy: 'window-message', event, registeredAt }, }); } } return edges; } /** * Phase 4: React class-component re-render. `this.setState(...)` re-runs the * component's `render()`, but that hop is React-internal — no static edge — so a * flow like "mutation → setState → canvas repaint" dead-ends at setState even * though `render → getRenderableElements → …` is fully call-connected after it. * Bridge it: for each class that has a `render` method, link every sibling method * whose body calls `this.setState(` → `render`. The setState gate keeps this to * React class components (a non-React class with a `render` method won't call * `this.setState`). Over-approximation (all setState methods reach render) is * accepted — it's reachability-correct, like the callback channels. */ async function reactRenderEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); // A class can only emit here if it CONTAINS a method named `render` — so one // indexed name lookup bounds the candidate set up front, and the class scan // below skips everything else before its per-class edge/node queries. On a // repo with few/no render methods (any non-React codebase) this collapses // the pass from every-class fan-out to ~zero DB work, with identical output: // the skipped classes fail the same `render` check today, just after paying // for their children. (Not a language gate: `render` + `this.setState(` in // Java — e.g. Litho — legitimately matches today and still does.) const renderOwners = new Set(); for (const n of ctx.getNodesByName('render')) { if (n.kind !== 'method') continue; for (const e of queries.getIncomingEdges(n.id, ['contains'])) renderOwners.add(e.source); } if (renderOwners.size === 0) return edges; for (const cls of queries.iterateNodesByKind('class')) { if ((++scanned255 & 63) === 0) await onYield(); if (!renderOwners.has(cls.id)) continue; const children = queries.getOutgoingEdges(cls.id, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n && n.kind === 'method'); const render = children.find((n) => n.name === 'render'); if (!render) continue; let added = 0; for (const m of children) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (m.id === render.id) continue; const content = ctx.readFile(m.filePath); const src = content && sliceLines(content, m.startLine, m.endLine); if (!src || !SETSTATE_RE.test(src)) continue; const key = `${m.id}>${render.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: m.id, target: render.id, kind: 'calls', line: m.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'react-render', via: 'setState', registeredAt: `${render.filePath}:${render.startLine}` }, }); added++; } } return edges; } /** * Phase 4b: Flutter setState → build (the Dart analog of react-render). In a * StatefulWidget's State class, `setState(() {…})` re-runs `build(context)`, but * that hop is framework-internal (Flutter calls build), so a flow like * "onPressed → _increment → setState → rebuilt UI" dead-ends at setState. Bridge * it: for each Dart class with a `build` method, link every sibling method whose * body calls `setState(` → `build`. The setState gate + `.dart` file keep this to * Flutter State classes. Over-approximation accepted (reachability-correct). * * Second phase (same pass): named navigation — `Navigator.pushNamed(context, * '/detail')` is a string-keyed dispatch whose destination lives in the app's * `routes:` table (`MaterialApp(routes: { '/detail': (ctx) => DetailPage() })`), * not at the callsite, so nothing links caller → page widget. Build a * route-name → widget-class map from every `routes:` map literal (only inside a * file that constructs a `MaterialApp`/`CupertinoApp`/`WidgetsApp`), then link * the enclosing method at each `Navigator.*Named(…, '/route')` site to the * widget class that route builds. `Navigator.push(ctx, MaterialPageRoute( * builder: (_) => X()))` needs nothing — the `X()` constructor is a literal * call in the enclosing method already. `GetPage(name:…, page:…)`/GetX's * `Get.toNamed` is a different registration shape — deferred. */ const FLUTTER_APP_RE = /\b(?:MaterialApp|CupertinoApp|WidgetsApp|GetMaterialApp)\s*\(/; const FLUTTER_ROUTES_BLOCK_RE = /\broutes\s*:\s*\{/g; const FLUTTER_ROUTE_ENTRY_RE = /['"]([^'"]+)['"]\s*:\s*(?:\([^)]*\)|[A-Za-z_]\w*)\s*=>\s*(?:const\s+)?([A-Z]\w*)\s*\(/g; const FLUTTER_NAMED_NAV_RE = /\b[Nn]avigator\s*\.\s*(?:of\s*\([^()]*\)\s*\.\s*)?(?:pushNamed|pushReplacementNamed|pushNamedAndRemoveUntil|popAndPushNamed|restorablePushNamed|restorablePushReplacementNamed)\s*\(\s*(?:[\w$.!]+\s*,\s*)?['"]([^'"]+)['"]/g; async function flutterBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); for (const cls of queries.iterateNodesByKind('class')) { if ((++scanned255 & 63) === 0) await onYield(); const children = queries.getOutgoingEdges(cls.id, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n && n.kind === 'method'); const build = children.find((n) => n.name === 'build'); if (!build || !build.filePath.endsWith('.dart')) continue; let added = 0; for (const m of children) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (m.id === build.id) continue; const content = ctx.readFile(m.filePath); const src = content && sliceLines(content, m.startLine, m.endLine); if (!src || !FLUTTER_SETSTATE_RE.test(src)) continue; const key = `${m.id}>${build.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: m.id, target: build.id, kind: 'calls', line: m.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'flutter-build', via: 'setState', registeredAt: `${build.filePath}:${build.startLine}` }, }); added++; } } // ── named routes → page widgets ────────────────────────────────────────── // Pass 1: collect `routes: { '/x': (ctx) => XPage(), … }` entries — only // from a file that constructs an app widget, so a `routes:` map on an // unrelated object literal never registers. const routeWidgets = new Map(); const routeAmbiguous = new Set(); for (const file of ctx.getAllFiles()) { if (!file.endsWith('.dart')) continue; const content = ctx.readFile(file); if (!content || !content.includes('routes') || !FLUTTER_APP_RE.test(content)) continue; FLUTTER_ROUTES_BLOCK_RE.lastIndex = 0; let bm: RegExpExecArray | null; while ((bm = FLUTTER_ROUTES_BLOCK_RE.exec(content))) { const open = bm.index + bm[0].length - 1; const close = matchBalanced(content, open); if (close === -1) continue; const block = content.slice(open, close + 1); FLUTTER_ROUTE_ENTRY_RE.lastIndex = 0; let em: RegExpExecArray | null; while ((em = FLUTTER_ROUTE_ENTRY_RE.exec(block))) { const [, routeName, widget] = em; const prev = routeWidgets.get(routeName!); if (prev && (prev.widget !== widget! || prev.file !== file)) { // Two different widgets behind one route name — can't tell which a // pushNamed means, so drop the route rather than guess. routeAmbiguous.add(routeName!); routeWidgets.delete(routeName!); } else if (!routeAmbiguous.has(routeName!)) { routeWidgets.set(routeName!, { widget: widget!, file }); } } } } if (routeWidgets.size === 0) return edges; // Pass 2: `Navigator.pushNamed(context, '/x')` sites. The registered-name // backstop — only a route string actually declared in a `routes:` map ever // links — is the precision gate; an unknown name yields nothing. let scannedFiles = 0; for (const file of ctx.getAllFiles()) { if ((++scannedFiles & 15) === 0) await onYield(); if (!file.endsWith('.dart')) continue; const content = ctx.readFile(file); if (!content || !content.includes('pushNamed')) continue; const nodesInFile = ctx.getNodesInFile(file); const lineOf = makeLineAt(content, 1); FLUTTER_NAMED_NAV_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = FLUTTER_NAMED_NAV_RE.exec(content))) { const reg = routeWidgets.get(m[1]!); if (!reg) continue; const candidates = ctx .getNodesByName(reg.widget) .filter((n) => n.kind === 'class' && n.filePath.endsWith('.dart')); const widgetCls = candidates.find((n) => n.filePath === reg.file) ?? (candidates.length === 1 ? candidates[0] : undefined); if (!widgetCls) continue; const disp = enclosingFn(nodesInFile, lineOf(m.index)) ?? enclosingValue(nodesInFile, lineOf(m.index)); if (!disp || disp.id === widgetCls.id) continue; const key = `${disp.id}>${widgetCls.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: disp.id, target: widgetCls.id, kind: 'navigates', line: lineOf(m.index), provenance: 'heuristic', metadata: { synthesizedBy: 'flutter-nav', route: m[1], registeredAt: `${file}:${lineOf(m.index)}` }, }); } } return edges; } /** * Reactive ArkUI property decorators: assigning a property carrying one of * these re-runs the owning struct's `build()`. Covers both state models — * V1 (`@Component`: State/Prop/Link/Provide/Consume/Storage*) and V2 * (`@ComponentV2`: Local/Provider/Consumer; `@Param` is read-only in V2 so * the assignment gate never fires on it, and `@Trace` lives on `@ObservedV2` * data classes, not struct properties). */ const ARKUI_REACTIVE_DECORATORS = new Set([ 'State', 'Prop', 'Link', 'Provide', 'Consume', 'StorageLink', 'StorageProp', 'LocalStorageLink', 'LocalStorageProp', 'ObjectLink', 'Local', 'Provider', 'Consumer', ]); /** ArkUI-observed array mutators — `this.todos.push(x)` re-renders like an assignment. */ const ARKUI_ARRAY_MUTATORS = 'push|pop|shift|unshift|splice|sort|reverse|fill'; /** * Phase 4b-ets: ArkUI state → build (the ArkTS analog of react-render / * flutter-build). Assigning a reactive-decorated property (`@State count`, * `@Link selected`, …) re-runs the `@Component struct`'s `build()`, but that * hop is framework-internal — no static edge — so "onClick → markAllDone → * this.todos = […] → rebuilt list" dead-ends at the assignment. Bridge it: * for each arkts struct with a `build()` method and at least one reactive * property, link every sibling method whose body ASSIGNS (or array-mutates) * one of those properties → `build`. Assignment-gated on the struct's OWN * reactive property names — a method that merely reads state, or a struct * with no reactive properties, gets nothing (this is the precision line the * all-sibling-methods design would erase). */ async function arkuiStateBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); for (const struct of queries.iterateNodesByKind('struct', { languages: ['arkts'] })) { if ((++scanned255 & 63) === 0) await onYield(); const children = queries.getOutgoingEdges(struct.id, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n); const build = children.find((n) => n.kind === 'method' && n.name === 'build'); if (!build) continue; const reactiveProps = children.filter( (n) => n.kind === 'property' && (n.decorators ?? []).some((d) => ARKUI_REACTIVE_DECORATORS.has(d)) ); if (reactiveProps.length === 0) continue; const propAlternation = reactiveProps .map((p) => p.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) .join('|'); // `this.count = …` / `+=` / `++` / `--` / `this.todos.push(…)`. The // `=(?!=)` keeps `this.done == x` comparisons out. const mutationRe = new RegExp( `this\\.(?:${propAlternation})\\s*(?:=(?!=)|\\+\\+|--|[+\\-*/%&|^]=|\\.(?:${ARKUI_ARRAY_MUTATORS})\\s*\\()` ); let added = 0; for (const m of children) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (m.kind !== 'method' || m.id === build.id) continue; const content = ctx.readFile(m.filePath); const src = content && sliceLines(content, m.startLine, m.endLine); if (!src || !mutationRe.test(stripCommentsForRegex(src, 'typescript'))) continue; const key = `${m.id}>${build.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: m.id, target: build.id, kind: 'calls', line: m.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'arkui-state', via: 'state assignment', registeredAt: `${build.filePath}:${build.startLine}` }, }); added++; } } return edges; } /** Emit/subscribe call sites of HarmonyOS's `@ohos.events.emitter` bus. */ const ARKUI_EMITTER_CALL_RE = /\bemitter\s*\.\s*(emit|on|once)\s*\(\s*([A-Za-z_$][\w$.]*|\{[^)]{0,120}?\beventId\s*:\s*[^,}]+[^)]*?\})/g; /** Cap per event bucket — a generic key with many parties is dynamic routing, not a static pair. */ const ARKUI_EMITTER_FANOUT_CAP = 8; /** * Phase 4b-ets2: HarmonyOS `@ohos.events.emitter` bridge. The cross-component * bus — `emitter.emit(eventId)` fires `emitter.on(eventId, cb)` — is * framework-internal, so an order flow riding it (OrangeShopping's * add-to-cart) dead-ends at the emit. Link emit-site enclosing * function/method → on/once-site enclosing function/method when both * reference the SAME statically-recoverable event key. * * Key recovery, per call site (comment-stripped enclosing-file source): the * first argument is an `{ eventId: K }` literal, a `Names.Dotted` constant, or * a local whose same-file declaration is `new EventsId(K)` / `= K` — chase one * level. Precision scoping learned from the samples monorepo (thousands of * unrelated samples, most using eventId 1): NUMERIC keys pair within the same * FILE only; NAMED keys pair within the same workspace module directory (or * the whole project when it declares no modules — the single-app case), both * behind a fan-out cap. Inline `on(id, (e) => {…})` arrows need no special * handling — their bodies' calls already attribute to the registering method, * so targeting that method keeps the chain connected. */ async function arkuiEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise { let scannedFiles = 0; interface Site { nodeId: string; file: string; line: number } // bucket key -> emit sites / handler sites const emits = new Map(); const handlers = new Map(); const moduleDirs = (() => { const ws = ctx.getWorkspacePackages?.(); return ws ? [...new Set(ws.byName.values())].sort((a, b) => b.length - a.length) : []; })(); const moduleScopeOf = (file: string): string => { for (const dir of moduleDirs) { if (file === dir || file.startsWith(dir + '/')) return dir; } return ''; }; for (const file of ctx.getAllFiles()) { if ((++scannedFiles & 15) === 0) await onYield(); if (!file.endsWith('.ets')) continue; const content = ctx.readFile(file); if (!content || !content.includes('emitter.')) continue; const safe = stripCommentsForRegex(content, 'typescript'); const nodes = ctx.getNodesInFile(file) .filter((n) => n.kind === 'method' || n.kind === 'function'); ARKUI_EMITTER_CALL_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = ARKUI_EMITTER_CALL_RE.exec(safe))) { const verb = m[1]!; const arg = m[2]!.trim(); const line = lineOf(safe, m.index); const encl = nodes .filter((n) => n.startLine <= line && n.endLine >= line) .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0]; if (!encl) continue; // Recover the event key from the first argument. let key: string | null = null; const idLit = arg.startsWith('{') ? arg.match(/\beventId\s*:\s*([\w$.]+)/)?.[1] : undefined; const token = idLit ?? arg; if (token !== undefined) { if (/^\d+$/.test(token)) { key = `num:${file}:${token}`; // numeric: same-file only } else if (token.includes('.')) { key = `name:${moduleScopeOf(file)}:${token}`; } else { // Local variable — chase its same-file declaration one level: // `let x = new EventsId(K)` / `const x = K`. const declRe = new RegExp( `\\b${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b\\s*(?::[^=\\n]+)?=\\s*(?:new\\s+[\\w$.]+\\(\\s*([^)\\n]+?)\\s*\\)|([\\w$.]+))` ); const decl = safe.match(declRe); const inner = (decl?.[1] ?? decl?.[2])?.trim(); if (inner && /^\d+$/.test(inner)) key = `num:${file}:${inner}`; else if (inner && /^[\w$.]+$/.test(inner)) key = `name:${moduleScopeOf(file)}:${inner}`; } } if (!key) continue; const site: Site = { nodeId: encl.id, file, line }; if (verb === 'emit') { (emits.get(key) ?? emits.set(key, []).get(key)!).push(site); } else { (handlers.get(key) ?? handlers.set(key, []).get(key)!).push(site); } } } const edges: Edge[] = []; const seen = new Set(); for (const [key, emitSites] of emits) { const handlerSites = handlers.get(key); if (!handlerSites) continue; if (emitSites.length > ARKUI_EMITTER_FANOUT_CAP || handlerSites.length > ARKUI_EMITTER_FANOUT_CAP) continue; const eventLabel = key.slice(key.lastIndexOf(':') + 1); for (const e of emitSites) for (const h of handlerSites) { if (e.nodeId === h.nodeId) continue; const dedupe = `${e.nodeId}>${h.nodeId}`; if (seen.has(dedupe)) continue; seen.add(dedupe); edges.push({ source: e.nodeId, target: h.nodeId, kind: 'calls', line: e.line, provenance: 'heuristic', metadata: { synthesizedBy: 'arkui-emitter', event: eventLabel, registeredAt: `${h.file}:${h.line}` }, }); } } return edges; } /** `router.pushUrl({ url: 'pages/Detail' })` / replaceUrl — literal urls only. */ const ARKUI_ROUTER_RE = /\brouter\s*\.\s*(?:pushUrl|replaceUrl)\s*\(\s*\{[^)]{0,200}?\burl\s*:\s*['"]([\w\-./]+)['"]/g; /** * Phase 4b-ets3: HarmonyOS page navigation. `router.pushUrl({ url: * 'pages/Detail' })` reaches the `@Entry struct` of * `/src/main/ets/pages/Detail.ets`, but the hop is a string — no * static edge — so "tap → openDetail → ???" ends at the router call. Bridge * literal urls to the page struct: the url resolves against the standard * `src/main/ets/` layout (what main_pages.json entries name); candidates * prefer the caller's own workspace module (routes are module-scoped), and * anything still ambiguous is dropped rather than guessed. Only `@Entry` * structs qualify as targets — the decorator is what makes a file a page. */ async function arkuiRouterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise { const edges: Edge[] = []; const seen = new Set(); const allFiles = ctx.getAllFiles(); const moduleDirs = (() => { const ws = ctx.getWorkspacePackages?.(); return ws ? [...new Set(ws.byName.values())].sort((a, b) => b.length - a.length) : []; })(); const moduleScopeOf = (file: string): string => { for (const dir of moduleDirs) { if (file === dir || file.startsWith(dir + '/')) return dir; } return ''; }; let scannedFiles = 0; for (const file of allFiles) { if ((++scannedFiles & 15) === 0) await onYield(); if (!file.endsWith('.ets')) continue; const content = ctx.readFile(file); if (!content || !content.includes('router.')) continue; const safe = stripCommentsForRegex(content, 'typescript'); const nodes = ctx.getNodesInFile(file) .filter((n) => n.kind === 'method' || n.kind === 'function'); ARKUI_ROUTER_RE.lastIndex = 0; let m: RegExpExecArray | null; while ((m = ARKUI_ROUTER_RE.exec(safe))) { const url = m[1]!; const line = lineOf(safe, m.index); const encl = nodes .filter((n) => n.startLine <= line && n.endLine >= line) .sort((a, b) => (a.endLine - a.startLine) - (b.endLine - b.startLine))[0]; if (!encl) continue; const suffix = `/src/main/ets/${url}.ets`; let candidates = allFiles.filter((f) => f.endsWith(suffix)); if (candidates.length > 1) { const scope = moduleScopeOf(file); const sameModule = candidates.filter((f) => moduleScopeOf(f) === scope); if (sameModule.length > 0) candidates = sameModule; } if (candidates.length !== 1) continue; // ambiguous or unresolved — never guess const page = ctx.getNodesInFile(candidates[0]!).find( (n) => n.kind === 'struct' && (n.decorators ?? []).includes('Entry') ); if (!page) continue; const key = `${encl.id}>${page.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: encl.id, target: page.id, kind: 'calls', line, provenance: 'heuristic', metadata: { synthesizedBy: 'arkui-route', event: url, registeredAt: `${candidates[0]}:${page.startLine}` }, }); } } return edges; } /** * Phase 4c: C++ virtual override. A call through a base/interface pointer * (`db->Get(...)`, `iter->Next()`) dispatches at runtime to a subclass override, * but that hop is a vtable indirection — no static call edge — so a flow stops at * the abstract base method. Bridge it like react-render: for each C++ class that * `extends` a base, link each base method → the subclass method of the same name * (the override), so trace/callees from the interface method reach the * implementation(s). Over-approximation accepted (reachability-correct); capped * per class and gated to C++ to avoid touching other languages' dispatch. * An explicit specialization of a member template, which shares the * template's name, overrides nothing and is overridden by nothing. */ async function cppOverrideEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); const methodsOf = (classId: string): Node[] => queries .getOutgoingEdges(classId, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n && n.kind === 'method'); const overridable = (m: Node): boolean => cppSpecializationArguments(m, ctx) === null; for (const cls of queries.iterateNodesByKind('class')) { if ((++scanned255 & 63) === 0) await onYield(); const subMethods = methodsOf(cls.id).filter((n) => n.language === 'cpp'); if (subMethods.length === 0) continue; for (const ext of queries.getOutgoingEdges(cls.id, ['extends'])) { const base = queries.getNodeById(ext.target); if (!base || base.language !== 'cpp' || base.id === cls.id) continue; const baseMethods = new Map(methodsOf(base.id).filter(overridable).map((m) => [m.name, m])); let added = 0; for (const m of subMethods) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; const bm = baseMethods.get(m.name); if (!bm || bm.id === m.id || !overridable(m)) continue; const key = `${bm.id}>${m.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: bm.id, target: m.id, kind: 'calls', line: bm.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'cpp-override', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` }, }); added++; } } } return edges; } /** * Phase 5.5: interface / abstract dispatch (Java, Kotlin). A call through an * injected interface (`@Autowired FooService svc; svc.list()`) or an abstract * base dispatches at runtime to the implementing class's override — a vtable * indirection with no static call edge — so a request→service flow stops at the * interface method. Bridge it like cpp-override: for each class that * `implements` an interface (or `extends` an abstract base), link each * base/interface method → the class's same-name method (the override) so * trace/callees reach the implementation. Of an overloaded name, an overload * links the methods with its parameters where the language makes an override * repeat them (./override-parameters, #2663). Over-approximation accepted * (reachability-correct); capped per class, gated to JVM languages. */ // Languages whose static `implements`/`extends` edges should bridge an // interface (or abstract base) method to the matching concrete-class method. // The set is "languages with explicit nominal subtyping and a single class // kind that holds methods" — i.e. the shape this loop expects. Swift and // Scala fit shape-wise (Swift `protocol`/`class`, Scala `trait`/`class`) // and are added below; their concrete-side nodes can be a `struct` (Swift) // or an `object` (Scala) so the loop also iterates those kinds. A `.tsx` or // `.jsx` class is a TypeScript or JavaScript class, and its base or interface // is often in a `.ts` file, or the other way round. const IFACE_OVERRIDE_LANGS = new Set([ 'java', 'kotlin', 'csharp', 'typescript', 'tsx', 'javascript', 'jsx', 'swift', 'scala', 'go', 'rust', 'arkts', ]); /** Depth cap for transitive-supertype BFS in interfaceOverrideEdges — real * extends/implements chains are ≤~6; the cap is a graph-corruption backstop. */ const MAX_SUPERTYPE_DEPTH = 8; /** * Languages whose static and instance methods override only their own kind: * a JS/TS class's statics are inherited and overridden by the subclass's * statics, its instance methods by instance methods (#2761). */ const STATIC_SPLIT_LANGS: ReadonlySet = new Set(['typescript', 'tsx', 'javascript', 'jsx']); /** * Whether a supertype edge out of a Go type is one of its embeddings (#2397): * declared, never synthesized (go-implements writes those), into a struct, an * interface or a defined type, and out of an interface only into an interface. * `kindOf` answers those three kinds for a Go node id, null for anything else. */ function isGoEmbedding(e: Edge, kindOf: (id: string) => NodeKind | null): boolean { if (e.provenance === 'heuristic') return false; const to = kindOf(e.target); return to !== null && (kindOf(e.source) !== 'interface' || to === 'interface'); } /** An exported Go identifier starts with an upper-case letter, in Unicode's sense. */ const GO_EXPORTED_NAME = /^\p{Lu}/u; /** * What a Go method matches an interface's method by: its name, and for an * unexported name the package that declares it as well. Go makes the * `refresh` declared in discovery/hetzner and the one declared in * discovery/aws two different methods, so neither satisfies the other's * interface. Package identity includes the directory and package clause, so a method * that embedding promotes keeps the package of the type declaring it. */ function goMethodKey(m: Node, packageOf: GoPackageOf): string { if (GO_EXPORTED_NAME.test(m.name)) return m.name; const file = m.filePath.replace(/\\/g, '/'); return `${file.slice(0, Math.max(file.lastIndexOf('/'), 0))}\0${packageOf(m.filePath) ?? m.filePath}\0${m.name}`; } /** * {@link goMethodKey} for a method of a standard-library type: its name, and * for an unexported one (`testing.TB`'s `private`) the declaring package, * spelled so it is no directory of the project's. */ function goStdlibMethodKey(importPath: string | null, name: string): string { return GO_EXPORTED_NAME.test(name) ? name : `std:${importPath ?? ''}\0${name}`; } /** What a Go type has, or an interface asks for. */ interface GoMethodNames { /** * Its methods by {@link goMethodKey}: its own, the project types' it * embeds, and those the standard-library types it embeds bring * (./go-stdlib-methods), `error`'s included. */ readonly methods: Set; /** Embedded types from outside the index whose methods nothing names, by package and name. */ readonly opaque: ReadonlySet; } /** * The top-level items of the Go bracketed list opening at `text[open]` — the * parameters of `(ctx context.Context, a, b int)` are `ctx context.Context`, `a` * and `b int` — and the offset where the list closes. Nested brackets, string * literals and comments are skipped whole. Null when the list never closes. */ function goListItems(text: string, open: number): { items: string[]; end: number } | null { const items: string[] = []; let depth = 0; let item = ''; for (let i = open; i < text.length; i++) { const c = text[i]!; if (c === '/' && (text[i + 1] === '/' || text[i + 1] === '*')) { const end = text[i + 1] === '/' ? text.indexOf('\n', i) : text.indexOf('*/', i + 2) + 1; if (end <= 0) return null; i = end; item += ' '; continue; } if (c === '"' || c === '`' || c === "'") { let j = i + 1; while (j < text.length && text[j] !== c) j += c !== '`' && text[j] === '\\' ? 2 : 1; if (j >= text.length) return null; item += text.slice(i, j + 1); i = j; continue; } if (c === '(' || c === '[' || c === '{') { if (depth++ === 0) continue; } else if (c === ')' || c === ']' || c === '}') { if (--depth === 0) { if (item.trim()) items.push(item.trim()); return { items, end: i }; } } else if (c === ',' && depth === 1) { if (item.trim()) items.push(item.trim()); item = ''; continue; } item += c; } return null; } /** * A Go signature as extraction stores it for a function or method — the * parameter list's text, then the result's — split into its parameters and * results: `(ctx context.Context, a, b int) (int, error)` has the parameters * `ctx context.Context`, `a` and `b int`. Null when the text has another shape. */ function goSignatureParts(signature: string | undefined): { params: string[]; results: string[] } | null { const sig = signature?.trim(); if (!sig || sig[0] !== '(') return null; const params = goListItems(sig, 0); if (!params) return null; const rest = sig.slice(params.end + 1).trim(); if (rest[0] !== '(') return { params: params.items, results: rest ? [rest] : [] }; const results = goListItems(rest, 0); if (!results || rest.slice(results.end + 1).trim()) return null; return { params: params.items, results: results.items }; } /** * How many parameters and results a Go signature has, as `params/results`: * `(ctx context.Context, keys ...string) (int, error)` is `2/2`, and a grouped * `a, b int` is two parameters. Null when the signature doesn't read. */ export function goSignatureArity(signature: string | undefined): string | null { const parts = goSignatureParts(signature); return parts ? `${parts.params.length}/${parts.results.length}` : null; } /** * The arity a gRPC server implements an RPC with, read off the signature the * generated client has for it. A unary call (`Range(ctx, in *RangeRequest, * opts ...grpc.CallOption) (*RangeResponse, error)`) is served without the * call options (`Range(ctx, *RangeRequest) (*RangeResponse, error)`); a * streaming one (`Watch(ctx, opts ...grpc.CallOption) (Watch_WatchClient, * error)`) gets its stream in their place and returns an error * (`Watch(Watch_WatchServer) error`). Null when it isn't a client's. */ function goGrpcServerArity(signature: string | undefined): string | null { const parts = goSignatureParts(signature); const opts = parts?.params[parts.params.length - 1]; if (!parts || !opts || !/^(?:[A-Za-z_]\w*\s+)?\.\.\.\s*(?:grpc\.)?CallOption$/.test(opts)) return null; const unary = parts.results.length === 2 && parts.results[0]!.startsWith('*'); return `${parts.params.length - 1}/${unary ? 2 : 1}`; } /** * Go implicit interface satisfaction (#584). Go has no `implements` keyword — a * type satisfies an interface structurally when its method set covers the * interface's. Synthesize the missing `implements` edge (type → interface) by * matching method sets, so impl-navigation works and the interface-dispatch * bridge ({@link interfaceOverrideEdges}, now 'go'-enabled) can link an interface * method call to the concrete overrides, and to the methods embedding promotes. * * The implementers are structs and defined types. A defined type declares * methods as a struct does — gin's `type formSource map[string][]string` has * `TrySet`, prometheus's `type staticDiscoverer []*targetgroup.Group` has `Run`, * an adapter `type HandlerFunc func(…)` has `ServeHTTP` — and is extracted as a * `type_alias` that owns them through `contains` edges. Go gives it none of * the methods declared on the type it is written over, so it is matched by * the methods it declares. A true alias (`type A = B`) is B, not a type of its * own: its `type_alias` owns only methods written with it as the receiver * (`func (c *KumaSDConfig) Name()`), which are B's, and stands in for B with * those. One without any is no implementer. * * Both method sets include what embedding brings in, read off the declared * `extends`/`implements` edge each embedded type is. An interface has the * methods of the interfaces it embeds: etcd's `AuthReadTx` is `RLock` and * `RUnlock` plus all of `UnsafeAuthReader`, so an `RWMutex` is not one. A struct * has the methods promoted from the structs, interfaces and defined types it * embeds, at any depth: counting embedded interfaces alone would drop every * struct that satisfies one through promoted methods. Synthesized edges are * never followed (this pass writes them). * * A type embedded from outside the index leaves only the resolver's failed * `extends` row. The methods of a standard-library type, and of `error`, are * known (./go-stdlib-methods), with their counts: prometheus's `TBRun` is all * of `testing.TB` plus `Run`, not any struct with a `Run`, and a struct * embedding `sync.Mutex` is hugo's `Locker` but not etcd's gRPC `LockClient`, * whose `Lock` takes a context and a request. Any other outside type's * methods are unknown, so a struct embedding the same type has them, and * otherwise only the one type with every method the interface does name is * taken to implement it — kapacitor's `Diagnostic` (a third-party `Logger` * plus `Log`) has no more claim on every struct with a `Log` than on none. * * Methods match by name, and an unexported name by its package too * ({@link goMethodKey}). prometheus has a `refresher { refresh(…) }` in each of * several discovery packages, and only a type with a `refresh` declared in that * package satisfies it, its own or one embedding brings in: aws's * EC2Discovery, with a `refresh` of package aws, is no hetzner refresher. etcd's * gRPC servers sit outside the generated package and still satisfy its * `KVServer`, whose `mustEmbedUnimplementedKVServer` the `UnsafeKVServer` or * `UnimplementedKVServer` they embed declares there. * * Each wanted method also needs a declaration with its parameter and result * counts, read off the stored signatures: Go wants the signatures identical, * and the counts are what the text settles for certain — a cache's `Get(ctx, * key, opts ...OpOption)` is no `Get(id types.ID) Peer`. A standard-library * method carries its counts in the table, so an `io.Writer`'s `Write` asks for * one parameter and two results. A signature that doesn't read rules nothing * out. A gRPC client interface also takes the structs serving its service * (see `wantedArities`), the bridge a client's call crosses to reach its * handler. * * Types are not compared, and a promoted name counts even where Go finds it * ambiguous or hidden by a field — over-approximation accepted, in line with * the other dispatch synthesizers; capped per interface. Empty interfaces * (`any`) are skipped so they don't match every type, and a struct that * embeds the interface keeps the edge its embedding already is. */ async function goImplementsEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield, packageOf: GoPackageOf): Promise { const methodKey = (m: Node): string => goMethodKey(m, packageOf); let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); // Materializes GO types only (the pass is language-gated by the caller), // never the whole struct kind — that array is O(nodes) on struct-heavy repos // like the Linux kernel (#1212). Structs and defined types arrive // interleaved in one canonical order, so the cap below takes implementers // as the files declare them, whatever their kind. const goImplementers: Node[] = []; for (const n of queries.iterateNodesByKindIn(['struct', 'type_alias'], ['go'])) { if ((++scanned255 & 63) === 0) await onYield(); goImplementers.push(n); } const goInterfaces: Node[] = []; for (const i of queries.iterateNodesByKindIn('interface', ['go'])) { if ((++scanned255 & 63) === 0) await onYield(); goInterfaces.push(i); } // The kinds of type whose methods embedding passes on: a struct can embed a // defined type (`type HandlersChain []HandlerFunc`) as well. const typeKind = new Map(); for (const n of goImplementers) typeKind.set(n.id, n.kind); for (const i of goInterfaces) typeKind.set(i.id, 'interface'); const kindOf = (id: string): NodeKind | null => typeKind.get(id) ?? null; // A type's own methods, each by its goMethodKey, so every method set below // holds an unexported name with its package. Each method's stored signature // rides along under the same key for the arity check below. Memoized: an // embedded base is read once, however many types embed it. const ownMemo = new Map>(); const ownSignatures = new Map>(); const ownMethods = (id: string): Set => { let names = ownMemo.get(id); if (!names) { names = new Set(); const signatures = new Map(); for (const e of queries.getOutgoingEdges(id, ['contains'])) { const n = queries.getNodeById(e.target); if (!n || n.kind !== 'method') continue; const key = methodKey(n); names.add(key); const list = signatures.get(key); if (list) list.push(n.signature); else signatures.set(key, [n.signature]); } ownMemo.set(id, names); ownSignatures.set(id, signatures); } return names; }; // The types one embeds: an interface embeds interfaces, a struct any of the // three. Every type's are read up front in a few batched queries rather than // one query per type. const isEmbedding = (e: Edge): boolean => isGoEmbedding(e, kindOf); const NO_EMBEDS: string[] = []; const embedMemo = new Map(); const typeIds = [...typeKind.keys()]; for (let i = 0; i < typeIds.length; i += 2000) { for (const e of queries.getOutgoingEdgesFrom(typeIds.slice(i, i + 2000), ['extends', 'implements'])) { if (!isEmbedding(e)) continue; const targets = embedMemo.get(e.source); if (targets) targets.push(e.target); else embedMemo.set(e.source, [e.target]); } await onYield(); } const embeds = (id: string): string[] => embedMemo.get(id) ?? NO_EMBEDS; // The type and every type it embeds, down to the last level. Go allows a // struct to embed a pointer to itself, or to one embedding it back. const embedClosure = (id: string): string[] => { if (embeds(id).length === 0) return [id]; const reached = new Set([id]); const pending = [id]; while (pending.length > 0) { const at = pending.pop()!; for (const t of embeds(at)) { if (reached.has(t)) continue; reached.add(t); pending.push(t); } } return [...reached]; }; // The types each one embeds from outside the index, as the resolver's failed // `extends` rows: the methods of a standard-library type or of `error`, by // key with their arities, or else the embedded type itself, named by the // package it is written through so that the same embedding elsewhere is // recognized. const outside = new Map[]; opaque: string[] }>(); for (const ref of queries.getUnresolvedReferencesFromNodes(typeIds, ['extends'])) { if (ref.language !== 'go' || !ref.filePath) continue; const name = ref.referenceName; const { written, imported } = goRefQualification({ ...ref, filePath: ref.filePath, language: 'go' }, ctx); const importPath = imported?.source ?? null; const known = imported ? goStdlibMethods(importPath, name) : written ? undefined : goStdlibMethods(null, name); let found = outside.get(ref.fromNodeId); if (!found) outside.set(ref.fromNodeId, (found = { stdlib: [], opaque: [] })); if (known) found.stdlib.push(new Map([...known].map(([m, arity]) => [goStdlibMethodKey(importPath, m), arity]))); else if (imported) found.opaque.push(`${imported.source}.${name}`); else if (written) found.opaque.push(`${written}.${name}`); else found.opaque.push(`${ref.filePath.replace(/\\/g, '/').replace(/\/?[^/]*$/, '')}#${name}`); } await onYield(); // Own methods plus every embedded type's, a standard-library one's too. const NONE_OPAQUE: ReadonlySet = new Set(); const methodNames = (id: string): GoMethodNames => { const types = embedClosure(id); if (types.length === 1 && !outside.has(id)) return { methods: ownMethods(id), opaque: NONE_OPAQUE }; const methods = new Set(); const opaque = new Set(); for (const t of types) { for (const m of ownMethods(t)) methods.add(m); const out = outside.get(t); if (!out) continue; for (const known of out.stdlib) for (const key of known.keys()) methods.add(key); for (const type of out.opaque) opaque.add(type); } return { methods, opaque }; }; const covers = (have: Set, want: Set): boolean => { if (have.size < want.size) return false; for (const m of want) { if (!have.has(m)) return false; } return true; }; const coversOpaque = (have: GoMethodNames, want: GoMethodNames): boolean => { for (const type of want.opaque) { if (!have.opaque.has(type)) return false; } return true; }; // Each method in a type's method set, by its goMethodKey, → the arities // (`params/results`) its declarations there have, or null when one of their // signatures doesn't read (then the name rules nothing out). A method a // standard-library embedding brings has the table's. Built only for the // pairs whose names already match. const arityMemo = new Map | null>>(); const methodArities = (id: string): Map | null> => { let arities = arityMemo.get(id); if (arities) return arities; arities = new Map(); for (const t of embedClosure(id)) { ownMethods(t); for (const [name, signatures] of ownSignatures.get(t) ?? []) { let known = arities.get(name); if (known === null) continue; if (!known) arities.set(name, (known = new Set())); for (const signature of signatures) { const arity = goSignatureArity(signature); if (arity === null) { arities.set(name, null); break; } known.add(arity); } } for (const methods of outside.get(t)?.stdlib ?? []) { for (const [name, arity] of methods) { let known = arities.get(name); if (known === null) continue; if (!known) arities.set(name, (known = new Set())); known.add(arity); } } } arityMemo.set(id, arities); return arities; }; // The arities an implementer may declare each of an interface's methods // with: the interface's own. A gRPC client interface (every method takes // `opts ...grpc.CallOption` last) also takes its service's server side, so // the structs serving it (etcd's `kvServer` for `KVClient`) stay linked and // a client's call keeps reaching the handler that serves it. const wantedArities = (iface: Node): Map | null> => { const own = methodArities(iface.id); const wanted = new Map | null>(); for (const t of embedClosure(iface.id)) { for (const [name, signatures] of ownSignatures.get(t) ?? []) { let arities = wanted.get(name); if (!arities) wanted.set(name, (arities = new Set(own.get(name)))); for (const signature of signatures) { const served = goGrpcServerArity(signature); if (served === null) return own; arities.add(served); } } } // What only a standard-library embedding asks for keeps the table's arity. for (const [name, arities] of own) if (!wanted.has(name)) wanted.set(name, arities); return wanted; }; // Go accepts an implementation only when each method's signature is the // interface's. The stored text settles how many parameters and results // there are: a type with no declaration of a wanted name at a wanted arity // can't satisfy it. const aritiesFit = (typeId: string, wanted: Map | null>): boolean => { const have = methodArities(typeId); for (const [name, arities] of wanted) { const got = have.get(name); if (!arities || !got) continue; let fits = false; for (const arity of arities) { if (got.has(arity)) { fits = true; break; } } if (!fits) return false; } return true; }; // A type without a method, or an embedded type nothing describes, satisfies // no interface this pass looks at. const candidates: Node[] = []; const candidateMethods = new Map(); for (const s of goImplementers) { if ((++scanned255 & 63) === 0) await onYield(); const have = methodNames(s.id); if (have.methods.size + have.opaque.size === 0) continue; candidates.push(s); candidateMethods.set(s.id, have); } for (const iface of goInterfaces) { if ((++scanned255 & 63) === 0) await onYield(); const want = methodNames(iface.id); if (want.methods.size + want.opaque.size === 0) continue; // empty interface (`any`) — would match everything let added = 0; const link = (s: Node): void => { const key = `${s.id}>${iface.id}`; if (seen.has(key)) return; seen.add(key); edges.push({ source: s.id, target: iface.id, kind: 'implements', line: s.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'go-implements', via: iface.name, registeredAt: `${s.filePath}:${s.startLine}` }, }); added++; }; // A struct that needs promoted methods waits for the types declaring all // of them, every defined type among them: under the cap, those are what // the interface-dispatch bridge links a call through the interface to. A // namesake it declares of an unexported method from another package is // not one of them: the method it needs is promoted. One that lacks only // the embedded types nothing names the methods of counts when no other // type has the rest. const throughEmbedding: Node[] = []; let wanted: Map | null> | undefined; let covering = 0; let sole: Node | undefined; for (const s of candidates) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; const have = candidateMethods.get(s.id)!; if (!covers(have.methods, want.methods)) continue; if (!wanted) wanted = wantedArities(iface); if (!aritiesFit(s.id, wanted)) continue; covering++; if (embeds(s.id).includes(iface.id)) continue; // declared by embedding it if (!coversOpaque(have, want)) { if (covering === 1) sole = s; continue; } const own = ownMethods(s.id); if (want.opaque.size > 0 || (own !== have.methods && !covers(own, want.methods))) throughEmbedding.push(s); else link(s); } if (sole && covering === 1 && want.methods.size > 0) throughEmbedding.push(sole); for (const s of throughEmbedding) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; link(s); } } return edges; } /** * Cross-file Go method → receiver-type `contains` edges. In Go a type's methods * are commonly declared in a different file from the `type` declaration itself * (`type User struct{…}` in `user.go`, `func (u *User) Save()` in * `user_store.go`). Extraction attaches the struct→method `contains` edge only * when the receiver type is in the SAME file — the owner lookup in * `tree-sitter.ts` is scoped to the file being parsed — so a cross-file method * is left orphaned from its type (it's still `contains`ed by its file, just not * its struct). That breaks `codegraph_node` member outlines, any * callers/callees/impact traversal that goes through the type's `contains` * edges, and the {@link goImplementsEdges} method-set computation (which derives * a struct's method set from those same edges, so it under-counts interfaces a * cross-file struct satisfies). * * Go guarantees a method's receiver type is declared in the SAME PACKAGE as the * method, and a Go package is a single directory — so this is a deterministic * structural link, not a heuristic: find the same-named type in the method's * own directory and add the missing `contains` edge with no provenance, matching * same-file extraction. Tag synthesis ownership so an incremental * refresh can replace it alongside implicit `implements`. Skips methods that * already have a type parent (the same-file case). (#583, cross-file half) */ async function goCrossFileMethodContainsEdges(queries: QueryBuilder, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); const TYPE_KINDS = new Set(['struct', 'class', 'interface', 'enum', 'type_alias']); const dirOf = (p: string): string => { const i = p.replace(/\\/g, '/').lastIndexOf('/'); return i >= 0 ? p.slice(0, i) : ''; }; for (const method of queries.iterateNodesByKind('method', { languages: ['go'] })) { if ((++scanned255 & 63) === 0) await onYield(); // The receiver type is encoded in the method's qualifiedName as `Recv::name` // (extraction sets `${receiverType}::${name}` for receiver methods). const qn = method.qualifiedName; if (!qn) continue; const sep = qn.lastIndexOf('::'); if (sep <= 0) continue; const receiver = qn.slice(0, sep); if (!receiver) continue; // Already attached to its type (same-file case handled at extraction)? const hasTypeParent = queries .getIncomingEdges(method.id, ['contains']) .some((e) => { const src = queries.getNodeById(e.source); return src != null && TYPE_KINDS.has(src.kind); }); if (hasTypeParent) continue; // Find the receiver type in the SAME directory (= same Go package). Go forbids // duplicate type names within a package, so a same-name same-dir match is // unambiguous; scoping to the directory avoids linking to a same-named type // in another package. const dir = dirOf(method.filePath); const owner = queries .getNodesByName(receiver) .find((n) => n.language === 'go' && TYPE_KINDS.has(n.kind) && dirOf(n.filePath) === dir); if (!owner) continue; const key = `${owner.id}>${method.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: owner.id, target: method.id, kind: 'contains', line: method.startLine, metadata: { synthesizedBy: 'go-method-contains' } }); } return edges; } /** * Kotlin Multiplatform `expect`/`actual` linking. A `common` source set declares * `expect fun foo()` / `expect class Bar`; each platform source set (jvm, native, * js, …) provides an `actual` implementation with the IDENTICAL fully-qualified * name in a different file. Callers in common code resolve to the `expect` * declaration, so every `actual` impl ends up with zero dependents — invisible to * impact/affected even though editing it can break every caller of the API. * * Synthesize a `calls` edge from the common declaration to each platform `actual` * (mirroring the interface-impl bridge: abstract → concrete), so editing a * platform impl surfaces the common `expect` and its callers, and the impl file * participates in the graph. * * `expect`/`actual` are captured onto the node's `decorators` list at extraction * (kotlin.ts `extractModifiers`). Members of an `expect class` are NOT themselves * keyword-marked, so the declaration side is matched as the same-FQN, same-kind * node that is NOT marked `actual`. Requiring an `actual`-marked counterpart also * gates out plain cross-file overloads (neither side is marked). */ // Kinds that an `expect`/`actual` pair may legitimately straddle. `expect class` // is routinely fulfilled by an `actual typealias` (e.g. `actual typealias // CancellationException = …`, `actual typealias SchedulerTask = Task`), so a // strict kind match would miss those one-line alias files. Same-FQN + the // `actual` marker already gates out unrelated symbols, so widening to the // type-like kinds is safe. const KMP_TYPE_KINDS = new Set(['class', 'interface', 'struct', 'enum', 'type_alias']); function kmpKindsCompatible(a: string, b: string): boolean { return a === b || (KMP_TYPE_KINDS.has(a) && KMP_TYPE_KINDS.has(b)); } async function kotlinExpectActualEdges(queries: QueryBuilder, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); // SQL-side language+decorator pre-filter, streamed. The old // `getAllNodes().filter(...)` hydrated the ENTIRE node table into one array // just to find kotlin `actual` declarations — on a 2M-node graph that alone // exceeded Node's default heap and killed the index (#1212). The LIKE // pre-filter can over-match (substring), so the exact decorator check stays. for (const act of queries.iterateNodesByLanguageWithDecorator('kotlin', 'actual')) { if ((++scanned255 & 63) === 0) await onYield(); if (!act.decorators?.includes('actual')) continue; let added = 0; for (const cand of queries.getNodesByQualifiedNameExact(act.qualifiedName)) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; // The declaration side: same FQN + compatible kind, a different file, NOT // itself an `actual` (that would be a sibling platform impl, not the decl). if (cand.language !== 'kotlin' || cand.id === act.id) continue; if (!kmpKindsCompatible(cand.kind, act.kind) || cand.filePath === act.filePath) continue; if (cand.decorators?.includes('actual')) continue; const key = `${cand.id}>${act.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: cand.id, target: act.id, kind: 'calls', line: cand.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'kotlin-expect-actual', via: act.name, registeredAt: `${act.filePath}:${act.startLine}`, }, }); added++; } } return edges; } /** The methods a Go struct runs for a method it does not declare, and the line of the embedding they come through. */ interface GoPromotion { methods: Node[]; line: number; } /** * Which embedded type's method a Go struct runs for a method it does not * declare, picked the way Go's selector picks it: breadth-first through the * struct's embeddings, the shallowest depth holding the method wins, and it * selects nothing when it occurs more than once at that depth, one type * reached along two paths included. A type met at a shallower depth is not * walked again. An embedded interface brings its whole method set at its own * depth, and a method it provides is a dynamic call once more, so that is no * promotion either. Struct fields are not in the graph: a field that hides a * promoted method is not seen. The method is asked for by its * {@link goMethodKey}: a namesake of an unexported method declared in another * package is another method, so it neither provides nor hides it. */ function goPromotions( queries: QueryBuilder, methodsOf: (id: string) => Node[], methodKey: (m: Node) => string ): (structId: string, key: string) => GoPromotion | null { const kinds = new Map(); const kindOf = (id: string): NodeKind | null => { let kind = kinds.get(id); if (kind === undefined) { const n = queries.getNodeById(id); kind = n?.language === 'go' && (n.kind === 'struct' || n.kind === 'interface' || n.kind === 'type_alias') ? n.kind : null; kinds.set(id, kind); } return kind; }; const embedMemo = new Map(); const embeds = (id: string): Edge[] => { let out = embedMemo.get(id); if (!out) { const targets = new Set(); out = queries.getOutgoingEdges(id, ['extends', 'implements']).filter((e) => { if (!isGoEmbedding(e, kindOf) || targets.has(e.target)) return false; targets.add(e.target); return true; }); embedMemo.set(id, out); } return out; }; const ifaceMemo = new Map>(); const ifaceMethods = (id: string): Set => { let names = ifaceMemo.get(id); if (!names) { names = new Set(); const reached = new Set([id]); const pending = [id]; while (pending.length > 0) { const at = pending.pop()!; for (const m of methodsOf(at)) names.add(methodKey(m)); for (const e of embeds(at)) { if (reached.has(e.target)) continue; reached.add(e.target); pending.push(e.target); } } ifaceMemo.set(id, names); } return names; }; const provides = (id: string, key: string): boolean => kindOf(id) === 'interface' ? ifaceMethods(id).has(key) : methodsOf(id).some((m) => methodKey(m) === key); const memo = new Map(); return (structId, key) => { const memoKey = `${structId}>${key}`; const hit = memo.get(memoKey); if (hit !== undefined) return hit; let found: GoPromotion | null = null; // Each type at the current depth, with how many paths reach it and the // line of the struct's own embedding the first of them starts with. let level = new Map([[structId, { paths: 1, line: 0 }]]); const met = new Set([structId]); for (let depth = 0; level.size > 0; depth++) { const next = new Map(); for (const [id, at] of level) { if (kindOf(id) === 'interface') continue; // its embeddings are its method set for (const e of embeds(id)) { if (met.has(e.target)) continue; const to = next.get(e.target); if (to) to.paths += at.paths; else next.set(e.target, { paths: at.paths, line: depth === 0 ? (e.line ?? 0) : at.line }); } } let paths = 0; let provider: string | undefined; for (const [id, at] of next) { met.add(id); if (!provides(id, key)) continue; paths += at.paths; provider = id; } if (provider !== undefined) { if (paths === 1 && kindOf(provider) !== 'interface') { found = { methods: methodsOf(provider).filter((m) => methodKey(m) === key), line: next.get(provider)!.line }; } break; } level = next; } memo.set(memoKey, found); return found; }; } async function interfaceOverrideEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield, packageOf: GoPackageOf): Promise { const goKey = (m: Node): string => goMethodKey(m, packageOf); let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); // Memoized: a popular base interface's method list is otherwise re-fetched // once per implementer (dubbo-style hub interfaces have hundreds), and the // memo only ever serves reads. Same rows, same order — byte-identical. const methodsMemo = new Map(); const methodsOf = (classId: string): Node[] => { const hit = methodsMemo.get(classId); if (hit) return hit; const methods = queries .getOutgoingEdges(classId, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n && n.kind === 'method'); methodsMemo.set(classId, methods); return methods; }; // A Swift protocol's methods live in its extensions: requirements are not // extracted as methods, and `extension EventMonitor { func request(…) }` is // where the default implementations a conformer overrides are. A class-kind // node sharing a protocol's name is one of its extensions. const protocolMemo = new Map(); const baseMethodsOf = (base: Node): Node[] => { if (base.language !== 'swift' || base.kind !== 'interface') return methodsOf(base.id); const hit = protocolMemo.get(base.id); if (hit) return hit; const methods = [ ...methodsOf(base.id), ...queries .getNodesByName(base.name) .filter((n) => n.language === 'swift' && n.kind === 'class') .flatMap((n) => methodsOf(n.id)), ]; protocolMemo.set(base.id, methods); return methods; }; // Of a class's same-named methods, the ones that can override one of a // base's overloads (#2663): Java, Kotlin, C# and Scala make an override // repeat the parameters of what it overrides. Asked only for a name that // is overloaded on either side. const overridesOf = overrideFilter(ctx); const nameCounts = new Map>(); const declaredNamed = (base: Node, name: string): number => { let counts = nameCounts.get(base.id); if (!counts) { counts = new Map(); for (const m of baseMethodsOf(base)) counts.set(m.name, (counts.get(m.name) ?? 0) + 1); nameCounts.set(base.id, counts); } return counts.get(name) ?? 0; }; // A Go struct also satisfies an interface with the methods its embedded // types promote into it (goImplementsEdges counts them), and a call through // the interface then runs the embedded type's method. Those links are made // after the loop, from what the struct's cap has left, so every override // keeps its edge, and a provider that implements the interface itself keeps // its own. const goPromotion = goPromotions(queries, methodsOf, goKey); const promoted: { cls: Node; methods: Node[]; left: number }[] = []; // Concrete-side kinds vary by language: `class` covers Java / Kotlin / // C# / TS / Swift-classes / Scala-classes; `struct` covers Swift value // types that conform to protocols. Iterate both. A Go defined type // (`type HandlerFunc func(…)`) holds its methods as a struct does, as a // `type_alias`; that kind is walked for Go alone. const concreteKinds = ['class', 'struct', 'union'] as const; const concrete = [ ...concreteKinds.map((kind) => () => queries.iterateNodesByKind(kind)), () => queries.iterateNodesByKindIn('type_alias', ['go']), ]; for (const nodesOfKind of concrete) { for (const cls of nodesOfKind()) { if ((++scanned255 & 63) === 0) await onYield(); // A class can only emit here if it HAS a supertype edge — check that // (one edge query) before materializing its methods: most classes in a // typical graph extend/implement nothing and skip in one hop. const sups = queries.getOutgoingEdges(cls.id, ['implements', 'extends']); if (sups.length === 0) continue; const implMethods = methodsOf(cls.id).filter((n) => IFACE_OVERRIDE_LANGS.has(n.language) && !(['javascript', 'typescript'].includes(n.language) && n.name === 'constructor') ); // A Go struct that satisfies an interface (a synthesized edge) may do so // with promoted methods alone. Its declared `implements` edges are the // interfaces it embeds, which provide whatever it lacks themselves. const goStruct = cls.language === 'go' && (cls.kind === 'struct' || cls.kind === 'type_alias'); if (implMethods.length === 0 && !(goStruct && sups.some((s) => s.provenance === 'heuristic'))) continue; // Group impl methods by name to handle OVERLOADS: an interface `list()` and // `list(params)` are distinct nodes and a call may resolve to either, so // link every base overload → every same-name impl overload (keying by name // alone would drop all but one and miss the resolved overload). const methodKey = cls.language === 'go' ? goKey : (m: Node): string => m.name; const implByKey = new Map(); for (const m of implMethods) { const key = methodKey(m); const arr = implByKey.get(key); if (arr) arr.push(m); else implByKey.set(key, [m]); } // TRANSITIVE supertypes: `A implements B`, `B extends C` → A also overrides // C's members (a call typed to C dispatches to A's impl). BFS over the // implements/extends edges, visited-guarded for diamonds/cycles and // depth-capped — real hierarchies are shallow, and a mid-chain node that // fails the language check is still traversed THROUGH (its own supertypes // may be valid bases). const supertypes: Node[] = []; const visited = new Set([cls.id]); const queue: Array<{ id: string; depth: number }> = sups.map((s) => ({ id: s.target, depth: 1 })); while (queue.length > 0) { const cur = queue.shift()!; if (visited.has(cur.id)) continue; visited.add(cur.id); const base = queries.getNodeById(cur.id); if (base && base.id !== cls.id && IFACE_OVERRIDE_LANGS.has(base.language)) supertypes.push(base); if (cur.depth >= MAX_SUPERTYPE_DEPTH) continue; for (const e of queries.getOutgoingEdges(cur.id, ['implements', 'extends'])) { if (!visited.has(e.target)) queue.push({ id: e.target, depth: cur.depth + 1 }); } } for (const base of supertypes) { if (cls.language === 'go' && base.kind !== 'interface') continue; const promotes = goStruct && base.kind === 'interface' && sups.some((edge) => edge.target === base.id && edge.provenance === 'heuristic'); let added = 0; const unmatched: Node[] = []; for (const bm of baseMethodsOf(base)) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; const impls = implByKey.get(methodKey(bm)); if (!impls) { if (promotes) unmatched.push(bm); continue; } const overloaded = impls.length > 1 || declaredNamed(base, bm.name) > 1; for (const m of overloaded ? overridesOf(bm, impls) : impls) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (bm.id === m.id) continue; // A JS/TS static method overrides only a static one, and an // instance method only an instance one (#2761): B's `s()` and the // `static s()` of `class A extends B` are unrelated, and a call to // one never runs the other. if (STATIC_SPLIT_LANGS.has(m.language) && (bm.isStatic === true) !== (m.isStatic === true)) continue; const key = `${bm.id}>${m.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: bm.id, target: m.id, kind: 'calls', line: bm.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'interface-impl', via: m.name, registeredAt: `${m.filePath}:${m.startLine}` }, }); added++; } } if (unmatched.length > 0 && added < MAX_CALLBACKS_PER_CHANNEL) { promoted.push({ cls, methods: unmatched, left: MAX_CALLBACKS_PER_CHANNEL - added }); } } } } // The wiring site of a promoted method is the struct's embedding it comes // through: `type blockSeriesSet struct{ blockBaseSeriesSet }`. promoted.sort((a, b) => (a.cls.filePath < b.cls.filePath ? -1 : a.cls.filePath > b.cls.filePath ? 1 : 0) || a.cls.startLine - b.cls.startLine || (a.cls.id < b.cls.id ? -1 : a.cls.id > b.cls.id ? 1 : 0), ); for (const { cls, methods, left } of promoted) { if ((++scanned255 & 63) === 0) await onYield(); let budget = left; for (const bm of methods) { if (budget <= 0) break; const promotion = goPromotion(cls.id, goKey(bm)); if (!promotion) continue; for (const m of promotion.methods) { if (budget <= 0) break; const key = `${bm.id}>${m.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: bm.id, target: m.id, kind: 'calls', line: bm.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'interface-impl', via: m.name, promotedInto: cls.name, registeredAt: `${cls.filePath}:${promotion.line || cls.startLine}`, }, }); budget--; } } } return edges; } /** * Go gRPC stub → impl bridge. The protoc-gen-go-grpc codegen emits an * `UnimplementedXxxServer` struct in `*_grpc.pb.go` carrying one method * per service RPC; the real handler is a hand-written struct in another * file (`x/bank/keeper/msg_server.go::msgServer.Send` in cosmos-sdk). * Go's structural typing means no `implements` edge exists for our * resolver to follow, so `trace("Send","SendCoins")` lands on the * empty stub and reports "no path" (validated empirically — the cosmos * Q1 r1 trace failure that drove this work). * * Bridge: for each `UnimplementedXxxServer` whose RPC-method names are * a SUBSET of some other Go struct's method names, emit `calls` edges * `stub.method → impl.method` (paired by name). Excludes the gRPC * internal markers `mustEmbedUnimplementedXxxServer` and * `testEmbeddedByValue`, and skips candidate impls that themselves * live in a generated file (their `xxxClient` / sibling stubs would * otherwise look like impls). * * Multiple candidates is allowed and capped at MAX_CALLBACKS_PER_CHANNEL — * a service often has both a production impl and one or more test * mocks; linking to all preserves trace utility without false-favoring. * * Provenance: `heuristic`, `synthesizedBy: 'go-grpc-stub-impl'`. The * stub's source line is the wiring site shown in the trace trail. */ async function goGrpcStubImplEdges(queries: QueryBuilder, onYield: MaybeYield): Promise { let scanned255 = 0; const edges: Edge[] = []; const seen = new Set(); const STUB_RE = /^Unimplemented.*Server$/; // gRPC internal-helper methods that appear on every Unimplemented*Server; // not part of the service contract, so exclude when computing the RPC-method // signature used to match impls. const isInternalMarker = (n: string) => n.startsWith('mustEmbed') || n === 'testEmbeddedByValue'; // Methods directly contained by each Go struct, name-only. Built once. const methodNamesByStruct = new Map>(); const methodNodesByStruct = new Map(); const goStructs: Node[] = []; for (const s of queries.iterateNodesByKind('struct', { languages: ['go'] })) { if ((++scanned255 & 63) === 0) await onYield(); goStructs.push(s); const ms = queries .getOutgoingEdges(s.id, ['contains']) .map((e) => queries.getNodeById(e.target)) .filter((n): n is Node => !!n && n.kind === 'method'); methodNodesByStruct.set(s.id, ms); methodNamesByStruct.set(s.id, new Set(ms.map((m) => m.name))); } for (const stub of goStructs) { if (!STUB_RE.test(stub.name)) continue; // The stub MUST live in a generated file — that's what tells us this is // a protoc-emitted scaffold rather than someone naming a struct // `UnimplementedXxxServer` by hand. Without this gate we'd also bridge // such hand-written structs and create misleading edges. if (!isGeneratedFile(stub.filePath)) continue; const stubMethods = (methodNodesByStruct.get(stub.id) ?? []).filter( (m) => !isInternalMarker(m.name), ); if (stubMethods.length === 0) continue; const stubMethodNames = stubMethods.map((m) => m.name); for (const cand of goStructs) { if (cand.id === stub.id) continue; // Skip generated-file candidates — they're siblings (msgClient, // UnsafeMsgServer, …) whose method sets coincidentally match. if (isGeneratedFile(cand.filePath)) continue; const candNames = methodNamesByStruct.get(cand.id); if (!candNames) continue; // Subset: every RPC method must exist on the candidate by name. // Signature-level match would tighten this further, but name-match // alone already gives one-to-one pairing in real codebases because // gRPC method-name sets are highly distinctive (Send + MultiSend + // UpdateParams + SetSendEnabled is unique to bank's MsgServer). if (!stubMethodNames.every((n) => candNames.has(n))) continue; const candMethods = methodNodesByStruct.get(cand.id) ?? []; let added = 0; for (const sm of stubMethods) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; for (const cm of candMethods) { if (added >= MAX_CALLBACKS_PER_CHANNEL) break; if (cm.name !== sm.name) continue; const key = `${sm.id}>${cm.id}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: sm.id, target: cm.id, kind: 'calls', line: sm.startLine, provenance: 'heuristic', metadata: { synthesizedBy: 'go-grpc-stub-impl', via: cm.name, registeredAt: `${cm.filePath}:${cm.startLine}`, }, }); added++; } } } } return edges; } /** Kinds a JSX tag can name. A tag that resolves only to a type is markup we drop. */ const JSX_CHILD_KINDS = new Set(['component', 'function', 'class']); /** * The languages a JSX tag can plausibly name a component in. Preferred over a * same-named symbol in another language, never required — a React Native tag * whose only match is the native class it bridges to (`requireNativeComponent`) * still links there. */ const JSX_CHILD_LANGUAGES = [...JS_FAMILY, 'vue', 'svelte']; /** * Whether a JSX tag can render `node` (`jsxChild`): a script's component, * function or class named with a tag's capital, or any component, which a * default import names under a name of its own. A tag in a file a sync never * touched may name one the sync adds, so adding one redraws the JSX edges. * (A `.vue` or `.svelte` file redraws them on any change.) */ export function isJsxChildCandidate(node: Pick): boolean { return JSX_CHILD_KINDS.has(node.kind) && JS_FAMILY.includes(node.language) && (node.kind === 'component' || /^[A-Z]/.test(node.name)); } function languageForJsxFile(file: string): Language { if (file.endsWith('.tsx')) return 'tsx'; if (/\.[cm]?ts$/.test(file)) return 'typescript'; if (file.endsWith('.jsx')) return 'jsx'; if (file.endsWith('.vue')) return 'vue'; if (file.endsWith('.svelte')) return 'svelte'; return 'javascript'; } /** `localName` → the project file it is imported from, for one file's imports. */ /** * `resolveImportPath` answers for one synthesis run, keyed by language, * importing directory and specifier: the same specifiers repeat across * thousands of files, and each miss probes the disk for extensions and index * files (0.3 s of existsSync on trezor-suite). Null outside a run. */ let importPathMemo: Map | null = null; function resolveImportPathMemo(source: string, file: string, language: Language, ctx: ResolutionContext): string | null { if (!importPathMemo) return resolveImportPath(source, file, language, ctx); const key = `${language}\0${file.slice(0, file.lastIndexOf('/') + 1)}\0${source}`; let hit = importPathMemo.get(key); if (hit === undefined) { hit = resolveImportPath(source, file, language, ctx); importPathMemo.set(key, hit); } return hit; } function importedFrom(ctx: ResolutionContext, file: string, language: Language): Map { const out = new Map(); for (const im of ctx.getImportMappings(file, language)) { // The mappings name the module as written; the file it is comes from the // same resolution the import resolver uses (aliases, extensions, index files). const resolved = im.resolvedPath ?? resolveImportPathMemo(im.source, file, language, ctx); if (resolved) out.set(im.localName, resolved); } return out; } /** * Does `file` import `name` from a package outside the repository (`import { * Button } from 'antd'`)? A package means one the file's package.json, or an * enclosing one, declares, under a specifier no project file answers. That is * the test the name matcher applies to calls and values. What such a name * renders is the package's, never a project symbol that shares the name. */ function importedFromPackage(ctx: ResolutionContext, name: string, file: string): boolean { const language = languageForJsxFile(file); const binding = ctx.getImportMappings(file, language).find((m) => m.localName === name); return !!binding && ctx.isOutOfRepoImport?.(binding.source, file, language) === true; } /** * The module of the project `file` imports `name` from, and the export the * import names: `default` for a default import, else the imported name. * Undefined when the file imports no such name from a module the index holds: * a package's (`importedFromPackage`), or a path only the app's build resolves. */ function projectImport(ctx: ResolutionContext, name: string, file: string): { module: string; exported: string } | undefined { const language = languageForJsxFile(file); const binding = ctx.getImportMappings(file, language).find((m) => m.localName === name); if (!binding || binding.isNamespace) return undefined; const module = binding.resolvedPath ?? resolveImportPath(binding.source, file, language, ctx); if (!module || !ctx.getNodesInFile(module).some((n) => n.kind === 'file')) return undefined; return { module, exported: binding.isDefault || binding.exportedName === 'default' ? 'default' : binding.exportedName }; } /** * The component a JSX tag names, among every node that shares the name. * * A tag is written in one file, and that file already says which `FrameCard` it * means: the one it declares, or the one it imports. Taking the FIRST node of * that name — which is what this did — is a coin flip once a name repeats, and * it costs twice over. The parent gets an edge to a component it never renders, * and the component it does render is left with no caller at all, so every walk * back from that subtree dead-ends: on an Expo app whose `` was one * of two, the folder sheet's `openBackgroundNoiseDetail` stood alone on Screens * with no screen behind it, while the edge pointed at an unrelated card in * another sheet. * * Same file first — a small component declared beside its use is the commonest * shape, and the one an import can never disambiguate. Then a name the file * imports from a package: that package's component, which is no node here, so * nothing. On SigNoz, antd's `