From 50913e3ba0ba551958479f5b51fa2284ebfa2baa Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:12:54 -0500 Subject: [PATCH] fix(javascript): observe shared array iterator prototype effects (#12493) * fix(javascript): observe shared array iterator prototype effects * fix(javascript): follow iterator escapes and projected receivers * fix(javascript): retain packed prototype reads and receiver captures * fix(javascript): treat proven prototype inspections as read-only * fix(javascript): retain ordinary array destructuring read dependencies (#12505) --- ...vaScriptSemanticGraphDestructuring.test.ts | 353 +++++++++++++++++ .../javascript/javascriptModuleInterop.ts | 69 +++- .../javascriptSemanticAmbientWrites.ts | 375 +++++++++++++++--- .../javascriptSemanticMemberMutations.ts | 6 +- .../javascript/javascriptSemanticObjects.ts | 31 +- .../javascriptSemanticReadPresence.ts | 79 ++++ .../javascriptSemanticReferenceSources.ts | 38 +- .../javascriptSemanticReturnedReferences.ts | 1 + .../javascript/javascriptSemanticValues.ts | 48 --- .../javascriptDestructuringEvidence.test.ts | 95 +++-- 10 files changed, 927 insertions(+), 168 deletions(-) create mode 100644 src/domain/javascript/javascriptSemanticReadPresence.ts diff --git a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts index 943c005414..d3bbaa369c 100644 --- a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts @@ -175,3 +175,356 @@ it.each(["{}", "unknownSource"])( ); }, ); + +it.each([ + ["ordinary array", "", "resolved"], + ["prototype read alone", "Object.getPrototypeOf([].values());", "resolved"], + [ + "one iterator's own next", + "const iterator = [].values(); iterator.next = replacement;", + "resolved", + ], + [ + "unrelated custom iterator", + "const iterator = Object.create({ next: original }); Object.getPrototypeOf(iterator).next = replacement;", + "resolved", + ], + [ + "direct prototype assignment", + "Object.getPrototypeOf([][Symbol.iterator]()).next = replacement;", + "candidate", + ], + [ + "aliased iterator and prototype", + "const array = []; const iterator = array.values(); const p = Reflect.getPrototypeOf(iterator); const alias = p; alias.next = replacement;", + "candidate", + ], + [ + "explicit builtin factory", + "const iterator = Array.prototype.values.call([]); Object.getPrototypeOf(iterator).next = replacement;", + "candidate", + ], + [ + "descriptor", + 'const prototype = Object.getPrototypeOf([].keys()); Object.defineProperty(prototype, "next", { value: replacement });', + "candidate", + ], + [ + "typed array iterator sharing the prototype", + "const bytes = new Uint8Array(); Object.getPrototypeOf(bytes.values()).next = replacement;", + "candidate", + ], + [ + "separate Map iterator prototype", + "Object.getPrototypeOf(new Map().values()).next = replacement;", + "resolved", + ], + ["whole iterator escape", "consume([].values());", "candidate"], + [ + "iterator nested in an escaping container", + "const box = { iterator: [].entries() }; consume(box);", + "candidate", + ], + [ + "array receiver in a stored property", + "const box = { items: [] }; Object.getPrototypeOf(box.items.values()).next = replacement;", + "candidate", + ], + [ + "typed array receiver through aliased properties", + "const box = { items: new Uint8Array() }; const alias = box; Object.getPrototypeOf(alias.items.values()).next = replacement;", + "candidate", + ], + [ + "array receiver through a member assignment", + "const box = {}; box.items = []; Object.getPrototypeOf(box.items.values()).next = replacement;", + "candidate", + ], + [ + "member assignment after the iterator was obtained", + "const box = { items: new Map() }; const iterator = box.items.values(); box.items = []; Object.getPrototypeOf(iterator).next = replacement;", + "resolved", + ], + [ + "replaced prototype inspector receives the iterator", + "Reflect.getPrototypeOf = opaque; Reflect.getPrototypeOf([].values());", + "candidate", + ], + [ + "object property with unrelated iterator", + "const box = { items: new Map() }; Object.getPrototypeOf(box.items.values()).next = replacement;", + "resolved", + ], + [ + "read-only alias to getPrototypeOf", + "const inspect = Reflect.getPrototypeOf; const iterator = [].values(); inspect(iterator);", + "resolved", + ], + [ + "packed direct prototype read", + "Reflect.getPrototypeOf(...[[].values()]);", + "resolved", + ], + [ + "method apply prototype read", + "Reflect.getPrototypeOf.apply(null, [[].values()]);", + "resolved", + ], + [ + "Reflect.apply prototype read", + "Reflect.apply(Reflect.getPrototypeOf, null, [[].values()]);", + "resolved", + ], + [ + "packed prototype read with another ignored iterator argument", + "Reflect.apply(Reflect.getPrototypeOf, null, [[].values(), [].values()]);", + "resolved", + ], + [ + "ignored iterator passed directly to native inspection", + "Reflect.getPrototypeOf({}, [].values());", + "resolved", + ], + [ + "ignored iterator passed through method apply", + "Reflect.getPrototypeOf.apply(null, [{}, [].values()]);", + "resolved", + ], + [ + "opaque aliased apply pack", + "const args = [{}, [].values()]; Reflect.apply(Reflect.getPrototypeOf, null, args);", + "candidate", + ], + [ + "opaque inspector receives extra iterator", + "Reflect.getPrototypeOf = opaque; Reflect.getPrototypeOf({}, [].values());", + "candidate", + ], + [ + "opaque Reflect.apply receives packed extra iterator", + "Reflect.apply = opaque; Reflect.apply(Reflect.getPrototypeOf, null, [{}, [].values()]);", + "candidate", + ], + [ + "ignored argument evaluation can still expose the iterator", + "Reflect.getPrototypeOf({}, consume([].values()));", + "candidate", + ], + [ + "ignored packaged argument evaluation can change the prototype", + "Reflect.apply(Reflect.getPrototypeOf, null, [{}, (Object.getPrototypeOf([].values()).next = replacement)]);", + "candidate", + ], + [ + "native inspection of the shared prototype", + "const p = Object.getPrototypeOf([].values()); Object.getPrototypeOf(p);", + "resolved", + ], + [ + "nested direct native inspection of the shared prototype", + "Object.getPrototypeOf(Object.getPrototypeOf([].values()));", + "resolved", + ], + [ + "actual shared-prototype exposure", + "const p = Object.getPrototypeOf([].values()); consume(p);", + "candidate", + ], + [ + "overwritten inspector receives the shared prototype", + "const p = Object.getPrototypeOf([].values()); Object.getPrototypeOf = opaque; Object.getPrototypeOf(p);", + "candidate", + ], + [ + "read-only bound inspector", + "const inspect = Reflect.getPrototypeOf.bind(null); inspect({}, [].values());", + "resolved", + ], + [ + "opaque replacement of bind before creating the inspector", + "Function.prototype.bind = opaque; const inspect = Reflect.getPrototypeOf.bind(null); inspect({}, [].values());", + "candidate", + ], + [ + "opaque packed argument exposure precedes an earlier deferred inspection", + "const iterator = [].values(); function inspect() { Object.getPrototypeOf({}, iterator); } Reflect.apply = opaque; Reflect.apply(Reflect.getPrototypeOf, null, [{}], Object); inspect();", + "candidate", + ], + [ + "two helper exposures can invalidate a deferred inspection", + "const iterator = [].values(); function inspect() { Reflect.getPrototypeOf({}, iterator); } function expose() { Object.getPrototypeOf({}, Reflect); } Reflect.apply = opaque; Reflect.apply(Reflect.getPrototypeOf, null, [{}], Object); expose(); inspect();", + "candidate", + ], + [ + "opaque replacement of Reflect.apply", + "Reflect.apply = opaque; Reflect.apply(Reflect.getPrototypeOf, null, [[].values()]);", + "candidate", + ], + [ + "opaque replacement of Function.prototype.apply", + "Function.prototype.apply = opaque; Reflect.getPrototypeOf.apply(null, [[].values()]);", + "candidate", + ], + [ + "native inspector captured before replacement", + "const inspect = Reflect.getPrototypeOf; Reflect.getPrototypeOf = opaque; inspect([].values());", + "resolved", + ], + [ + "inspector captured after replacement", + "Reflect.getPrototypeOf = opaque; const inspect = Reflect.getPrototypeOf; inspect([].values());", + "candidate", + ], + [ + "property captured before an array store", + "const box = { items: new Map() }; const captured = box.items; box.items = []; Object.getPrototypeOf(captured.values()).next = replacement;", + "resolved", + ], + [ + "destructured property captured before an array store", + "const box = { items: new Map() }; const { items: captured } = box; box.items = []; Object.getPrototypeOf(captured.values()).next = replacement;", + "resolved", + ], + [ + "property captured after an array store", + "const box = { items: new Map() }; box.items = []; const captured = box.items; Object.getPrototypeOf(captured.values()).next = replacement;", + "candidate", + ], + [ + "captured parent still observes a later child store", + "const box = { parent: { items: new Map() } }; const captured = box.parent; box.parent.items = []; Object.getPrototypeOf(captured.items.values()).next = replacement;", + "candidate", + ], + [ + "separately captured parent and child before a later store", + "const box = { parent: { items: new Map() } }; const parent = box.parent; const captured = parent.items; box.parent.items = []; Object.getPrototypeOf(captured.values()).next = replacement;", + "resolved", + ], + [ + "Reflect.apply is distinct from Function.prototype.apply", + "Function.prototype.apply = opaque; Reflect.apply(Reflect.getPrototypeOf, null, [[].values()]);", + "resolved", + ], + [ + "projected argument captured before an array store", + "const box = { items: new Map() }; ((captured) => { Object.getPrototypeOf(captured.values()).next = replacement; })(box.items); box.items = [];", + "resolved", + ], + [ + "prototype escape", + "consume(Object.getPrototypeOf([].entries()));", + "candidate", + ], + [ + "non-next property", + "Object.getPrototypeOf([].values()).other = replacement;", + "resolved", + ], +] as const)( + "attributes array iterator effects for %s", + (_name, change, resolution) => { + const graph = graphForJavaScript(` + const config = ["original"]; + const replacement = () => ({ value: "other", done: false }); + ${change} + const [selected] = config; + `); + 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 }); + }, +); + +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"], + ["unrelated write", "config[1] = 2; const [selected] = config;", "resolved"], + ["later default", "const [selected, missing = 0] = config;", "resolved"], + [ + "earlier delete", + "delete config[0]; const [selected] = config;", + "candidate", + ], + [ + "earlier truncation", + "config.length = 0; const [selected] = config;", + "candidate", + ], + [ + "own custom iterator", + "config[Symbol.iterator] = function* () { yield 2; }; const [selected] = config;", + "candidate", + ], + [ + "prototype iterator", + "Array.prototype[Symbol.iterator] = function* () { yield 2; }; const [selected] = config;", + "candidate", + ], + [ + "earlier shared next replacement", + 'Object.getPrototypeOf([].values()).next = () => ({ value: "other", done: false }); const [selected] = config;', + "candidate", + ], + [ + "later shared next replacement", + 'const [selected] = config; Object.getPrototypeOf([].values()).next = () => ({ value: "other", done: false });', + "resolved", + ], + [ + "custom prototype", + "Object.setPrototypeOf(config, { *[Symbol.iterator]() { yield 2; } }); const [selected] = config;", + "candidate", + ], + ["earlier default", "const [value = 0, selected] = config;", "candidate"], + [ + "earlier setter", + "let selected; const target = { set value(_) { config[1] = 2; } }; [target.value, selected] = config;", + "candidate", + ], + ["nested binding", "let selected; [[selected]] = config;", "candidate"], +] as const)( + "preserves array iteration dependencies for %s", + (_name, read, resolution) => { + const graph = graphForJavaScript(` + const config = [[1], 1]; + ${read} + config[0] = 2; + config[1] = 2; + `); + 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 }); + }, +); diff --git a/src/domain/javascript/javascriptModuleInterop.ts b/src/domain/javascript/javascriptModuleInterop.ts index ac8c5e99bb..3ec5b3a449 100644 --- a/src/domain/javascript/javascriptModuleInterop.ts +++ b/src/domain/javascript/javascriptModuleInterop.ts @@ -65,6 +65,11 @@ const INTRINSICS: Readonly> = { __hasOwnProp: ["Object", "prototype", "hasOwnProperty"], }; +type IntrinsicReadObserver = ( + capture: t.Node, + path: readonly string[], +) => boolean; + interface IntrinsicDependency { readonly path: readonly string[]; readonly capturedAt?: t.Node; @@ -172,7 +177,9 @@ export const createSemanticModuleInterop = ( // A nominal alias path is sufficient for conservative mutation lookup, but // helper proof also needs each read to follow initialization. An alias copy // retains the earlier function capture; a member read captures it anew. - const capturedIntrinsic = (node: t.Node): IntrinsicDependency | undefined => { + const capturedIntrinsic = ( + node: t.Node, + ): Required | undefined => { const path = intrinsicPath(node); if (path === undefined) return undefined; const visited = new Set(); @@ -231,29 +238,32 @@ export const createSemanticModuleInterop = ( const intrinsicReadChanged = ( node: t.Node, path: readonly string[], + mayObserve?: IntrinsicReadObserver, ): boolean => { const capture = capturedIntrinsic(node)?.capturedAt ?? node; const scope = opaqueMutationPath(capture).join("."); const method = path.at(-1); - const invocationMethod = - method === "bind" || method === "call" || method === "apply"; - return writes.some( - (write) => - (write.scope === scope || write.scope === "intrinsic") && - write.offset < (capture.start ?? -1) && - (write.coverage.covers(path) || - (invocationMethod && - write.coverage.covers([ - "intrinsic", - "Function", - "prototype", - method, - ]))), + const inherited = + (method === "bind" || method === "call" || method === "apply") && + !(method === "apply" && path.length === 3 && path[1] === "Reflect") + ? ["intrinsic", "Function", "prototype", method] + : undefined; + return ( + mayObserve?.(capture, path) === true || + (inherited !== undefined && mayObserve?.(capture, inherited) === true) || + writes.some( + (write) => + (write.scope === scope || write.scope === "intrinsic") && + write.offset < (capture.start ?? -1) && + (write.coverage.covers(path) || + (inherited !== undefined && write.coverage.covers(inherited))), + ) ); }; const resolveBoundIntrinsic = ( node: t.Node, + mayObserve?: IntrinsicReadObserver, ): JavaScriptIntrinsicInvocation | undefined => { const visited = new Set(); const argumentGroups: t.CallExpression["arguments"][] = []; @@ -302,8 +312,9 @@ export const createSemanticModuleInterop = ( const invocation = resolveJavaScriptIntrinsicInvocation( current, intrinsicPath, - boundIntrinsic, - intrinsicReadChanged, + (callee) => boundIntrinsic(callee, mayObserve), + (reference, selected) => + intrinsicReadChanged(reference, selected, mayObserve), nativeArrayIteration, ); if ( @@ -330,9 +341,20 @@ export const createSemanticModuleInterop = ( current = bindTarget; continue; } + if (captured !== undefined && mayObserve !== undefined) + opaqueArguments ||= intrinsicReadChanged( + captured.capturedAt, + path, + mayObserve, + ); const boundPath = [...path, "bind"]; const functionBind = ["intrinsic", "Function", "prototype", "bind"]; opaqueArguments ||= bindReads.some((capture) => { + if ( + mayObserve?.(capture, boundPath) || + mayObserve?.(capture, functionBind) + ) + return true; const scope = opaqueMutationPath(capture).join("."); return writes.some( (write) => @@ -357,11 +379,12 @@ export const createSemanticModuleInterop = ( const activeBoundValues = new WeakSet(); const boundIntrinsic = ( node: t.Node, + mayObserve?: IntrinsicReadObserver, ): JavaScriptIntrinsicInvocation | undefined => { if (activeBoundValues.has(node)) return undefined; activeBoundValues.add(node); try { - return resolveBoundIntrinsic(node); + return resolveBoundIntrinsic(node, mayObserve); } finally { activeBoundValues.delete(node); } @@ -725,12 +748,18 @@ export const createSemanticModuleInterop = ( | t.NewExpression | t.TaggedTemplateExpression, callablePath = intrinsicPath, + mayObserve?: IntrinsicReadObserver, ) => resolveJavaScriptIntrinsicInvocation( node, callablePath, - boundIntrinsic, - intrinsicReadChanged, + mayObserve === undefined + ? boundIntrinsic + : (callee) => boundIntrinsic(callee, mayObserve), + mayObserve === undefined + ? intrinsicReadChanged + : (reference, path) => + intrinsicReadChanged(reference, path, mayObserve), nativeArrayIteration, ), boundIntrinsic, diff --git a/src/domain/javascript/javascriptSemanticAmbientWrites.ts b/src/domain/javascript/javascriptSemanticAmbientWrites.ts index addb1dc447..ced6fcb84d 100644 --- a/src/domain/javascript/javascriptSemanticAmbientWrites.ts +++ b/src/domain/javascript/javascriptSemanticAmbientWrites.ts @@ -12,11 +12,13 @@ import { import { collectJavaScriptIdentityWritesSteps, electronMemberPath, + type JavaScriptIntrinsicInvocation, } from "./javascriptElectronMemberWrites.js"; import { createSemanticModuleInterop } from "./javascriptModuleInterop.js"; import { ambientEffectCovers, ambientPathMayObserveAt, + opaqueCodeMayChangeGlobalRead, semanticEffectMayFollow, semanticEffectMayPrecede, } from "./javascriptSemanticEffectLog.js"; @@ -39,13 +41,21 @@ import { GLOBAL_OBJECT_NAMES, globalObjectName, globalReferenceNamespace, + isIntrinsicGlobalReference, } from "./javascriptSemanticGlobalReference.js"; import { readSemanticRequireLoader } from "./javascriptSemanticRequireOriginSlot.js"; import { + semanticArrayIteratorPrototypePath, semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; +import { + semanticNormalizeCapturedSelections, + semanticShiftCapturedSelections, + type SemanticCapturedSelection, +} from "./javascriptSemanticProjectedSources.js"; +import { isIntrinsicTypedArrayConstruction } from "./javascriptSemanticTypedArrays.js"; /** * Own static methods of `Object` and `Reflect` in the language. A native one @@ -114,6 +124,30 @@ const canonicalAmbientPath = ( return ["global", ...path.slice(firstProperty)]; }; +const arrayIteratorMethods = new Set(["entries", "keys", "values"]); + +const intrinsicPrototypeRead = ( + invocation: JavaScriptIntrinsicInvocation | undefined, +) => { + if (invocation?.kind !== "known" || invocation.path.length !== 3) + return undefined; + const [, owner, method] = invocation.path; + if ( + (owner !== "Object" && owner !== "Reflect") || + method !== "getPrototypeOf" + ) + return undefined; + const target = invocation.arguments?.[0]; + return t.isNode(target) && !t.isSpreadElement(target) ? target : undefined; +}; + +/** A normalized native inspection neither retains its target nor uses extra arguments. */ +const isReadOnlyPrototypeInspection = ( + invocation: JavaScriptIntrinsicInvocation | undefined, +): boolean => + intrinsicPrototypeRead(invocation) !== undefined && + invocation?.arguments?.every((argument) => t.isExpression(argument)) === true; + type AmbientPath = readonly (string | null)[]; const retainedAmbientEffects = new WeakMap< @@ -191,6 +225,21 @@ const joinAmbientProjection = ( ? undefined : left.map((key, index) => (key === right[index] ? key : null)); +type CapturedSelections = readonly SemanticCapturedSelection[] | undefined; + +const sameCaptures = ( + left: CapturedSelections, + right: CapturedSelections, +): boolean => + left === right || + (left !== undefined && + right !== undefined && + left.length === right.length && + left.every( + ({ at, depth }, index) => + at === right[index]?.at && depth === right[index]?.depth, + )); + type AmbientIdentityUnknownReason = | "unresolved-value" | "widened-projection" @@ -202,6 +251,7 @@ interface AmbientResolution { readonly callerPaths: readonly AmbientPath[]; readonly ownership: "local" | "ambient" | "unknown"; readonly unknownReasons: readonly AmbientIdentityUnknownReason[]; + readonly possibleArrayReceiver?: true; } interface AmbientReferenceFacts { @@ -209,8 +259,14 @@ interface AmbientReferenceFacts { t.Node, Map >; - readonly prototypeTarget: (node: t.Node) => t.Node | undefined; + readonly callResult: ( + node: t.CallExpression | t.OptionalCallExpression, + ) => + | { readonly kind: "prototype"; readonly target: t.Node } + | { readonly kind: "array-iterator"; readonly receiver?: t.Node } + | undefined; readonly freshObject: (node: t.Node) => boolean; + readonly arrayIteratorReceiver: (node: t.Node) => boolean; } /** @@ -231,12 +287,13 @@ export const createAmbientPathResolver = ( ReturnType >(); const returnedReferences = createSemanticReturnedReferences(state); - return ( + const resolve = ( node: t.Node, capture?: t.Node, escapedContents = false, projection: AmbientProjection = [], receiver?: (node: t.Node, path: AmbientProjection) => void, + observes?: "array-receiver", ): AmbientResolution => { const prior = possibleWrites ? undefined : cached.get(node); if (prior !== undefined) return prior; @@ -250,6 +307,7 @@ export const createAmbientPathResolver = ( node: t.Node; suffix: AmbientProjection; readsAtSelf: true | undefined; + capturedSelections?: CapturedSelections; }; // A binding read queues its selected initializers for one projection, // taken from the end as if queued one by one. Reads selecting the same @@ -259,6 +317,7 @@ export const createAmbientPathResolver = ( // read reached through an alias cycle grows quadratically per query. interface QueuedInitializers { readonly items: readonly Pending[]; + readonly capturedSelections: CapturedSelections; remaining: number; } const pending: (Pending | QueuedInitializers)[] = [ @@ -289,11 +348,16 @@ export const createAmbientPathResolver = ( // depths widen to unknown, so diamonds and cycles have finite state. // Null marks a fully widened root. An absent entry has not been visited. const expanded = new WeakMap(); + const expansionCaptures = + observes === "array-receiver" + ? new WeakMap() + : undefined; let continued = false; const queue = ( node: t.Node, suffix: AmbientProjection, readsAtSelf?: true, + capturedSelections?: CapturedSelections, ): void => { if (!admitted(suffix)) return; continued = true; @@ -303,7 +367,7 @@ export const createAmbientPathResolver = ( const root = memberPaths.get(node)?.root; if (root !== undefined && expanded.get(root) === null) return; } - pending.push({ node, suffix, readsAtSelf }); + pending.push({ node, suffix, readsAtSelf, capturedSelections }); }; const retain = (path: AmbientPath) => { let canonical = canonicalAmbientPath(path); @@ -346,15 +410,33 @@ export const createAmbientPathResolver = ( current.suffix === undefined || members.length === 0 ? current.suffix : [...members, ...current.suffix]; + let capturedSelections = + observes === "array-receiver" && members.length > 0 + ? [ + { at: current.node, depth: members.length }, + ...(semanticShiftCapturedSelections( + current.capturedSelections, + members.length, + ) ?? []), + ] + : current.capturedSelections; const previous = expanded.get(root); if (previous !== undefined) { + const previousCaptures = expansionCaptures?.get(root); + // Multiple aliases may choose the same slot at different reads. + // Widen the timing once to the factory read instead of keeping paths + // for each alias history. Widened projections drop earlier bounds. + if (!sameCaptures(previousCaptures, capturedSelections)) + capturedSelections = undefined; + const captureWidened = + previousCaptures !== undefined && capturedSelections === undefined; if (previous === null) { resolvedIdentity = true; continue; } if (suffix !== undefined && previous.length === suffix.length) { const joined = joinSemanticPropertyPaths(previous, suffix); - if (joined === previous) { + if (joined === previous && !captureWidened) { resolvedIdentity = true; continue; } @@ -371,13 +453,27 @@ export const createAmbientPathResolver = ( return unresolved; } } + if (suffix === undefined) capturedSelections = undefined; expanded.set(root, suffix ?? null); + expansionCaptures?.set(root, capturedSelections); if (suffix === undefined || suffix.includes(null)) unknownReasons.add("widened-projection"); // A widened projection is a possible write, never proof of an intrinsic. if (suffix === undefined && !possibleWrites) continue; const continueWith = (node: t.Node, path: AmbientProjection = suffix) => - queue(node, path, current.readsAtSelf); + queue( + node, + path, + current.readsAtSelf, + path !== undefined && + suffix !== undefined && + path.length <= suffix.length + ? semanticShiftCapturedSelections( + capturedSelections, + path.length - suffix.length, + ) + : undefined, + ); const continueReturned = (callee: t.Node, path: AmbientProjection) => { const returned = returnedReferences(callee); // Returned references retain possible source-local values, not a @@ -398,6 +494,18 @@ export const createAmbientPathResolver = ( ], ); }; + if ( + observes === "array-receiver" && + (suffix === undefined || suffix.length === 0) && + facts?.arrayIteratorReceiver(root) + ) + return { + paths: [], + callerPaths: [], + ownership: "local", + unknownReasons: [], + possibleArrayReceiver: true, + }; if (!t.isIdentifier(root) && facts?.freshObject(root)) { receiver?.(root, suffix); // The allocation owns itself; a projected child needs its own proof. @@ -406,6 +514,17 @@ export const createAmbientPathResolver = ( resolvedIdentity = true; } for (const [source, path] of facts?.stores.get(root) ?? []) { + const readAt = + (path === undefined + ? undefined + : capturedSelections?.find(({ depth }) => path.length <= depth) + ?.at) ?? capture; + if ( + observes === "array-receiver" && + readAt !== undefined && + !semanticEffectMayPrecede(state, readAt, source.mutation) + ) + continue; const stored = storedValueProjection( suffix, source, @@ -476,13 +595,22 @@ export const createAmbientPathResolver = ( const argument = possibleWrites ? semanticDirectInvocationArgument(root, binding, state) : undefined; - if (argument !== undefined) queue(argument, suffix, true); + if (argument !== undefined) + queue(argument, suffix, true, capturedSelections); const bySuffix = queuedInitializers.get(selected) ?? new Map(); queuedInitializers.set(selected, bySuffix); - const suffixKey = JSON.stringify(suffix); + let suffixKey = JSON.stringify(suffix); let queued = bySuffix.get(suffixKey); + if ( + queued?.capturedSelections !== undefined && + !sameCaptures(queued.capturedSelections, capturedSelections) + ) { + suffixKey = JSON.stringify(["factory-read", suffix]); + capturedSelections = undefined; + queued = bySuffix.get(suffixKey); + } if (queued === undefined) { const stable = possibleWrites ? undefined @@ -504,22 +632,49 @@ export const createAmbientPathResolver = ( escapedContents ? "escape" : "identity", ); if (path === null) continue; + const projected = + suffix === undefined || + semanticReferenceIterationUnknown(initializer, state) + ? undefined + : path.map((key) => + key === null || typeof key === "object" + ? null + : String(key), + ); + const captureDepth = + "copyProjectionOffset" in initializer && + typeof initializer.copyProjectionOffset === "number" + ? initializer.copyProjectionOffset + 1 + : initializer.projection.length; + const retainedCaptures = + projected === undefined || suffix === undefined + ? undefined + : semanticShiftCapturedSelections( + capturedSelections, + projected.length - suffix.length, + ); const item: Pending = { node: initializer.node, readsAtSelf: true, - suffix: - suffix === undefined || - semanticReferenceIterationUnknown(initializer, state) - ? undefined - : path.map((key) => - key === null || typeof key === "object" - ? null - : String(key), - ), + suffix: projected, + capturedSelections: + observes === "array-receiver" && + projected !== undefined && + captureDepth > 0 + ? semanticNormalizeCapturedSelections( + [ + { at: initializer.node, depth: captureDepth }, + ...(retainedCaptures?.filter( + ({ depth }) => depth > captureDepth, + ) ?? []), + ], + projected.length, + ) + : retainedCaptures, }; if (admitted(item.suffix)) items.push(item); } - queued = { items, remaining: items.length }; + queued = { items, capturedSelections, remaining: items.length }; bySuffix.set(suffixKey, queued); } // Taken items still count as queued for this read: requeued, they @@ -543,16 +698,44 @@ export const createAmbientPathResolver = ( ); continue; } - const prototypeTarget = possibleWrites - ? facts?.prototypeTarget(root) - : undefined; - if (prototypeTarget !== undefined) { + const callResult = + possibleWrites && + (t.isCallExpression(root) || t.isOptionalCallExpression(root)) + ? facts?.callResult(root) + : undefined; + if (callResult?.kind === "prototype") { continueWith( - prototypeTarget, + callResult.target, suffix === undefined ? undefined : ["__proto__", ...suffix], ); continue; } + // A call that may return a native array iterator can reach the + // shared prototype through a prototype projection. Its ordinary + // return alternatives still pass through the same alias walk. + if ( + observes !== "array-receiver" && + callResult?.kind === "array-iterator" && + (suffix === undefined || + suffix[0] === null || + suffix[0] === "__proto__" || + (escapedContents && suffix.length === 0)) && + (callResult.receiver === undefined || + resolve( + callResult.receiver, + callResult.receiver, + false, + [], + undefined, + "array-receiver", + ).possibleArrayReceiver === true) + ) { + retain([ + ...semanticArrayIteratorPrototypePath, + ...(suffix?.slice(1) ?? []), + ]); + resolvedIdentity = true; + } if ( possibleWrites && (t.isCallExpression(root) || @@ -711,6 +894,7 @@ export const createAmbientPathResolver = ( if (!possibleWrites) cached.set(node, resolution); return resolution; }; + return resolve; }; /** @@ -737,6 +921,10 @@ export function* indexJavaScriptAmbientWritesSteps( browserReceiver: boolean; projection?: AmbientProjection; }[] = []; + const prototypeInspections: { + readonly node: t.CallExpression | t.OptionalCallExpression; + readonly arguments: readonly t.Node[]; + }[] = []; // Object/Reflect static calls, settled once every ambient write is known. const staticReceivers: { node: t.Node; @@ -758,21 +946,41 @@ export function* indexJavaScriptAmbientWritesSteps( const ambientWrites = createAmbientPathResolver(state, true, { stores, freshObject: interop.isFreshObject, - prototypeTarget: (node) => { - if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) - return undefined; + arrayIteratorReceiver: (node) => + t.isArrayExpression(node) || + (t.isNewExpression(node) && + (isIntrinsicGlobalReference(node.callee, state, "Array") || + isIntrinsicTypedArrayConstruction(node, state))), + callResult: (node) => { const invocation = interop.intrinsicInvocation(node); + const prototype = intrinsicPrototypeRead(invocation); + if (prototype !== undefined) + return { kind: "prototype", target: prototype }; if ( - invocation?.kind !== "known" || - invocation.path.length !== 3 || - !["Object", "Reflect"].includes(invocation.path[1] ?? "") || - invocation.path[2] !== "getPrototypeOf" + invocation?.path.length === 4 && + invocation.path[1] === "Array" && + invocation.path[2] === "prototype" && + arrayIteratorMethods.has(invocation.path[3]!) + ) + return { kind: "array-iterator" }; + const callee = unwrapJavaScriptExpression(node.callee).node; + if ( + !(t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) ) return undefined; - const target = invocation.arguments?.[0]; - return t.isNode(target) && !t.isSpreadElement(target) - ? target - : undefined; + const key = semanticStaticPropertyKey(callee.property, callee.computed); + if ( + !(key !== null && arrayIteratorMethods.has(key)) && + !( + callee.computed && + globalReferenceNamespace(callee.property, state, [ + "Symbol", + "iterator", + ]) !== undefined + ) + ) + return undefined; + return { kind: "array-iterator", receiver: callee.object }; }, }); yield* collectJavaScriptIdentityWritesSteps( @@ -812,17 +1020,26 @@ export function* indexJavaScriptAmbientWritesSteps( const retainEscape = (target: t.Node, browserReceiver = false) => { escapes.push({ target, node, browserReceiver }); }; - for (const [index, argument] of (t.isTaggedTemplateExpression(node) + const arguments_ = t.isTaggedTemplateExpression(node) ? node.quasi.expressions - : node.arguments - ).entries()) + : node.arguments; + const inspection = + (t.isCallExpression(node) || t.isOptionalCallExpression(node)) && + isReadOnlyPrototypeInspection(invocation) + ? { node, arguments: [] as t.Node[] } + : undefined; + for (const [index, argument] of arguments_.entries()) if ( t.isNode(argument) && !semanticArgumentStaysInSource(node, index, state) - ) - retainEscape( - t.isSpreadElement(argument) ? argument.argument : argument, - ); + ) { + const value = t.isSpreadElement(argument) + ? argument.argument + : argument; + if (inspection === undefined) retainEscape(value); + else inspection.arguments.push(value); + } + if (inspection !== undefined) prototypeInspections.push(inspection); const callee = unwrapJavaScriptExpression( t.isTaggedTemplateExpression(node) ? node.tag : node.callee, ).node; @@ -1004,12 +1221,59 @@ export function* indexJavaScriptAmbientWritesSteps( if (ambientPathMayObserveAt(state, node, ["global", ...method], "contents")) retainEscapeEffect({ node, target, browserReceiver: false }); else state.retainedGlobalCallReceivers.add(target); - function retainEscapeEffect({ + // Validate the normalized dispatch at its intrinsic captures. A rejected + // call can expose a helper used by an earlier textual call in a deferred + // activation. Recheck provisional reads once after publishing those escapes. + // If that pass adds another relevant effect, conservatively retain the + // remaining escapes instead of rescanning the whole source to a fixed point. + const firstInspectionPass = + retainOpaquePrototypeInspections(prototypeInspections); + if (firstInspectionPass.changed) { + const secondInspectionPass = retainOpaquePrototypeInspections( + firstInspectionPass.provisional, + ); + if (secondInspectionPass.changed) + for (const inspection of secondInspectionPass.provisional) + retainPrototypeInspectionArguments(inspection); + } + function retainOpaquePrototypeInspections( + inspections: typeof prototypeInspections, + ) { + const provisional: typeof prototypeInspections = []; + let changed = false; + for (const inspection of inspections) { + const invocation = interop.intrinsicInvocation( + inspection.node, + undefined, + (capture, path) => + ambientPathMayObserveAt( + state, + capture, + ["global", ...path.slice(1)], + "contents", + ) || opaqueCodeMayChangeGlobalRead(capture, state, path[1] ?? ""), + ); + if (isReadOnlyPrototypeInspection(invocation)) + provisional.push(inspection); + else changed = retainPrototypeInspectionArguments(inspection) || changed; + } + return { provisional, changed }; + } + function retainPrototypeInspectionArguments({ node, - target, - browserReceiver, - projection, - }: (typeof escapes)[number]): void { + arguments: argumentValues, + }: (typeof prototypeInspections)[number]): boolean { + let changed = false; + for (const target of argumentValues) + changed = + retainEscapeEffect({ node, target, browserReceiver: false }, true) || + changed; + return changed; + } + function retainEscapeEffect( + { node, target, browserReceiver, projection }: (typeof escapes)[number], + trackPrototypeInspectionEffects = false, + ): boolean { const resolved = ambientWrites(target, node, true, projection); if ( browserReceiver && @@ -1018,11 +1282,24 @@ export function* indexJavaScriptAmbientWritesSteps( resolved.paths.every((path) => path.length === 1 && path[0] === "global") ) state.retainedGlobalCallReceivers.add(target); - for (const path of resolved.paths) + let changed = false; + for (const path of resolved.paths) { // Only proven browser APIs keep their global receiver from user code. - if (!(browserReceiver && path.length === 1 && path[0] === "global")) { - retainSemanticAmbientEffect(state, "escape", path, node); - } + if (browserReceiver && path.length === 1 && path[0] === "global") + continue; + const retained = retainSemanticAmbientEffect(state, "escape", path, node); + changed ||= + retained && + trackPrototypeInspectionEffects && + (path[0] === semanticArrayIteratorPrototypePath[0] || + (path[0] === "global" && + (path.length === 1 || + path[1] === null || + ["Array", "Function", "Object", "Reflect"].includes( + path[1] ?? "", + )))); + } + return changed; } // A function may call a browser method replaced later in source order. if ( diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index fce884ddad..360df3e936 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -2077,7 +2077,11 @@ export function* collectSemanticMemberMutationsSteps( const slot = semanticSelectedReferenceSlot(reference, state); // Custom iteration can yield the iterable itself as well as any child. // Treat its root as escaped, including writes through yielded references. - const knownArray = semanticKnownArrayIteration(slot?.value, state); + const knownArray = semanticKnownArrayIteration( + slot?.value, + state, + reference.node, + ); if (knownArray && reference.iterationOnly) continue; markValue( reference.node, diff --git a/src/domain/javascript/javascriptSemanticObjects.ts b/src/domain/javascript/javascriptSemanticObjects.ts index 0acb90e20a..ca3e2847a9 100644 --- a/src/domain/javascript/javascriptSemanticObjects.ts +++ b/src/domain/javascript/javascriptSemanticObjects.ts @@ -18,7 +18,7 @@ import { } from "./javascriptSemanticState.js"; import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; -import { createSemanticReadPresenceQuery } from "./javascriptSemanticValues.js"; +import { createSemanticReadPresenceQuery } from "./javascriptSemanticReadPresence.js"; /** Recover bounded static property reads, writes, spreads, and destructuring. */ export const collectJavaScriptSemanticObjects = ( @@ -145,10 +145,17 @@ const collectDestructuring = ( { state, output, readPresence }: ObjectCollectionContext, ): void => { const source = expressionObjectIdentity(initializer, state); + const rootArray = t.isArrayPattern(root); let ownSlot = - initializer == null || source.path === null - ? undefined - : readPresence(source.bindingId, initializer); + initializer != null && + source.path !== null && + (!rootArray || source.path.length === 0) + ? readPresence( + source.bindingId, + initializer, + rootArray ? "array-iteration" : "property", + ) + : undefined; // An unsupported property still occupies its place in the pattern's // evaluation order, even when it cannot produce a graph operation. const pending: ({ @@ -180,6 +187,7 @@ const collectDestructuring = ( ? unwrapJavaScriptExpression(occurrence.left).node : occurrence; if (t.isObjectPattern(pattern)) { + if (rootArray) ownSlot = undefined; for (const property of pattern.properties.toReversed()) { if (!t.isObjectProperty(property)) { pending.push(null); @@ -199,15 +207,16 @@ const collectDestructuring = ( continue; } if (t.isArrayPattern(pattern)) { - ownSlot = undefined; + if (pattern !== root) ownSlot = undefined; for (let index = pattern.elements.length - 1; index >= 0; index -= 1) { const element = pattern.elements[index]; - if ( - element !== null && - element !== undefined && - !t.isRestElement(element) - ) - pending.push({ pattern: element, path: [...path, String(index)] }); + if (element == null || t.isRestElement(element)) pending.push(null); + else + pending.push({ + pattern: element, + path: [...path, String(index)], + lookup: "own", + }); } continue; } diff --git a/src/domain/javascript/javascriptSemanticReadPresence.ts b/src/domain/javascript/javascriptSemanticReadPresence.ts new file mode 100644 index 0000000000..cf6329b2e8 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticReadPresence.ts @@ -0,0 +1,79 @@ +import * as t from "@babel/types"; +import { + staticObjectPropertyReader, + unwrapJavaScriptExpression, +} from "./javascriptAstValues.js"; +import { + capturedBindingPathMayHaveChanged, + hasRecordedReferenceEffects, + opaqueCodeMayRebindBinding, +} from "./javascriptSemanticEffectLog.js"; +import { semanticBindingPrecedesCapture } from "./javascriptSemanticMutationInitializers.js"; +import { semanticArrayIndex } from "./javascriptSemanticPropertyPaths.js"; +import { semanticNativeArrayIterationValueAt } from "./javascriptSemanticReferenceSources.js"; +import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js"; + +/** Prove a direct data slot in its source at the time of the read. */ +export const createSemanticReadPresenceQuery = ( + state: JavaScriptSemanticAnalysisState, +) => { + const readers = new WeakMap< + t.ObjectExpression, + ReturnType + >(); + return ( + bindingId: string | null, + capture: t.Node, + source: "property" | "array-iteration" = "property", + ) => { + 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 (source === "array-iteration") { + if (!t.isArrayExpression(value)) return undefined; + const array = semanticNativeArrayIterationValueAt(capture, state); + if (array === undefined || array.unknownItems) return undefined; + return (path: readonly string[]): boolean => { + const [key] = path; + if (key === undefined || path.length !== 1) return false; + const index = semanticArrayIndex(key); + const slot = index === null ? undefined : array.items[index]; + return ( + slot?.name === key && + slot.presence === "present" && + !capturedBindingPathMayHaveChanged(binding, path, capture, state) + ); + }; + } + 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); + }; + }; +}; diff --git a/src/domain/javascript/javascriptSemanticReferenceSources.ts b/src/domain/javascript/javascriptSemanticReferenceSources.ts index 50ac54517f..8181fb9cc0 100644 --- a/src/domain/javascript/javascriptSemanticReferenceSources.ts +++ b/src/domain/javascript/javascriptSemanticReferenceSources.ts @@ -33,24 +33,43 @@ interface ReferenceSource { readonly iterationSources?: readonly ReferenceSource[]; } +/** Shared intrinsic reached through a native array iterator's prototype. */ +export const semanticArrayIteratorPrototypePath = [ + "array-iterator-prototype", +] as const; +const arrayIteratorNextPath = [ + ...semanticArrayIteratorPrototypePath, + "next", +] as const; + /** Native array iteration preserves numeric slots only while its iterator is intact. */ export const semanticKnownArrayIteration = ( value: JavaScriptSemanticValue | undefined, state: JavaScriptSemanticAnalysisState, -): boolean => + read: t.Node, +): value is Extract => !state.arrayIterationUnknown && value?.status === "array" && + !ambientPathMayObserveAt(state, read, arrayIteratorNextPath, "contents") && value.items.every((item) => semanticArrayIndex(item.name) !== null); +/** + * Return the array that admits native iteration at this read. A plain array's + * numeric properties are the values consumed by its native iterator. + */ +export const semanticNativeArrayIterationValueAt = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, +) => { + const value = evaluateSemanticExpression(node, state, node); + return semanticKnownArrayIteration(value, state, node) ? value : undefined; +}; + /** Invocation spreads use the same native-iteration proof at their source read. */ export const semanticKnownArrayIterationAt = ( node: t.Node, state: JavaScriptSemanticAnalysisState, -): boolean => - semanticKnownArrayIteration( - evaluateSemanticExpression(node, state, node), - state, - ); +): boolean => semanticNativeArrayIterationValueAt(node, state) !== undefined; /** Numeric destructuring projections do not select slots of custom iterators. */ export const semanticReferenceIterationUnknown = ( @@ -75,8 +94,7 @@ const selectedReferenceIterationKnown = ( // inventory can prove every possible nested iterable without treating // a computed object property or custom iterator as an own-index read. if ( - !semanticKnownArrayIteration(value, state) || - value.status !== "array" || + !semanticKnownArrayIteration(value, state, source.node) || value.unknownItems ) return false; @@ -92,7 +110,9 @@ const selectedReferenceIterationKnown = ( } values = [...selected]; } - return values.every((value) => semanticKnownArrayIteration(value, state)); + return values.every((value) => + semanticKnownArrayIteration(value, state, source.node), + ); }; /** Exclude references whose source slot or destructuring fallback is absent. */ diff --git a/src/domain/javascript/javascriptSemanticReturnedReferences.ts b/src/domain/javascript/javascriptSemanticReturnedReferences.ts index 4238e07dda..a25fb6a755 100644 --- a/src/domain/javascript/javascriptSemanticReturnedReferences.ts +++ b/src/domain/javascript/javascriptSemanticReturnedReferences.ts @@ -553,6 +553,7 @@ export const createSemanticReturnedReferences = ( source.capturedSelectionAt, )?.value, state, + source.capturedSelectionAt, ) ) projection = [null, ...source.path.slice(1)]; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 5a8dce97af..37a3cafc4e 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -1,8 +1,6 @@ import type { JavaScriptSemanticPrecision } from "./javascriptSemanticPrecision.js"; import { applySemanticBindingReferenceEffects, - capturedBindingPathMayHaveChanged, - hasRecordedReferenceEffects, opaqueCodeMayRebindBinding, } from "./javascriptSemanticEffectLog.js"; import * as t from "@babel/types"; @@ -41,7 +39,6 @@ import { readSemanticRequireOriginCandidate } from "./javascriptSemanticRequireO import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { readExactJavaScriptLiteral, - staticObjectPropertyReader, semanticStaticPropertyKey, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; @@ -264,51 +261,6 @@ 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 6ef58d12d3..d0791bf2a1 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 earlier property dependencies through analysis and default tracing", + "traces proved destructuring dependencies and leaves custom iteration uncertain", async ({ cli }) => { const root = await createTestTempDirectory( "rea-js-destructuring-evidence-", @@ -26,6 +26,27 @@ cliTest( const { a: [plain] } = nested; const { a: [fallback] = [] } = nested; const { b: scalar = 0 } = nested; + const previous = { items: new Map() }; + const captured = previous.items; + previous.items = []; + Object.getPrototypeOf(captured.values()).next = () => ({ done: true }); + Reflect.apply(Reflect.getPrototypeOf, null, [[].values(), [].values()]); + const sourcePrototype = Object.getPrototypeOf([].values()); + Object.getPrototypeOf(sourcePrototype); + const before = ["first"]; + const [ordinary] = before; + let arrayAssigned; + [arrayAssigned] = before; + before[0] = "later"; + const box = { items: [] }; + const iterator = box.items.values(); + const prototype = Reflect.getPrototypeOf(iterator); + Object.defineProperty(prototype, "next", { + value: () => ({ value: "other", done: false }), + }); + const after = ["second"]; + let selected; + [selected] = after; `, ); const output = await cli.run({ @@ -36,12 +57,15 @@ cliTest( .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) .parse(output.json); const graph = result.semantic_graph; - for (const [name, path] of [ + for (const [name, path, resolution = "resolved"] of [ ["declared", ["a"]], ["a", ["a"]], ["plain", ["a", "0"]], ["fallback", ["a", "0"]], ["scalar", ["b"]], + ["ordinary", ["0"]], + ["arrayAssigned", ["0"]], + ["selected", ["0"], "candidate"], ] as const) { const binding = graph.nodes.find( (node) => node.kind === "binding" && node.label === name, @@ -53,43 +77,54 @@ cliTest( relation.target_node_id === binding?.node_id, ); expect(relations).toHaveLength(1); - expect(relations[0]?.resolution).toBe("resolved"); + expect(relations[0]?.resolution).toBe(resolution); expect( graph.nodes.find( (node) => node.node_id === relations[0]?.source_node_id, )?.properties.property_path, ).toEqual(path); } + const directRead = graph.nodes.find( + ({ kind, label }) => kind === "expression" && label === "read:/a", + ); expect( - graph.relations.find(({ relation }) => relation === "reads-property"), + graph.relations.find( + ({ relation, target_node_id }) => + relation === "reads-property" && + target_node_id === directRead?.node_id, + ), ).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", + for (const name of ["declared", "ordinary", "arrayAssigned", "selected"]) { + const binding = graph.nodes.find( + ({ kind, label }) => kind === "binding" && label === name, + ); + await writeFile( + queryPath, + JSON.stringify({ + application: output.json, + query: { + seed: { kind: "semantic-node", node_id: binding?.node_id }, + direction: "backward-provenance", + }, + }), + ); + const trace = await cli.run({ + 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, + }), + ]), }, - }), - ); - 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", - }), - ]), - }, - }); + }; + if (name === "selected") expect(trace.json).not.toMatchObject(relation); + else expect(trace.json).toMatchObject(relation); + } }, );