diff --git a/docs/guides/javascript/javascript-application-workflows.md b/docs/guides/javascript/javascript-application-workflows.md index 295dedab5c5..4335e1aeb10 100644 --- a/docs/guides/javascript/javascript-application-workflows.md +++ b/docs/guides/javascript/javascript-application-workflows.md @@ -406,7 +406,15 @@ search, semantic tracing, and version comparison use the preserved values. Event and listener nodes likewise preserve the complete event name in `properties.event_name`. Event role keys use the same reserved-prefix string digest rule, scoped to the emitter; repeated registrations, removals, and -dispatches keep one event per exact emitter/name pair. Long event labels use +dispatches keep one event per exact emitter/name pair. Class `this` receivers +have separate instance and static candidate families. Possible local bases, +including conditional bases, connect matching sides; a shared unknown external +base does not connect unrelated classes. Member arrows inherit their side, +while computed keys, decorators and heritage use the enclosing receiver. +All `this` identities remain incomplete, with candidate relations and explicit +event unknowns. Receiver rebinding and external/cross-file inheritance remain +unresolved. New analyses change class `this` event IDs; select fresh graph IDs. +Long event labels use `event`, and listener labels use the shorter of `:` and `:listener`. Dynamic names remain `null` with explicit uncertainty. Query the preserved name or select IDs from the parent graph. Previously stored graphs keep their diff --git a/src/domain/javascript/javascriptSemanticAnalysis.this_emitters.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.this_emitters.test.ts new file mode 100644 index 00000000000..e9f557e6241 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticAnalysis.this_emitters.test.ts @@ -0,0 +1,157 @@ +import { expect, it } from "vitest"; + +import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js"; + +const emitters = (source: string) => { + const ir = analyzeJavaScriptSemantics(source); + expect(ir.coverage.status).toBe("complete"); + const groups = new Map(); + for (const { emitterKey, method, resolution } of ir.eventOperations) + groups.set(emitterKey, [ + ...(groups.get(emitterKey) ?? []), + `${method}:${resolution}`, + ]); + return [...groups.values()]; +}; + +it("shares each class receiver side across members without joining static and instance fields", () => { + expect( + emitters(`class E { + field = this.on('ready', handler); + constructor() { this.emit('ready'); } + get value() { return this.emit('ready'); } + #remove() { this.off('ready', handler); } + run() { (() => this.emit('ready'))(); } + static field = this.on('ready', handler); + static { this.emit('ready'); } + static run() { this.off('ready', handler); } + }`), + ).toEqual([ + [ + "on:partial", + "emit:partial", + "emit:partial", + "off:partial", + "emit:partial", + ], + ["on:partial", "emit:partial", "off:partial"], + ]); +}); + +it("retains separate static and instance candidate families across local inheritance", () => { + expect( + emitters(` + class Base { + run() { this.on('ready', handler); } + static run() { this.on('ready', handler); } + } + class Child extends Base { + run() { this.emit('ready'); } + static run() { this.emit('ready'); } + } + class Other { run() { this.emit('ready'); } } + `), + ).toEqual([ + ["on:partial", "emit:partial"], + ["on:partial", "emit:partial"], + ["emit:partial"], + ]); +}); + +it.each([ + "flag ? Base : Other", + "Base || Other", + "flag ? Base : external", + "(0, Base)", +])("retains possible local base event links for %s", (base) => { + const groups = emitters(` + class Base { run() { this.on('ready', handler); } } + class Other { run() { this.off('ready', handler); } } + class Child extends (${base}) { run() { this.emit('ready'); } } + `); + expect(groups[0]).toContain("on:partial"); + expect(groups[0]).toContain("emit:partial"); + expect(groups.flat()).toHaveLength(3); + expect(groups).toHaveLength(base.includes("Other") ? 1 : 2); +}); + +it("does not join classes merely because they name the same unknown external base", () => { + expect( + emitters(` + class A extends external { field = this.on(name, handler); } + class B extends external { field = this.emit('ready'); } + `), + ).toEqual([["on:unresolved"], ["emit:partial"]]); +}); + +it("keeps nested ordinary functions separate while member arrows inherit their class side", () => { + expect( + emitters(`class E { + field = () => this.on('ready', handler); + run() { + (() => this.emit('ready'))(); + function inner() { this.emit('ready'); } + } + static field = () => this.on('ready', handler); + static run() { (() => this.emit('ready'))(); } + }`), + ).toEqual([ + ["on:partial", "emit:partial"], + ["emit:partial"], + ["on:partial", "emit:partial"], + ]); +}); + +it("keeps class definition expressions outside member receiver families", () => { + expect( + emitters(`function install() { + this.on('ready', handler); + @decorate(this.emit('ready')) + class E extends (this.emit('ready'), Base) { + @decorate(this.emit('ready')) run() { this.on('ready', handler); } + [this.emit('ready')]() { this.emit('ready'); } + [this.emit('ready')] = this.emit('ready'); + } + }`), + ).toEqual([ + [ + "on:partial", + "emit:partial", + "emit:partial", + "emit:partial", + "emit:partial", + "emit:partial", + ], + ["on:partial", "emit:partial", "emit:partial"], + ]); +}); + +it("evaluates computed object-method keys in the enclosing receiver", () => { + expect( + emitters(`function install() { + this.on('ready', handler); + return { + [this.emit('ready')]() { this.emit('ready'); } + }; + }`), + ).toEqual([["on:partial", "emit:partial"], ["emit:partial"]]); +}); + +it("terminates cyclic class candidates with partial event links", () => { + expect( + emitters(` + class A extends B { run() { this.on('ready', handler); } } + class B extends A { run() { this.emit('ready'); } } + `), + ).toEqual([["on:partial", "emit:partial"]]); +}); + +it("retains candidate links through a long local class chain", () => { + const classes = ["class C0 { run() { this.on('ready', handler); } }"]; + for (let index = 1; index <= 500; index++) + classes.push(`class C${index} extends C${index - 1} {}`); + classes.push("class Child extends C500 { run() { this.emit('ready'); } }"); + expect(emitters(classes.join("\n"))).toEqual([ + ["on:partial", "emit:partial"], + ]); +}); diff --git a/src/domain/javascript/javascriptSemanticAsyncEffects.ts b/src/domain/javascript/javascriptSemanticAsyncEffects.ts index 9888c70b929..837d3ea1fd0 100644 --- a/src/domain/javascript/javascriptSemanticAsyncEffects.ts +++ b/src/domain/javascript/javascriptSemanticAsyncEffects.ts @@ -8,6 +8,7 @@ import type { JavaScriptSemanticTimerOperation, } from "./javascriptSemanticIr.js"; import { createSemanticCallableIdStack } from "./javascriptSemanticCallableStack.js"; +import { createSemanticThisReceiverKey } from "./javascriptSemanticThisReceivers.js"; import { readExactJavaScriptLiteral, semanticStaticPropertyName, @@ -135,13 +136,14 @@ export const collectJavaScriptSemanticAsyncEffects = ( ]); const callableIds = new Set(callables.map(({ callableId }) => callableId)); const callableStack = createSemanticCallableIdStack(callableIds); + const thisReceiverKey = createSemanticThisReceiverKey(state); const ancestors: t.Node[] = []; traverseJavaScriptValueAst(program, state.erasedSyntaxNodes, { enter: (node, parent) => { callableStack.enter(node, parent); if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) { const ownerCallableId = callableStack.callables.at(-1) ?? null; - collectEvent(node, ownerCallableId, state, events); + collectEvent(node, ownerCallableId, state, events, thisReceiverKey); collectTimer({ node, ownerCallableId, @@ -202,6 +204,7 @@ const collectEvent = ( ownerCallableId: string | null, state: JavaScriptSemanticAnalysisState, output: JavaScriptSemanticEventOperation[], + thisReceiverKey: (node: t.ThisExpression) => string, ): void => { const member = dataEffectMemberCallee(node); if (member === null) return; @@ -225,7 +228,7 @@ const collectEvent = ( rejectsSemanticEventListener(listenerArgument) ) return; - const emitter = emitterIdentity(member.object, state); + const emitter = emitterIdentity(member.object, state, thisReceiverKey); const eventName = dataEffectLiteralString(eventArgument); output.push({ eventId: `event:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`, @@ -260,6 +263,7 @@ const eventKind = ( const emitterIdentity = ( node: t.Expression | t.Super, state: JavaScriptSemanticAnalysisState, + thisReceiverKey: (node: t.ThisExpression) => string, ): { readonly key: string; readonly bindingId: string | null; @@ -299,16 +303,9 @@ const emitterIdentity = ( }; } if (t.isThisExpression(node)) { - let owner = state.parentsByNode.get(node); - while ( - owner !== undefined && - !t.isClass(owner) && - !(t.isFunction(owner) && !t.isArrowFunctionExpression(owner)) - ) - owner = state.parentsByNode.get(owner); // Lexical receiver ownership does not establish one runtime instance. return { - key: `this:${owner?.start ?? -1}:${owner?.end ?? -1}`, + key: thisReceiverKey(node), bindingId: null, complete: false, }; diff --git a/src/domain/javascript/javascriptSemanticThisReceivers.ts b/src/domain/javascript/javascriptSemanticThisReceivers.ts new file mode 100644 index 00000000000..6fbf4d1689f --- /dev/null +++ b/src/domain/javascript/javascriptSemanticThisReceivers.ts @@ -0,0 +1,138 @@ +import * as t from "@babel/types"; + +import { semanticMethodDefinitionExpression } from "./javascriptSemanticEvaluationOrder.js"; +import { semanticClassCandidates } from "./javascriptSemanticObjectReferences.js"; +import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js"; + +type ClassNode = t.ClassDeclaration | t.ClassExpression; +interface Receiver { + readonly owner: t.Node | undefined; + readonly side?: "instance" | "static"; +} + +/** Class sides and possible local bases define candidates, never runtime equality. */ +export const createSemanticThisReceiverKey = ( + state: JavaScriptSemanticAnalysisState, +): ((node: t.ThisExpression) => string) => { + const receivers = new WeakMap(); + let classComponents: ReturnType | undefined; + return (node) => { + const pending: t.Node[] = []; + let current: t.Node | undefined = node; + let receiver: Receiver = { owner: undefined }; + while (current !== undefined) { + const cached = receivers.get(current); + if (cached !== undefined) { + receiver = cached; + break; + } + pending.push(current); + const parent = state.parentsByNode.get(current); + if (t.isDecorator(current)) { + // Decorators, including parameter decorators, run at class definition. + current = parent; + while (current !== undefined && !t.isClass(current)) + current = state.parentsByNode.get(current); + continue; + } + const boundary = receiverBoundary(parent, current, state); + if (boundary !== undefined) { + receiver = boundary; + break; + } + current = parent; + } + for (const visited of pending) receivers.set(visited, receiver); + const { owner, side } = receiver; + if (t.isClass(owner)) { + classComponents ??= candidateClassComponents(state); + const family = classComponents(owner); + return `this:${family.start ?? -1}:${family.end ?? -1}:${side}`; + } + return `this:${owner?.start ?? -1}:${owner?.end ?? -1}`; + }; +}; + +const receiverBoundary = ( + parent: t.Node | undefined, + child: t.Node, + state: JavaScriptSemanticAnalysisState, +): Receiver | undefined => { + if (parent === undefined) return undefined; + if (t.isFunction(parent) && !t.isArrowFunctionExpression(parent)) { + if (semanticMethodDefinitionExpression(parent, child)) return undefined; + return t.isClassMethod(parent) || t.isClassPrivateMethod(parent) + ? classReceiver(parent, state) + : { owner: parent }; + } + if ( + t.isStaticBlock(parent) || + ((t.isClassProperty(parent) || + t.isClassPrivateProperty(parent) || + t.isClassAccessorProperty(parent)) && + parent.value === child) + ) + return classReceiver(parent, state); + return undefined; +}; + +const classReceiver = ( + member: + | t.ClassMethod + | t.ClassPrivateMethod + | t.ClassProperty + | t.ClassPrivateProperty + | t.ClassAccessorProperty + | t.StaticBlock, + state: JavaScriptSemanticAnalysisState, +): Receiver | undefined => { + const body = state.parentsByNode.get(member); + const owner = body === undefined ? undefined : state.parentsByNode.get(body); + return t.isClass(owner) + ? { + owner, + side: t.isStaticBlock(member) || member.static ? "static" : "instance", + } + : undefined; +}; + +/** External bases do not join classes; conditional local bases retain every candidate. */ +const candidateClassComponents = (state: JavaScriptSemanticAnalysisState) => { + const parents = new Map(); + const sizes = new Map(); + const representatives = new Map(); + const root = (node: ClassNode): ClassNode => { + const path: ClassNode[] = []; + let current = node; + let parent = parents.get(current); + while (parent !== undefined && parent !== current) { + path.push(current); + current = parent; + parent = parents.get(current); + } + for (const visited of path) parents.set(visited, current); + return current; + }; + for (const node of state.callableNodesById.values()) { + if (!t.isClass(node) || node.superClass == null) continue; + for (const base of semanticClassCandidates(node.superClass, state)) { + let left = root(node); + let right = root(base); + if (left === right) continue; + if ((sizes.get(left) ?? 1) < (sizes.get(right) ?? 1)) + [left, right] = [right, left]; + const first = representatives.get(left) ?? left; + const second = representatives.get(right) ?? right; + parents.set(right, left); + sizes.set(left, (sizes.get(left) ?? 1) + (sizes.get(right) ?? 1)); + representatives.set( + left, + (first.start ?? -1) <= (second.start ?? -1) ? first : second, + ); + } + } + return (node: ClassNode): ClassNode => { + const component = root(node); + return representatives.get(component) ?? component; + }; +}; diff --git a/tests/acceptance/applications/javascriptThisEmitters.test.ts b/tests/acceptance/applications/javascriptThisEmitters.test.ts new file mode 100644 index 00000000000..12b425c8622 --- /dev/null +++ b/tests/acceptance/applications/javascriptThisEmitters.test.ts @@ -0,0 +1,156 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; + +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; +import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +const fixtureSource = ` + class Base { + run() { this.on('ready', () => {}); } + static run() { this.on('ready', () => {}); } + } + class Other { + run() { this.on('ready', () => {}); } + static run() { this.on('ready', () => {}); } + } + class Child extends (flag ? Base : Other) { + run() { this.emit('ready'); } + static run() { this.emit('ready'); } + } + class ExternalA extends external { field = this.on('ready', () => {}); } + class ExternalB extends external { field = this.emit('ready'); } + class Sides { + field = this.on('sides', () => {}); + static field = this.emit('sides'); + } + const stable = createEmitter(); + stable.on('ready', () => {}); stable.emit('ready'); + function install() { + this.on('computed', () => {}); + return { + [this.emit('computed')]() { this.emit('computed'); } + }; + } + `; + +cliTest( + "preserves receiver sides, local bases and computed-key evaluation through CLI and stdio MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-this-emitters-"); + await writeFile(join(root, "main.mjs"), fixtureSource); + const response = await cli.run({ + arguments: [ + "analyze-javascript-application", + root, + "--artifact-format", + "directory", + "--json", + ], + timeoutMs: 60_000, + }); + expect(response.exitCode).toBe(0); + const contract = toolContract("analyze_javascript_application"); + const cliEvidence = contract.outputSchema.parse(response.json); + const cliGraph = javascriptApplicationAnalysisResultSchema.parse( + cliEvidence.normalized_result, + ).semantic_graph; + const { client, call } = await connectLocalToolsMcp(); + const result = await call("analyze_javascript_application", { + input_path: root, + format: "directory", + }); + expect(result.isError).not.toBe(true); + const evidence = contract.outputSchema.parse(result.structuredContent); + const text = result.content.find((item) => item.type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text result"); + expect(contract.outputSchema.parse(JSON.parse(text.text))).toEqual( + evidence, + ); + const graph = javascriptApplicationAnalysisResultSchema.parse( + evidence.normalized_result, + ).semantic_graph; + expect(graph).toEqual(cliGraph); + const ready = graph.nodes.filter( + (n) => n.kind === "event" && n.properties.event_name === "ready", + ); + expect(ready).toHaveLength(5); + const eventRelations = (id: string) => + graph.relations.filter( + (r) => + ["registers-listener", "dispatches-candidate"].includes(r.relation) && + (r.source_node_id === id || r.target_node_id === id), + ); + const stable = ready.find((n) => + String(n.properties.emitter_key).startsWith("binding:"), + ); + if (stable === undefined) throw new Error("Stable emitter was lost"); + expect(eventRelations(stable.node_id).map((r) => r.resolution)).toEqual([ + "resolved", + "resolved", + ]); + const receivers = ready.filter((n) => n !== stable); + expect( + receivers.map((n) => eventRelations(n.node_id).length).sort(), + ).toEqual([1, 1, 3, 3]); + for (const event of receivers) { + expect( + eventRelations(event.node_id).every( + (r) => r.resolution === "candidate", + ), + ).toBe(true); + expect( + graph.unknowns.some( + (u) => u.family === "event" && u.node_id === event.node_id, + ), + ).toBe(true); + } + const sides = graph.nodes.filter( + (n) => n.kind === "event" && n.properties.event_name === "sides", + ); + expect(sides).toHaveLength(2); + for (const event of sides) { + expect(eventRelations(event.node_id)).toHaveLength(1); + expect(eventRelations(event.node_id)[0]?.resolution).toBe("candidate"); + } + const computed = graph.nodes.filter( + (n) => n.kind === "event" && n.properties.event_name === "computed", + ); + expect(computed).toHaveLength(2); + const registration = computed.find((n) => + eventRelations(n.node_id).some( + (r) => r.relation === "registers-listener", + ), + ); + if (registration === undefined) + throw new Error("Outer receiver registration was lost"); + expect( + eventRelations(registration.node_id) + .map((r) => r.relation) + .sort(), + ).toEqual(["dispatches-candidate", "registers-listener"]); + expect( + computed + .filter((n) => n !== registration) + .flatMap((n) => eventRelations(n.node_id)) + .map((r) => r.relation), + ).toEqual(["dispatches-candidate"]); + for (const event of computed) { + expect( + eventRelations(event.node_id).every( + (r) => r.resolution === "candidate", + ), + ).toBe(true); + expect( + graph.unknowns.some( + (u) => u.family === "event" && u.node_id === event.node_id, + ), + ).toBe(true); + } + await client.ping(); + }, + 120_000, +);