diff --git a/src/application/javascript/JavaScriptSemanticGraphAbruptDestructuring.test.ts b/src/application/javascript/JavaScriptSemanticGraphAbruptDestructuring.test.ts index 77d1c3d3af..9e465ab29d 100644 --- a/src/application/javascript/JavaScriptSemanticGraphAbruptDestructuring.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphAbruptDestructuring.test.ts @@ -31,12 +31,21 @@ it.each([ ["null", "{} = {}"], ["undefined", "{} = null"], ["void 0", "[] = undefined"], + ["aliasedNull", "{} = {}"], + ["true ? null : {}", "{}"], + ["undefined", "{} = (false ? {} : null)"], + ["undefined", "{} = aliasedNull"], + ["null", "{}", '["bad"]'], + ["captured", "{}", "bad", "captured = {};"], ] as const)( "leaves bindings after %s matched against %s unproven", - (value, pattern) => { + (value, pattern, key = "bad", afterCapture?: string) => { const inspect = projection(` + const aliasedNull = null; + let captured = null; const model = { bad: ${value}, mode: "one" }; - const { mode: before, bad: ${pattern}, mode: selected } = model; + ${afterCapture ?? ""} + const { mode: before, ${key}: ${pattern}, mode: selected } = model; `); expect(inspect("before")).toMatchObject({ resolution: "resolved", @@ -53,10 +62,15 @@ it.each([ it.each([ ["const model = { bad: 0, mode: 'one' };", "{}"], ["const model = { bad: {}, mode: 'one' };", "{}"], + ["const model = { bad: true ? {} : null, mode: 'one' };", "{}"], ["const model = { bad: [], mode: 'one' };", "[]"], ["const model = { bad: undefined, mode: 'one' };", "{} = {}"], ["const model = { bad: 0, mode: 'one' };", "{} = null"], ["const undefined = 0; const model = { bad: undefined, mode: 'one' };", "{}"], + [ + "let captured = {}; const model = { bad: captured, mode: 'one' }; captured = null;", + "{}", + ], ] as const)( "preserves the reachable sibling for %s against %s", (setup, pattern) => { diff --git a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts index 4e1f0dac9b..9e00b53941 100644 --- a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts @@ -415,7 +415,6 @@ it.each(["{}", "unknownSource"])( ); it.each([ - ["ordinary array", "", "resolved"], ["prototype read alone", "Object.getPrototypeOf([].values());", "resolved"], [ "one iterator's own next", @@ -715,24 +714,6 @@ it.each([ }, ); -it("leaves an earlier destructuring dependency intact before an iterator prototype write", () => { - const graph = graphForJavaScript(` - const config = ["original"]; - const [selected] = config; - Object.getPrototypeOf([].values()).next = () => ({ value: "other", done: false }); - `); - const selected = graph.nodes.find( - ({ kind, label }) => kind === "binding" && label === "selected", - ); - expect( - graph.relations.find( - (relation) => - relation.relation === "destructures" && - relation.target_node_id === selected?.node_id, - ), - ).toMatchObject({ resolution: "resolved" }); -}); - it.each([ ["declaration", "const [selected] = config;", "resolved"], ["assignment", "let selected; [selected] = config;", "resolved"], diff --git a/src/domain/javascript/javascriptSemanticObjects.ts b/src/domain/javascript/javascriptSemanticObjects.ts index c0c9179568..8f992a9954 100644 --- a/src/domain/javascript/javascriptSemanticObjects.ts +++ b/src/domain/javascript/javascriptSemanticObjects.ts @@ -20,7 +20,10 @@ import { type JavaScriptSemanticInitializer, } from "./javascriptSemanticState.js"; import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js"; -import { clearSemanticValueCaches } from "./javascriptSemanticValues.js"; +import { + clearSemanticValueCaches, + evaluateSemanticExpression, +} from "./javascriptSemanticValues.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; import { createSemanticReadPresenceQuery, @@ -184,6 +187,20 @@ const collectMember = ( ); }; +/** Distinguish null from undefined because only undefined selects a default. */ +const destructuringNullishKind = ( + expression: t.Node, + state: JavaScriptSemanticAnalysisState, + isNullish: ObjectCollectionContext["isNullish"], +): "null" | "undefined" | null => { + const { node } = unwrapJavaScriptExpression(expression); + if (t.isNullLiteral(node)) return "null"; + if (isNullish(node)) return "undefined"; + if (isKnownDefinedSource(node)) return null; + const value = evaluateSemanticExpression(node, state); + return value.status === "literal" && value.value === null ? "null" : null; +}; + const collectDestructuring = ( root: t.Node, initializer: t.Node | null | undefined, @@ -262,12 +279,17 @@ const collectDestructuring = ( ? unwrapJavaScriptExpression(occurrence.left).node : occurrence; const plainObjectPath = next.plainObjectPath === true && !hasDefault; - // Only undefined selects the default, whose result can also be nullish. - if ( + // A bounded evaluation can prove the original data slot nullish. + const nullish = selected !== undefined && - (t.isObjectPattern(pattern) || t.isArrayPattern(pattern)) && - isNullish(selected) && - (!hasDefault || t.isNullLiteral(selected) || isNullish(occurrence.right)) + (t.isObjectPattern(pattern) || t.isArrayPattern(pattern)) + ? destructuringNullishKind(selected, state, isNullish) + : null; + if ( + nullish !== null && + (nullish === "null" || + !hasDefault || + destructuringNullishKind(occurrence.right, state, isNullish) !== null) ) { abrupt = true; ownSlot = undefined; @@ -314,11 +336,16 @@ const collectDestructuring = ( }); continue; } + // Computing a known key with effects (for example, void call()) + // can still invalidate the source slots before the property lookup. + const ownLookup = + !prop.computed || + t.isPureish(unwrapJavaScriptExpression(prop.key).node); pending.push({ pattern: prop.value, path: [...path, name], - plainObjectPath: plainObjectPath && !prop.computed, - lookup: prop.computed ? "unproven" : "own", + plainObjectPath: plainObjectPath && ownLookup, + lookup: ownLookup ? "own" : "unproven", }); } continue; diff --git a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts index 9613cf8c9e..4bfe597b86 100644 --- a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts +++ b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts @@ -1,8 +1,9 @@ import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; -import { z } from "zod"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js"; import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; @@ -53,6 +54,14 @@ const nullishDefaultSource = ` const { value: reachedBeforeDefault, stop: {} = null, value: unreachedAfterDefault } = record; `; +const aliasedAndComputedReceiverSource = ` + const stop = null; + const aliased = { stop, value: "present" }; + const { value: beforeAliasedNull, stop: {} = {}, value: afterAliasedNull } = aliased; + const computed = { stop: true ? null : {}, value: "present" }; + const { value: beforeComputedNull, ["stop"]: {}, value: afterComputedNull } = computed; +`; + const firstDefaultSource = ` const defined = [0, ["one"]]; const [used = (defined[1][0] = "dormant"), [inactiveDefaultElement]] = defined; @@ -106,116 +115,7 @@ const outerDeclarationSource = ` let pending; `; -const additionalFixtures = [ - ["iterator-close.js", iteratorCloseSource], - ["array-prototype-alias.js", arrayPrototypeAliasSource], - ["abrupt-object-pattern.js", abruptObjectPatternSource], - ["nullish-receiver.js", nullishReceiverSource], - ["nullish-default.js", nullishDefaultSource], - ["first-default.js", firstDefaultSource], - ["immutable-target.js", immutableTargetSource], - ["class-name-target.js", classNameTargetSource], - ["uninitialized-target.js", uninitializedTargetSource], - ["declarator-order.js", declaratorOrderSource], - ["outer-let.js", outerDeclarationSource], -] as const; - -const expectedDependencies = [ - ["declared", ["a"]], - ["a", ["a"]], - ["plain", ["a", "0"]], - ["fallback", ["a", "0"]], - ["scalar", ["b"]], - ["ordinary", ["0"]], - ["beforeImmutable", ["0"]], - ["afterImmutable", ["2"], "candidate"], - ["beforeClassName", ["0"]], - ["afterClassName", ["2"], "candidate"], - ["afterOuterClass", ["1"]], - ["beforeUninitialized", ["0"]], - ["afterUninitialized", ["2"], "candidate"], - ["initializedEarlier", ["1"]], - ["uninitializedLater", ["1"], "candidate"], - ["afterReady", ["1"]], - ["beforeOuterLet", ["0"]], - ["afterOuterLet", ["2"], "candidate"], - ["arrayAssigned", ["0"]], - ["elided", ["1"]], - ["projected", ["items", "0"]], - ["arrayObject", ["0", "mode"]], - ["nestedElement", ["items", "0"]], - ["siblingObjectElement", ["sibling", "0"]], - ["projectedNumericInnerElement", ["pairs", "0", "0"]], - ["unreachedSibling", ["sibling", "0"], "candidate"], - ["reachedBeforeNullish", ["value"]], - ["unreachedAfterNullish", ["value"], "candidate"], - ["reachedBeforeDefault", ["value"]], - ["unreachedAfterDefault", ["value"], "candidate"], - ["innerElement", ["0", "0"]], - ["siblingInnerElement", ["1", "0"]], - ["inactiveDefaultElement", ["1", "0"]], - ["activeDefaultElement", ["1", "0"], "candidate"], - ["spreadElement", ["1"]], - ["aliasedPrototypeElement", ["0", "0"], "candidate"], - ["selected", ["0"], "candidate"], - ["beforeClose", ["label"]], - ["consumed", ["items", "0", "mode"]], - ["afterClose", ["items", "1", "mode"], "candidate"], - ["storedAfterClose", ["next", "mode"], "candidate"], - ["abruptAfterClose", ["1", "mode"], "candidate"], - ["replacedBeforeClose", ["next", "mode"]], - ["replacedAfterClose", ["next", "mode"], "candidate"], - ["projectedAfterAcquisition", ["parent", "next", "mode"], "candidate"], -] as const; - -const tracedBindings = [ - "declared", - "ordinary", - "beforeImmutable", - "afterImmutable", - "beforeClassName", - "afterClassName", - "afterOuterClass", - "beforeUninitialized", - "afterUninitialized", - "initializedEarlier", - "uninitializedLater", - "afterReady", - "beforeOuterLet", - "afterOuterLet", - "arrayAssigned", - "elided", - "projected", - "arrayObject", - "nestedElement", - "siblingObjectElement", - "projectedNumericInnerElement", - "unreachedSibling", - "reachedBeforeNullish", - "unreachedAfterNullish", - "reachedBeforeDefault", - "unreachedAfterDefault", - "innerElement", - "siblingInnerElement", - "inactiveDefaultElement", - "activeDefaultElement", - "spreadElement", - "aliasedPrototypeElement", - "selected", - "beforeClose", - "consumed", - "afterClose", -] as const; - -cliTest( - "traces proved destructuring dependencies and leaves custom iteration uncertain", - async ({ cli }) => { - const root = await createTestTempDirectory( - "rea-js-destructuring-evidence-", - ); - await writeFile( - join(root, "main.js"), - ` +const mainSource = ` const src = { a: 1 }; const { a: declared, laterDefault = 0 } = src; let a; @@ -271,17 +171,92 @@ cliTest( const after = ["second"]; let selected; [selected] = after; - `, + `; + +const sources = [ + ["main.js", mainSource], + ["iterator-close.js", iteratorCloseSource], + ["array-prototype-alias.js", arrayPrototypeAliasSource], + ["abrupt-object-pattern.js", abruptObjectPatternSource], + ["nullish-receiver.js", nullishReceiverSource], + ["nullish-default.js", nullishDefaultSource], + ["aliased-computed-receiver.js", aliasedAndComputedReceiverSource], + ["first-default.js", firstDefaultSource], + ["immutable-target.js", immutableTargetSource], + ["class-name-target.js", classNameTargetSource], + ["uninitialized-target.js", uninitializedTargetSource], + ["declarator-order.js", declaratorOrderSource], + ["outer-let.js", outerDeclarationSource], +] as const; + +const expectedDependencies = [ + ["declared", ["a"]], + ["a", ["a"]], + ["plain", ["a", "0"]], + ["fallback", ["a", "0"]], + ["scalar", ["b"]], + ["ordinary", ["0"]], + ["beforeImmutable", ["0"]], + ["afterImmutable", ["2"], "candidate"], + ["beforeClassName", ["0"]], + ["afterClassName", ["2"], "candidate"], + ["afterOuterClass", ["1"]], + ["beforeUninitialized", ["0"]], + ["afterUninitialized", ["2"], "candidate"], + ["initializedEarlier", ["1"]], + ["uninitializedLater", ["1"], "candidate"], + ["afterReady", ["1"]], + ["beforeOuterLet", ["0"]], + ["afterOuterLet", ["2"], "candidate"], + ["arrayAssigned", ["0"]], + ["elided", ["1"]], + ["projected", ["items", "0"]], + ["arrayObject", ["0", "mode"]], + ["nestedElement", ["items", "0"]], + ["siblingObjectElement", ["sibling", "0"]], + ["projectedNumericInnerElement", ["pairs", "0", "0"]], + ["unreachedSibling", ["sibling", "0"], "candidate"], + ["reachedBeforeNullish", ["value"]], + ["unreachedAfterNullish", ["value"], "candidate"], + ["reachedBeforeDefault", ["value"]], + ["unreachedAfterDefault", ["value"], "candidate"], + ["beforeAliasedNull", ["value"]], + ["afterAliasedNull", ["value"], "candidate"], + ["beforeComputedNull", ["value"]], + ["afterComputedNull", ["value"], "candidate"], + ["innerElement", ["0", "0"]], + ["siblingInnerElement", ["1", "0"]], + ["inactiveDefaultElement", ["1", "0"]], + ["activeDefaultElement", ["1", "0"], "candidate"], + ["spreadElement", ["1"]], + ["aliasedPrototypeElement", ["0", "0"], "candidate"], + ["selected", ["0"], "candidate"], + ["beforeClose", ["label"]], + ["consumed", ["items", "0", "mode"]], + ["afterClose", ["items", "1", "mode"], "candidate"], + ["storedAfterClose", ["next", "mode"], "candidate"], + ["abruptAfterClose", ["1", "mode"], "candidate"], + ["replacedBeforeClose", ["next", "mode"]], + ["replacedAfterClose", ["next", "mode"], "candidate"], + ["projectedAfterAcquisition", ["parent", "next", "mode"], "candidate"], +] as const; + +cliTest( + "traces proved destructuring dependencies and leaves custom iteration uncertain", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-js-destructuring-evidence-", ); - for (const [path, source] of additionalFixtures) + for (const [path, source] of sources) await writeFile(join(root, path), source); const output = await cli.run({ arguments: ["analyze-javascript-application", root, "--json"], }); expect(output.exitCode).toBe(0); - const { normalized_result: result } = z - .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) - .parse(output.json); + const application = parseEvidence(output.json); + const result = javascriptApplicationAnalysisResultSchema.parse( + application.normalized_result, + ); const graph = result.semantic_graph; for (const [name, path, resolution = "resolved"] of expectedDependencies) { const binding = graph.nodes.find( @@ -312,17 +287,29 @@ cliTest( ), ).toMatchObject({ resolution: "resolved" }); const queryPath = join(root, "query.json"); - for (const name of tracedBindings) { + for (const [name, followsDependency] of [ + ["beforeAliasedNull", true], + ["afterAliasedNull", false], + ] as const) { const binding = graph.nodes.find( ({ kind, label }) => kind === "binding" && label === name, ); + if (binding === undefined) throw new Error(`Missing binding ${name}`); + const dependency = graph.relations.find( + ({ relation, target_node_id }) => + relation === "destructures" && target_node_id === binding.node_id, + ); + if (dependency === undefined) + throw new Error(`Missing dependency for ${name}`); + const seed = { kind: "semantic-node", node_id: binding.node_id }; await writeFile( queryPath, JSON.stringify({ - application: output.json, + application, query: { - seed: { kind: "semantic-node", node_id: binding?.node_id }, + seed, direction: "backward-provenance", + allowed_relations: ["destructures"], }, }), ); @@ -330,24 +317,31 @@ cliTest( arguments: ["trace-javascript-semantics", queryPath, "--json"], }); expect(trace.exitCode, trace.stderr).toBe(0); - const relation = { - normalized_result: { - relations: expect.arrayContaining([ - expect.objectContaining({ - relation: "destructures", - target_node_id: binding?.node_id, - }), - ]), - }, - }; - if ( - expectedDependencies.some( - ([binding, , resolution]) => - binding === name && resolution === "candidate", - ) - ) - expect(trace.json).not.toMatchObject(relation); - else expect(trace.json).toMatchObject(relation); + const evidence = parseEvidence(trace.json); + expect(evidence.evidence_links).toEqual([application.evidence_id]); + const traced = javaScriptSemanticTraceResultSchema.parse( + evidence.normalized_result, + ); + expect(traced).toMatchObject({ + source_evidence_id: application.evidence_id, + evidence_links: [application.evidence_id], + source_graph_id: graph.graph_id, + seed, + seed_node_ids: [binding.node_id], + direction: "backward-provenance", + }); + expect(traced.relations).toEqual(followsDependency ? [dependency] : []); + const reached = followsDependency + ? [binding.node_id, dependency.source_node_id] + : [binding.node_id]; + expect(traced.nodes.map(({ node_id }) => node_id).sort()).toEqual( + reached.sort(), + ); + if (!followsDependency) + expect(traced).toMatchObject({ + status: "ambiguous", + coverage: { status: "partial" }, + }); } }, );