fix(javascript): retain proven property presence at reads (#12477)

* fix(javascript): retain proven property presence at reads

The read-time IR and projection boundary builds on the destructuring work in #7716. This change adds an indexed own-slot proof and uses it for ordinary member reads as well.

Co-authored-by: SII-YDD <38822679+SII-YDD@users.noreply.github.com>

* fix(javascript): retain destructuring proof in read order

---------

Co-authored-by: SII-YDD <38822679+SII-YDD@users.noreply.github.com>
This commit is contained in:
morlutoandSII-YDD authored and GitHub committed 2026-11-19 19:17:32 +00:00
1 parent 833916bb4a
commit 1dc22f18cd
8 files changed
+322 -42

No files matched your search

@@ -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"] },
@@ -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,
@@ -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,
@@ -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;
@@ -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);
}
@@ -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<t.Node, t.Node>;
readonly readPresence: ReturnType<typeof createSemanticReadPresenceQuery>;
}
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,
@@ -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<typeof staticObjectPropertyReader>
>();
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,
@@ -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",
}),
]),
},
});
},
);