diff --git a/src/domain/javascript/javascriptMemberMutationQueryBudget.test.ts b/src/domain/javascript/javascriptMemberMutationQueryBudget.test.ts index 577ac4e019..cb0976e4e0 100644 --- a/src/domain/javascript/javascriptMemberMutationQueryBudget.test.ts +++ b/src/domain/javascript/javascriptMemberMutationQueryBudget.test.ts @@ -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 diff --git a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts index 4ede75e190..33899fcfc5 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.member_mutations.test.ts @@ -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", () => { diff --git a/src/domain/javascript/javascriptSemanticEffectLog.ts b/src/domain/javascript/javascriptSemanticEffectLog.ts index 909b54eb32..709c0edabc 100644 --- a/src/domain/javascript/javascriptSemanticEffectLog.ts +++ b/src/domain/javascript/javascriptSemanticEffectLog.ts @@ -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(); + 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[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, diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 7dcf24c696..5c8110fb7e 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -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, + 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, ): {