diff --git a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts index 7368c7f7ac..943c005414 100644 --- a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts @@ -1,6 +1,106 @@ import { expect, it } from "vitest"; import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js"; +it.each([ + "const { mode: selected, fallback = 0 } = config;", + 'const { mode: selected, ["fallback"]: later } = config;', + "const { mode: selected, nested: { fallback = 0 } } = config;", + "const { mode: selected, ...later } = config;", + "const { mode: selected, accessor: later } = config;", + "let selected; const target = {}; ({ mode: selected, fallback: target.value } = config);", +])( + "retains a proved read before a later unproven pattern operation", + (read) => { + const graph = graphForJavaScript(` + const config = { mode: "strict", fallback: 0, nested: { fallback: 0 }, get accessor() { return 0; } }; + ${read} + config.mode = "loose"; + `); + const selected = graph.nodes.find( + ({ kind, label }) => kind === "binding" && label === "selected", + ); + expect( + graph.relations.find( + (edge) => + edge.relation === "destructures" && + edge.target_node_id === selected?.node_id, + ), + ).toMatchObject({ resolution: "resolved" }); + }, +); + +it("leaves the next read uncertain after a source-mutating assignment target", () => { + const graph = graphForJavaScript(` + const config = { first: 1, mode: "strict" }; + let selected; + const target = { set value(_) { delete config.mode; } }; + ({ first: target.value, mode: selected } = config); + config.mode = "loose"; + `); + expect( + graph.relations.find(({ relation }) => relation === "destructures"), + ).toMatchObject({ resolution: "candidate" }); +}); + +it.each([ + { read: "const { mode: selected } = config;", relation: "destructures" }, + { + read: "let selected; ({ mode: selected } = config);", + relation: "destructures", + }, + { read: "const selected = config.mode;", relation: "reads-property" }, +] as const)( + "keeps earlier $relation at its read position", + ({ read, relation }) => { + const source = 'const config = { mode: "strict", other: 0 };'; + for (const [before, after, resolution] of [ + ["", 'config.mode = "loose";', "resolved"], + ["", "config.other = 1;", "resolved"], + ["delete config.mode;", "", "candidate"], + ["mutate(config);", "", "candidate"], + ]) { + const graph = graphForJavaScript( + [source, before, read, after].join("\n"), + ); + expect( + graph.relations.find((edge) => edge.relation === relation), + ).toMatchObject({ resolution }); + } + }, +); + +it("keeps a direct nested data-slot dependency after a later write", () => { + const graph = graphForJavaScript(` + const config = { nested: { mode: "strict" } }; + const { mode: selected } = config.nested; + config.nested.mode = "loose"; + `); + expect( + graph.relations.find(({ relation }) => relation === "destructures"), + ).toMatchObject({ resolution: "resolved" }); +}); + +it.each([ + `const config = { mode: "strict" }; const { first = (delete config.mode), mode: selected } = config;`, + `const config = { get first() { delete this.mode; return {}; }, mode: "strict" }; + const { first: {}, mode: selected } = config;`, +])( + "leaves a dependency uncertain after an effectful earlier pattern lookup", + (source) => { + const graph = graphForJavaScript(source + 'config.mode = "loose";'); + const selected = graph.nodes.find( + ({ kind, label }) => kind === "binding" && label === "selected", + ); + expect( + graph.relations.find( + (edge) => + edge.relation === "destructures" && + edge.target_node_id === selected?.node_id, + ), + ).toMatchObject({ resolution: "candidate" }); + }, +); + it("links declared and assigned destructuring bindings to their exact source slots", () => { const cases = [ { pattern: "{ a: selected }", source: "{ a: 1 }", path: ["a"] }, diff --git a/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts b/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts index 7f414fb7bc..e52379d863 100644 --- a/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphObjectProjection.ts @@ -120,7 +120,7 @@ const objectTarget = ( objectNode: slot, slot, slotApplicability: "resolved", - presence: fact.presence, + presence: operation.sourcePresence ?? fact.presence, receiverResolved: receiver.presence === "present" && semanticContainer(receiver.value) !== null, diff --git a/src/domain/javascript/javascriptSemanticEffectLog.ts b/src/domain/javascript/javascriptSemanticEffectLog.ts index e235299536..54dce39507 100644 --- a/src/domain/javascript/javascriptSemanticEffectLog.ts +++ b/src/domain/javascript/javascriptSemanticEffectLog.ts @@ -484,6 +484,14 @@ export const semanticBindingEffectGeneration = ( binding: JavaScriptSemanticBindingState, ): number => binding.memberWrites.length + binding.escapedPaths.length; +/** A read may need to distinguish a captured reference from its merged value. */ +export const hasRecordedReferenceEffects = ( + binding: JavaScriptSemanticBindingState, + state: JavaScriptSemanticAnalysisState, +): boolean => + semanticBindingEffectGeneration(binding) > 0 || + state.opaqueEffects.byScope.size > 0; + /** * Recorded ambient writes to `global` paths, as intrinsic paths with * non-literal keys as null. A write recorded without a site is placed at the @@ -967,6 +975,62 @@ const opaqueCodeMayReachBindingReference = ( ): boolean => semanticBindingMayHaveOpaqueEffect(binding, state, capturePoint, "reference"); +const observesCapturedWrite = ( + binding: JavaScriptSemanticBindingState, + capture: t.Node | undefined, + node: t.Node | undefined, + parents: JavaScriptSemanticAnalysisState["parentsByNode"], +): boolean => + capture === undefined || + node === undefined || + !semanticBindingEffectFollowsCapture(binding, capture, node, parents); + +const observesCapturedEscape = ( + binding: JavaScriptSemanticBindingState, + capture: t.Node | undefined, + node: t.Node | undefined, + parents: JavaScriptSemanticAnalysisState["parentsByNode"], +): boolean => + capture === undefined || + !semanticEscapeFollowsCapture(binding, capture, node, parents); + +/** Whether a captured own slot or its receiver may have changed before the read. */ +export const capturedBindingPathMayHaveChanged = ( + binding: JavaScriptSemanticBindingState, + path: readonly string[], + capture: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + return ( + opaqueCodeMayReachBindingReference(binding, state, capture) || + semanticOpaqueGlobalMayHaveChanged(capture, state) || + semanticSomeEffectPathCandidate( + binding.memberWrites, + path, + (effect) => + semanticEffectPathMatches(effect.path, path) && + observesCapturedWrite( + binding, + capture, + effect.node, + state.parentsByNode, + ), + ) || + semanticSomeEffectPathCandidate( + binding.escapedPaths, + path, + (effect) => + semanticEffectPathMatches(effect.path, path) && + observesCapturedEscape( + binding, + capture, + effect.node, + state.parentsByNode, + ), + ) + ); +}; + /** * The value of `binding`'s reference as a read captured at `capturePoint` * observes it, after the recorded effects that may precede the capture: @@ -983,16 +1047,8 @@ export const applySemanticBindingReferenceEffects = ( let projected = invalidateSemanticMutationPaths( value, binding.memberWrites - .filter( - ({ node }) => - capturePoint === undefined || - node === undefined || - !semanticBindingEffectFollowsCapture( - binding, - capturePoint, - node, - state.parentsByNode, - ), + .filter(({ node }) => + observesCapturedWrite(binding, capturePoint, node, state.parentsByNode), ) .map(({ path }) => path), ); @@ -1000,8 +1056,7 @@ export const applySemanticBindingReferenceEffects = ( // Escapes only invalidate object references; other lattice values survive. if (projected.status !== "object" && projected.status !== "array") break; if ( - capturePoint !== undefined && - semanticEscapeFollowsCapture( + !observesCapturedEscape( binding, capturePoint, escape.node, diff --git a/src/domain/javascript/javascriptSemanticIr.ts b/src/domain/javascript/javascriptSemanticIr.ts index 73f27286b2..81ae813645 100644 --- a/src/domain/javascript/javascriptSemanticIr.ts +++ b/src/domain/javascript/javascriptSemanticIr.ts @@ -403,6 +403,8 @@ export interface JavaScriptSemanticResourceOperation { export interface JavaScriptSemanticObjectOperation { readonly objectOperationId: string; readonly kind: "read" | "write" | "spread" | "destructure"; + /** Proven own data slot at this operation's read rather than in the merged value. */ + readonly sourcePresence?: "present"; readonly location: JavaScriptSourceRange; readonly ownerCallableId: string | null; readonly objectBindingId: string | null; diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 2b15053a67..7c7b89a9dd 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -558,7 +558,9 @@ const computeDirectInitializerPosition = ( if ( t.isAssignmentExpression(parent) && parent.right === node && - t.isIdentifier(parent.left) + (t.isIdentifier(parent.left) || + (parent.operator === "=" && + (t.isObjectPattern(parent.left) || t.isArrayPattern(parent.left)))) ) { return directMutationPosition(parent, parents); } diff --git a/src/domain/javascript/javascriptSemanticObjects.ts b/src/domain/javascript/javascriptSemanticObjects.ts index da3d9527b3..0acb90e20a 100644 --- a/src/domain/javascript/javascriptSemanticObjects.ts +++ b/src/domain/javascript/javascriptSemanticObjects.ts @@ -18,6 +18,7 @@ import { } from "./javascriptSemanticState.js"; import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; +import { createSemanticReadPresenceQuery } from "./javascriptSemanticValues.js"; /** Recover bounded static property reads, writes, spreads, and destructuring. */ export const collectJavaScriptSemanticObjects = ( @@ -32,6 +33,7 @@ export const collectJavaScriptSemanticObjects = ( state, output, writeTargets: new Map(), + readPresence: createSemanticReadPresenceQuery(state), }; traverseJavaScriptValueAst(program, state.erasedSyntaxNodes, { enter: (node, parent) => { @@ -65,24 +67,12 @@ export const collectJavaScriptSemanticObjects = ( t.isVariableDeclarator(node) && (t.isObjectPattern(node.id) || t.isArrayPattern(node.id)) ) - collectDestructuring( - node.id, - node.init, - ownerCallableId, - state, - output, - ); + collectDestructuring(node.id, node.init, ownerCallableId, context); else if ( t.isAssignmentExpression(node, { operator: "=" }) && (t.isObjectPattern(node.left) || t.isArrayPattern(node.left)) ) - collectDestructuring( - node.left, - node.right, - ownerCallableId, - state, - output, - ); + collectDestructuring(node.left, node.right, ownerCallableId, context); }, exit: (node) => callableStack.exit(node), }); @@ -93,6 +83,7 @@ interface ObjectCollectionContext { readonly state: JavaScriptSemanticAnalysisState; readonly output: JavaScriptSemanticObjectOperation[]; readonly writeTargets: Map; + readonly readPresence: ReturnType; } const collectMember = ( @@ -132,6 +123,11 @@ const collectMember = ( { node, kind: write ? "write" : "read", + provenOwnSlot: + !write && + identity.path !== null && + context.readPresence(identity.bindingId, node)?.(identity.path) === + true, ownerCallableId, objectBindingId: identity.bindingId, targetBindingId: null, @@ -146,32 +142,64 @@ const collectDestructuring = ( root: t.Node, initializer: t.Node | null | undefined, ownerCallableId: string | null, - state: JavaScriptSemanticAnalysisState, - output: JavaScriptSemanticObjectOperation[], + { state, output, readPresence }: ObjectCollectionContext, ): void => { const source = expressionObjectIdentity(initializer, state); - const pending: { + let ownSlot = + initializer == null || source.path === null + ? undefined + : readPresence(source.bindingId, initializer); + // An unsupported property still occupies its place in the pattern's + // evaluation order, even when it cannot produce a graph operation. + const pending: ({ readonly pattern: t.Node; readonly path: readonly string[]; - }[] = [{ pattern: root, path: [] }]; + readonly lookup?: "own" | "unproven"; + } | null)[] = [{ pattern: root, path: [] }]; while (pending.length > 0) { const next = pending.pop(); if (next === undefined) break; + if (next === null) { + ownSlot = undefined; + continue; + } const { path } = next; + const propertyPath = + source.path === null ? null : [...source.path, ...path]; + if ( + next.lookup === "unproven" || + (next.lookup === "own" && + ownSlot !== undefined && + propertyPath !== null && + !ownSlot(propertyPath)) + ) + ownSlot = undefined; const occurrence = unwrapJavaScriptExpression(next.pattern).node; + if (t.isAssignmentPattern(occurrence)) ownSlot = undefined; const pattern = t.isAssignmentPattern(occurrence) ? unwrapJavaScriptExpression(occurrence.left).node : occurrence; if (t.isObjectPattern(pattern)) { for (const property of pattern.properties.toReversed()) { - if (!t.isObjectProperty(property)) continue; + if (!t.isObjectProperty(property)) { + pending.push(null); + continue; + } const name = semanticStaticPropertyKey(property.key, property.computed); - if (name !== null) - pending.push({ pattern: property.value, path: [...path, name] }); + if (name === null) { + pending.push(null); + continue; + } + pending.push({ + pattern: property.value, + path: [...path, name], + lookup: property.computed ? "unproven" : "own", + }); } continue; } if (t.isArrayPattern(pattern)) { + ownSlot = undefined; for (let index = pattern.elements.length - 1; index >= 0; index -= 1) { const element = pattern.elements[index]; if ( @@ -183,17 +211,25 @@ const collectDestructuring = ( } continue; } - if (!t.isIdentifier(pattern)) continue; + if (!t.isIdentifier(pattern)) { + ownSlot = undefined; + continue; + } + const targetBinding = resolveSemanticBindingState( + state, + pattern, + pattern.name, + ); + if (targetBinding === undefined) ownSlot = undefined; addObjectOperation( { node: occurrence, kind: "destructure", ownerCallableId, objectBindingId: source.bindingId, - targetBindingId: - resolveSemanticBindingState(state, pattern, pattern.name) - ?.bindingId ?? null, - propertyPath: source.path === null ? null : [...source.path, ...path], + targetBindingId: targetBinding?.bindingId ?? null, + propertyPath, + provenOwnSlot: ownSlot !== undefined, }, state, output, @@ -208,6 +244,7 @@ interface AddObjectOperationInput { readonly objectBindingId: string | null; readonly targetBindingId: string | null; readonly propertyPath: readonly string[] | null; + readonly provenOwnSlot?: boolean; } const addObjectOperation = ( @@ -224,6 +261,9 @@ const addObjectOperation = ( String(input.node.end ?? -1), ].join(":"), kind: input.kind, + ...(input.provenOwnSlot === true + ? { sourcePresence: "present" as const } + : {}), location: range(input.node), ownerCallableId: input.ownerCallableId, objectBindingId: input.objectBindingId, diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 37a3cafc4e..5a8dce97af 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -1,6 +1,8 @@ import type { JavaScriptSemanticPrecision } from "./javascriptSemanticPrecision.js"; import { applySemanticBindingReferenceEffects, + capturedBindingPathMayHaveChanged, + hasRecordedReferenceEffects, opaqueCodeMayRebindBinding, } from "./javascriptSemanticEffectLog.js"; import * as t from "@babel/types"; @@ -39,6 +41,7 @@ import { readSemanticRequireOriginCandidate } from "./javascriptSemanticRequireO import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { readExactJavaScriptLiteral, + staticObjectPropertyReader, semanticStaticPropertyKey, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; @@ -261,6 +264,51 @@ export const evaluateSemanticExpression = ( ); }; +/** Prove a direct data slot at a read without evaluating the entire object at each read. */ +export const createSemanticReadPresenceQuery = ( + state: JavaScriptSemanticAnalysisState, +) => { + const readers = new WeakMap< + t.ObjectExpression, + ReturnType + >(); + return (bindingId: string | null, capture: t.Node) => { + const binding = + bindingId === null ? undefined : state.bindingsById.get(bindingId); + const initializer = binding?.initializers[0]; + if ( + !state.memberMutationFactsComplete || + binding === undefined || + initializer === undefined || + initializer.projection.length !== 0 || + binding.referenceInitializers.length !== 0 || + !hasRecordedReferenceEffects(binding, state) || + state.conditionallySkippedExpressions.has(initializer.node) || + !semanticBindingPrecedesCapture(binding, capture, state.parentsByNode) || + opaqueCodeMayRebindBinding(binding, state, capture) + ) + return undefined; + const value = unwrapJavaScriptExpression(initializer.node).node; + if (!t.isObjectExpression(value)) return undefined; + return (path: readonly string[]): boolean => { + if (path.length === 0) return false; + let receiver: t.Node = value; + for (const key of path) { + if (!t.isObjectExpression(receiver)) return false; + let read = readers.get(receiver); + if (read === undefined) { + read = staticObjectPropertyReader(receiver); + readers.set(receiver, read); + } + const property = read(key); + if (property.status !== "explicit") return false; + receiver = unwrapJavaScriptExpression(property.value).node; + } + return !capturedBindingPathMayHaveChanged(binding, path, capture, state); + }; + }; +}; + /** Resolve an expression using the same alias and module provenance owner. */ export const evaluateSemanticExpressionProvenance = ( node: t.Node, diff --git a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts index 66e09074c9..6ef58d12d3 100644 --- a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts +++ b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts @@ -8,7 +8,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; cliTest( - "retains assignment and nested-default destructuring Evidence", + "retains earlier property dependencies through analysis and default tracing", async ({ cli }) => { const root = await createTestTempDirectory( "rea-js-destructuring-evidence-", @@ -17,9 +17,11 @@ cliTest( join(root, "main.js"), ` const src = { a: 1 }; - const { a: declared } = src; + const { a: declared, laterDefault = 0 } = src; let a; ({ a } = src); + const direct = src.a; + src.a = 2; const nested = { a: [1], b: 2 }; const { a: [plain] } = nested; const { a: [fallback] = [] } = nested; @@ -58,5 +60,36 @@ cliTest( )?.properties.property_path, ).toEqual(path); } + expect( + graph.relations.find(({ relation }) => relation === "reads-property"), + ).toMatchObject({ resolution: "resolved" }); + const declared = graph.nodes.find( + ({ kind, label }) => kind === "binding" && label === "declared", + ); + const queryPath = join(root, "query.json"); + await writeFile( + queryPath, + JSON.stringify({ + application: output.json, + query: { + seed: { kind: "semantic-node", node_id: declared?.node_id }, + direction: "backward-provenance", + }, + }), + ); + const trace = await cli.run({ + arguments: ["trace-javascript-semantics", queryPath, "--json"], + }); + expect(trace.exitCode, trace.stderr).toBe(0); + expect(trace.json).toMatchObject({ + normalized_result: { + relations: expect.arrayContaining([ + expect.objectContaining({ + relation: "destructures", + resolution: "resolved", + }), + ]), + }, + }); }, );