fix(javascript): escape values stored into an object that escapes (#14273)

* fix(javascript): escape values stored into an object that escapes

An escape followed an object's initializers but not the values member
writes stored into it, so `x.a = y; unknown(x)` kept `y`'s members
literal. An escape now also escapes the stored values at or below the
escaped path. The effect log names the store paths, and the
projected-source owner selects the stores the escape site can see.

A collapsed escape names no site, so it escapes every value a reference
store put at or below its path, once for all collapsed queries. An
escaped path that initializers never reach stays pruned unless a store
targets it or a path below it. Stores inside a destructuring site's
pattern stay with the pattern's iterator and close owners, and operator
results are skipped because they are primitive.

Fixes #14152

* perf(javascript): classify reference stores once per binding

---------

Co-authored-by: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
owennandYsopwnable authored and GitHub committed 2026-11-28 23:16:20 +08:00
1 parent 2c07552b64
commit 26741b03be
4 files changed
+258 -1

No files matched your search

@@ -60,6 +60,21 @@ describe("a member-mutation query that outgrows its state budget", () => {
expect(collapsed.value?.status).not.toBe("literal");
});
it("escapes a value stored into the receiver of a collapsed escape", () => {
// The escape reaches the store's receiver through more aliases than the
// budget admits. The collapsed escape names no site, so every value a
// store put into that receiver escapes with it.
const body = `const y = { v: 1 };
const x = {};
x.a = y;
${aliasChain("x", 12)}
unknown(x12);
return y.v;`;
const collapsed = analyze(body, tightPrecision);
expect(collapsed.ir.coverage.resourceLimits).toContain("alias-selections");
expect(collapsed.value?.status).not.toBe("literal");
});
it("covers a dense cluster once for every query that collapses into it", () => {
// A hundred calls each pass a member of one cyclic cluster. Their
// collapsed escapes name no site, so the cluster is walked once and
@@ -715,6 +715,63 @@ describe("JavaScript semantic values after mutable references escape", () => {
`)?.status,
).toBe("unknown");
});
it.each([
["the escaped object", "const holder = {}; holder.child = source;"],
[
"an alias of the escaped object",
"const holder = {}; const alias = holder; alias.child = source;",
],
[
"a nested slot of the escaped object",
"const holder = { box: {} }; holder.box.child = source;",
],
["a computed slot", "const holder = {}; holder[key] = source;"],
])("follows a value stored into %s before it escapes", (_name, store) => {
expect(
resultValue(`
const source = { value: 1 };
${store}
mutate(holder);
return source.value;
`)?.status,
).toBe("unknown");
});
it("follows a stored value when the slot holding it escapes", () => {
expect(
resultValue(`
const source = { value: 1 };
const holder = {};
holder.child = source;
mutate(holder.child);
return source.value;
`)?.status,
).toBe("unknown");
});
it.each([
[
"a sibling slot escapes",
"const holder = { other: {} }; holder.child = source; mutate(holder.other);",
],
[
"the store follows the escape",
"const holder = {}; mutate(holder); holder.child = source;",
],
[
"only a child of the stored value escapes",
"const holder = {}; holder.child = source; mutate(holder.child.nested);",
],
])("keeps a stored value known when %s", (_name, body) => {
expect(
resultValue(`
const source = { value: 1, nested: {} };
${body}
return source.value;
`),
).toEqual({ status: "literal", value: 1 });
});
});
describe("JavaScript escaped references through async and destructuring syntax", () => {
@@ -7,6 +7,7 @@
import * as t from "@babel/types";
import { javaScriptProgramStrictness } from "./javascriptSourceParser.js";
import {
primitiveOwnKeys,
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
@@ -826,6 +827,89 @@ export function* semanticMemberWriteSources(
yield* effect.assignedSources ?? [];
}
/** Whether a recorded member write may have stored an object reference. */
const storesReference = (effect: MemberWrite): boolean =>
effect.assignedSources?.some(
(source) =>
primitiveOwnKeys(unwrapJavaScriptExpression(source.node).node) === null ||
source.iterationSources !== undefined ||
source.fallbackSources !== undefined ||
source.requiredSources !== undefined,
) === true;
// Member writes are only appended, so each one is classified once.
const referenceStores = new WeakMap<
readonly MemberWrite[],
{ readonly stores: MemberWrite[]; classified: number }
>();
/** The recorded member writes that may store a reference, in record order. */
const bindingReferenceStores = (
binding: JavaScriptSemanticBindingState,
): readonly MemberWrite[] => {
const writes = binding.memberWrites;
let index = referenceStores.get(writes);
if (index === undefined) {
index = { stores: [], classified: 0 };
referenceStores.set(writes, index);
}
for (; index.classified < writes.length; index.classified += 1) {
const effect = writes[index.classified]!;
if (storesReference(effect)) index.stores.push(effect);
}
return index.stores;
};
/**
* The receiver paths whose stored values an escape of `binding`'s object at
* `path` exposes: `path` itself when a reference store targets it or a
* prefix, and each longer path a reference store targets below it.
*/
export const semanticEscapedStorePaths = (
binding: JavaScriptSemanticBindingState,
path: JavaScriptSemanticPropertyPath,
): readonly JavaScriptSemanticPropertyPath[] => {
const paths = new Map<string, JavaScriptSemanticPropertyPath>();
for (const effect of bindingReferenceStores(binding))
if (effect.path.length <= path.length) {
if (semanticEffectPathMatches(effect.path, path))
paths.set(JSON.stringify(path), path);
} else if (
path.length === 0 ||
semanticEffectPathMatches(path, effect.path)
)
paths.set(JSON.stringify(effect.path), effect.path);
return [...paths.values()];
};
/** Whether a reference store targets `path` of `binding`'s object or below it. */
export const semanticBindingStoresAtOrBelow = (
binding: JavaScriptSemanticBindingState,
path: JavaScriptSemanticPropertyPath,
): boolean =>
bindingReferenceStores(binding).some(
(effect) =>
effect.path.length >= path.length &&
(path.length === 0 || semanticEffectPathMatches(path, effect.path)),
);
/**
* The sources reference stores assigned at `path` of `binding`'s object, at a
* prefix of it or below it, whenever they ran.
*/
export function* semanticStoredSourcesReaching(
binding: JavaScriptSemanticBindingState,
path: JavaScriptSemanticPropertyPath,
): Generator<NonNullable<AmbientEffect["assignedSources"]>[number]> {
for (const effect of bindingReferenceStores(binding))
if (
path.length === 0 ||
semanticEffectPathMatches(effect.path, path) ||
semanticEffectPathMatches(path, effect.path)
)
yield* effect.assignedSources ?? [];
}
const sameLiteralPrefix = (
prefix: JavaScriptSemanticPropertyPath,
path: SemanticAliasSelectionPath,
@@ -46,6 +46,9 @@ import {
bindingProjectedContentsMayChangeAt,
semanticAmbientArrayIterationUnknown,
semanticArrayPrototypeIterationMayChange,
semanticBindingStoresAtOrBelow,
semanticEscapedStorePaths,
semanticStoredSourcesReaching,
} from "./javascriptSemanticEffectLog.js";
import { semanticContainer } from "./javascriptSemanticSlots.js";
import {
@@ -117,6 +120,7 @@ import {
childNodes,
} from "./javascriptSemanticTraversal.js";
import {
primitiveOwnKeys,
semanticStaticPropertyKey,
semanticMemberChain,
semanticWriteTargets,
@@ -1069,6 +1073,82 @@ export function* collectSemanticMemberMutationsSteps(
joined: { key, value: joined },
});
};
// A destructuring site selects each receiver at its own pattern element,
// so a store in a later default may follow that read. The pattern's
// iterator and close owners select the stores an element can see.
const sitePattern =
t.isVariableDeclarator(mutation) && t.isPattern(mutation.id)
? mutation.id
: t.isAssignmentExpression(mutation) && t.isPattern(mutation.left)
? mutation.left
: undefined;
const storedBySitePattern = (node: t.Node): boolean => {
if (sitePattern === undefined) return false;
for (
let ancestor: t.Node | undefined = node;
ancestor !== undefined && ancestor !== mutation;
ancestor = parents.get(ancestor)
)
if (ancestor === sitePattern) return true;
return false;
};
// An escape exposes the values earlier writes stored at or below the
// escaped path; the receiver's initializers reach only their own slots.
// `followed` is a receiver path whose stored values are already queued.
const escapeStoredValues = (
binding: JavaScriptSemanticBindingState,
current: PendingValue,
nested: ReadonlySet<string>,
followed?: PropertyPath,
): void => {
// A collapsed escape names no site, so it may follow any store. Each
// stored value escapes whole without a site, and later collapsed
// queries stop where an earlier one covered it.
if (queryCollapsed) {
for (const stored of storedSourceNodes([
...semanticStoredSourcesReaching(binding, current.path),
]))
if (!primitiveStore(stored))
enqueue({
node: stored,
path: [],
bindings: nested,
definiteReceiver: false,
originAt: stored,
});
return;
}
for (const storedPath of semanticEscapedStorePaths(binding, current.path))
if (storedPath !== followed)
for (const source of semanticProjectedSourceFactsAtRead(
binding,
current.node,
storedPath,
state,
false,
current.memberReadAt ?? current.originAt ?? current.node,
current.capturedSelections,
)?.storedSources ?? [])
if (
!primitiveStore(source.node) &&
!storedBySitePattern(source.node)
)
enqueue({
node: source.node,
path: source.path,
bindings: nested,
definiteReceiver: false,
originAt: source.node,
memberReadAt: current.memberReadAt,
capturedSelections: semanticNormalizeCapturedSelections([
...(semanticShiftCapturedSelections(
current.capturedSelections,
source.path.length - storedPath.length,
) ?? []),
...(source.capturedSelections ?? []),
]),
});
};
enqueue({
node,
path,
@@ -1195,7 +1275,22 @@ export function* collectSemanticMemberMutationsSteps(
current.path,
effect,
);
if (path === null) continue;
if (path === null) {
// Initializers place no object at this escaped path, but a value a
// store put at or below it still escapes. A path only a store above
// it reaches stays pruned: through a self store such as
// `s.c = s.c.p`, it would grow on every visit.
if (
effect === "escape" &&
semanticBindingStoresAtOrBelow(binding, current.path)
)
escapeStoredValues(
binding,
current,
new Set([...current.bindings, lifetime, captureKey]),
);
continue;
}
const selectorIndex = path.findIndex(
(key) => key !== null && typeof key === "object",
);
@@ -1538,6 +1633,8 @@ export function* collectSemanticMemberMutationsSteps(
]),
});
}
if (effect === "escape")
escapeStoredValues(binding, current, nested, storedReceiverPath);
// A directly invoked function's parameter starts as its argument,
// which therefore did not escape at the call.
const argument = semanticDirectInvocationArgument(
@@ -2760,6 +2857,10 @@ const storedSourceNodes = (
return nodes;
};
/** Whether a stored expression is an operator result, which is primitive. */
const primitiveStore = (node: t.Node): boolean =>
primitiveOwnKeys(unwrapJavaScriptExpression(node).node) !== null;
const observableMutationPaths = (
state: JavaScriptSemanticAnalysisState,
): {