From f5573a0064b6afd1ba7c57d68eb3014d1468ee97 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:22:46 -0500 Subject: [PATCH] fix(javascript): acquire nested iterators from stored receivers (#12542) * fix(javascript): acquire nested iterators from stored receivers * fix(javascript): preserve stored iterator branches and pattern timing --- ...vaScriptSemanticGraphDestructuring.test.ts | 166 ++++++++++++++++++ .../javascript/javascriptSemanticEffectLog.ts | 53 ++++++ .../javascriptSemanticMemberMutations.ts | 111 +++++++++++- .../javascriptSemanticMutationInitializers.ts | 91 +++++++--- .../javascript/javascriptSemanticObjects.ts | 16 +- .../javascriptSemanticReadPresence.ts | 32 +++- .../javascript/javascriptSemanticValues.ts | 40 +++-- .../javascriptDestructuringEvidence.test.ts | 46 +++-- 8 files changed, 490 insertions(+), 65 deletions(-) diff --git a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts index fbfc237bf2..07e19dcdcf 100644 --- a/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphDestructuring.test.ts @@ -1484,3 +1484,169 @@ it.each([ ).toMatchObject({ resolution }); }, ); + +it.each([ + [ + "native replacement before acquisition", + closeNextObject, + "none=(box.items=[0,box.next]),items:[used]", + "candidate", + ], + [ + "native replacement after acquisition", + closeNextObject, + "items:[used],none=(box.items=[0,box.next])", + "resolved", + ], + [ + "native replacement with no close hook", + "", + "none=(box.items=[0,box.next]),items:[used]", + "resolved", + ], + [ + "custom replacement before acquisition", + "", + "none=(box.items={child:box.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}}),items:[used]", + "candidate", + ], + [ + "custom replacement after acquisition", + "", + "items:[used],none=(box.items={child:box.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}})", + "resolved", + ], + [ + "replacement's iterator updated before acquisition", + "", + "none=(box.items=[0,box.next]), second=(box.items[Symbol.iterator]=function(){delete this[1].mode;return [0].values();}),items:[used]", + "candidate", + ], +] as const)( + "captures the nested iterator receiver for %s", + (_name, hook, pattern, resolution) => { + const graph = graphForJavaScript(` + const box={items:[0],next:{mode:"before"}}; + ${hook} + const {${pattern},next:{mode:selected}}=box; + `); + const selected = graph.nodes.find( + (n) => n.kind === "binding" && n.label === "selected", + ); + expect( + graph.relations.find( + (r) => + r.relation === "destructures" && + r.target_node_id === selected?.node_id, + ), + ).toMatchObject({ resolution }); + }, +); + +it.each([ + ["two native arms", "flag ? [0,box.next] : [0]", "resolved"], + [ + "a possible custom arm", + "flag ? [0,box.next] : {child:box.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}}", + "candidate", + ], + [ + "an inactive custom arm", + "false ? {child:box.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}} : [0,box.next]", + "resolved", + ], +] as const)( + "retains conditional stored acquisition for %s", + (_name, store, resolution) => { + const graph = graphForJavaScript(` + const box={items:[0],next:{mode:"before"}}; + const {none=(box.items=${store}),items:[used],next:{mode:selected}}=box; + `); + const binding = graph.nodes.find( + (n) => n.kind === "binding" && n.label === "selected", + ); + expect( + graph.relations.find( + (r) => + r.target_node_id === binding?.node_id && + r.relation === "destructures", + ), + ).toMatchObject({ resolution }); + }, +); + +it.each([ + ["native close", closeNextObject, "[0,box.next]", "", "resolved"], + [ + "custom acquisition", + "", + "{child:box.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}}", + "", + "resolved", + ], + [ + "an ordinary prior write", + closeNextObject, + "[0,box.next]", + 'write=(box.next.mode="alternate"),', + "candidate", + ], +] as const)( + "orders sibling reads around stored %s", + (_name, hook, store, earlier, before) => { + const graph = graphForJavaScript(` + const box={items:[0],next:{mode:"initial"}}; + ${hook} + const {none=(box.items=${store}),${earlier}next:{mode:before},items:[used],next:{mode:after}}=box; + `); + for (const [name, resolution] of [ + ["before", before], + ["after", "candidate"], + ]) { + const binding = graph.nodes.find( + (n) => n.kind === "binding" && n.label === name, + ); + expect( + graph.relations.find( + (r) => + r.target_node_id === binding?.node_id && + r.relation === "destructures", + ), + ).toMatchObject({ resolution }); + } + }, +); + +it.each([ + ["ordinary property receiver", "box.parent", "candidate"], + ["parenthesized property receiver", '((box)["parent"])', "candidate"], + ["unknown receiver key", "box[key]", undefined], +] as const)( + "recovers a stored nested iterator for %s", + (_name, source, resolution) => { + const graph = graphForJavaScript(` + const box={parent:{items:[0],next:{mode:"before"}}}; + const replacement={child:box.parent.next,[Symbol.iterator](){delete this.child.mode;return [0].values();}}; + const {none=(box.parent.items=replacement),items:[used],next:{mode:selected}}=${source}; + `); + const binding = graph.nodes.find( + (n) => n.kind === "binding" && n.label === "selected", + ); + const relation = graph.relations.find( + (r) => + r.target_node_id === binding?.node_id && r.relation === "destructures", + ); + expect(relation?.resolution).toBe(resolution); + if (relation === undefined) + expect( + graph.unknowns.some(({ relation_kinds }) => + relation_kinds.includes("destructures"), + ), + ).toBe(true); + else + expect( + graph.nodes.find(({ node_id }) => node_id === relation.source_node_id) + ?.properties.property_path, + ).toEqual(["parent", "next", "mode"]); + }, +); diff --git a/src/domain/javascript/javascriptSemanticEffectLog.ts b/src/domain/javascript/javascriptSemanticEffectLog.ts index 54dce39507..3a4d831a09 100644 --- a/src/domain/javascript/javascriptSemanticEffectLog.ts +++ b/src/domain/javascript/javascriptSemanticEffectLog.ts @@ -27,6 +27,7 @@ import { } from "./javascriptSemanticEffectPathIndex.js"; import { isUnshadowedGlobal, + isSemanticArrayPatternEffect, semanticBindingEffectFollowsCapture, semanticEscapeFollowsCapture, semanticDefiniteEffectPrecedesReference, @@ -581,6 +582,27 @@ export const bindingMemberEffectMayPrecedeReads = ( return false; }; +/** Whether a selected receiver's contents can change before use. + * Writes replacing the receiver are covered by the source-selection query. + */ +export const bindingProjectedContentsMayChangeAt = ( + state: JavaScriptSemanticAnalysisState, + binding: JavaScriptSemanticBindingState, + path: JavaScriptSemanticPropertyPath, + read: t.Node, +): boolean => + opaqueCodeMayReachBindingReference(binding, state, read) || + bindingMemberEffectMayPrecedeReads( + state, + binding, + (kind, effect) => + (kind === "escape" || effect.path.length > path.length) && + semanticEffectPathMatches(effect.path.slice(0, path.length), path) + ? [read] + : undefined, + "activation", + ); + /** * Whether an assignment to `binding` recorded as a reference initializer * (a pattern or other non-ordinary write) may run before `read`. @@ -1031,6 +1053,37 @@ export const capturedBindingPathMayHaveChanged = ( ); }; +/** Preserve an own-data read when the only possible changes follow it in an iterator phase. */ +export const bindingPathOnlyEscapesAtLaterIteratorEffects = ( + binding: JavaScriptSemanticBindingState, + path: readonly string[], + read: t.Node, + state: JavaScriptSemanticAnalysisState, +): boolean => { + let laterIterator = false; + const matches = (effect: JavaScriptSemanticMemberEffect): boolean => + semanticEffectPathMatches(effect.path, path); + if ( + semanticSomeEffectPathCandidate(binding.escapedPaths, path, (effect) => { + if (!matches(effect)) return false; + if ( + !isSemanticArrayPatternEffect(effect.node) || + semanticEffectTiming(read, effect.node, state) !== "after" + ) + return true; + laterIterator = true; + return false; + }) || + !laterIterator + ) + return false; + return ( + !opaqueCodeMayReachBindingReference(binding, state, read) && + !semanticOpaqueGlobalMayHaveChanged(read, state) && + !semanticSomeEffectPathCandidate(binding.memberWrites, path, matches) + ); +}; + /** * The value of `binding`'s reference as a read captured at `capturePoint` * observes it, after the recorded effects that may precede the capture: diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 54ba5e1df7..ed46601e98 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -37,10 +37,15 @@ import { evaluateSemanticBinding, evaluateSemanticExpression, evaluateSemanticExpressionProvenance, + semanticSelectedBranchNodesAt, } from "./javascriptSemanticValues.js"; -import { bindingHasMemberWrites } from "./javascriptSemanticEffectLog.js"; +import { + bindingHasMemberWrites, + bindingProjectedContentsMayChangeAt, +} from "./javascriptSemanticEffectLog.js"; import { semanticContainer } from "./javascriptSemanticSlots.js"; import { + hasFreshProjectedReceiver, semanticProjectedSourceFactsAtRead, semanticCapturedSelectionsAfterPropertyRead, semanticShiftCapturedSelections, @@ -72,6 +77,7 @@ import { semanticBindingAtRead, semanticCaptureOrderingIdentity, semanticArrayPatternCloseScope, + semanticArrayPatternAcquisitionEffect, semanticScopeExitEffect, } from "./javascriptSemanticMutationInitializers.js"; import { @@ -105,6 +111,7 @@ import { } from "./javascriptSemanticTraversal.js"; import { semanticStaticPropertyKey, + semanticMemberChain, semanticWriteTargets, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; @@ -2008,6 +2015,104 @@ export function* collectSemanticMemberMutationsSteps( // A value thrown out of its function or the program reaches handlers the // throw-to-catch index does not link to it. for (const node of state.escapingThrows) markEscaped(node.argument, node); + const markAcquiredNestedIterator = ( + reference: IterableReference, + ): boolean => { + const { arrayPattern: pattern, mutation, node, projection } = reference; + if (pattern === undefined || projection.length === 0) return false; + const receiver = semanticMemberChain(node); + if (receiver === undefined || !t.isIdentifier(receiver.root)) return false; + const binding = resolveBinding(receiver.root, receiver.root.name); + if (binding === undefined || !bindingHasMemberWrites(binding)) return false; + const path = [...receiver.members, ...projection]; + // The RHS captures the parent, while the nested pattern selects the + // iterable later, after any preceding defaults or assignments. + const receiverCaptures = semanticNormalizeCapturedSelections([ + ...(semanticShiftCapturedSelections( + reference.capturedSelections, + receiver.members.length, + ) ?? []), + ...(receiver.members.length === 0 + ? [] + : [{ at: node, depth: receiver.members.length }]), + ]); + const captured = semanticProjectedSourceFactsAtRead( + binding, + receiver.root, + path, + state, + true, + pattern, + receiverCaptures, + ); + // A later-only write can invalidate the merged lattice without changing + // this acquisition. Leave the original capture on its established route. + if (captured === undefined || captured.storedSources.length === 0) + return false; + const contentsMayChange = bindingProjectedContentsMayChangeAt( + state, + binding, + path, + pattern, + ); + for (const source of captured.sources) { + const pending = [source.node]; + while (pending.length > 0) { + work.charge(); + const alternative = unwrapJavaScriptExpression(pending.pop()!).node; + if ( + t.isConditionalExpression(alternative) || + t.isLogicalExpression(alternative) + ) { + for (const branch of semanticSelectedBranchNodesAt( + alternative, + state, + source.node, + )) + pending.push(branch); + continue; + } + const value = semanticSelectedReferenceSlot( + { node: alternative, projection: source.path }, + state, + source.node, + )?.value; + const native = + !contentsMayChange && + semanticKnownArrayIteration(value, state, pattern) && + hasFreshProjectedReceiver(alternative, source.path, state); + const selection = native + ? semanticArrayPatternCloseSelection(pattern, mutation, value, state) + : undefined; + if (!native || selection !== undefined) + markValue( + alternative, + selection === undefined ? source.path : [...source.path, selection], + reference.bindings, + "escape", + native + ? semanticScopeExitEffect(pattern, mutation) + : semanticArrayPatternAcquisitionEffect(pattern, mutation), + alternative, + undefined, + false, + undefined, + false, + { + memberReadAt: source.node, + capturedSelections: semanticNormalizeCapturedSelections([ + ...(semanticShiftCapturedSelections( + reference.capturedSelections, + source.path.length - projection.length, + ) ?? []), + ...(source.capturedSelections ?? []), + ]), + }, + ); + } + } + return true; + }; // A later effect can make a previously defined destructuring source uncertain. // Reconsider defaults and iterable origins until their effects are stable. while ( @@ -2110,6 +2215,10 @@ export function* collectSemanticMemberMutationsSteps( state, capturesRootPattern ? node : undefined, ); + // A slot's value lattice loses identities invalidated by writes. Recover + // stored alternatives at the nested receiver's actual acquisition. + if (slot?.presence !== "present" && markAcquiredNestedIterator(reference)) + continue; // 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( diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 34d929f1f8..a3841a7b34 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -237,40 +237,74 @@ export const semanticTopLevelEffectFollowsCapture = ( ); }; -const scopeExitMarkers = new WeakMap(); -const scopeExitOwners = new WeakMap< +const scopeEffectMarkers = { + acquire: new WeakMap(), + exit: new WeakMap(), +}; +const scopeEffectOwners = new WeakMap< t.Node, - { readonly scope: t.Node; readonly positionOwner: t.Node } + { + readonly scope: t.Node; + readonly positionOwner: t.Node; + readonly phase: "acquire" | "exit"; + } >(); +const semanticScopeEffect = ( + scope: t.Node, + positionOwner: t.Node, + phase: "acquire" | "exit", +): t.Node => { + const markers = scopeEffectMarkers[phase]; + const cached = markers.get(scope); + if (cached !== undefined) return cached; + const marker = t.emptyStatement(); + const boundary = phase === "acquire" ? "start" : "end"; + if (scope[boundary] !== undefined) { + marker.start = scope[boundary]; + marker.end = scope[boundary]; + } + if (scope.loc != null) + marker.loc = { + ...scope.loc, + start: scope.loc[boundary], + end: scope.loc[boundary], + }; + markers.set(scope, marker); + scopeEffectOwners.set(marker, { scope, positionOwner, phase }); + return marker; +}; + /** A derived scope-end effect keeps finalization separate from source evaluation. */ export const semanticScopeExitEffect = ( scope: t.Node, positionOwner = scope, -): t.Node => { - const cached = scopeExitMarkers.get(scope); - if (cached !== undefined) return cached; - const marker = t.emptyStatement(); - if (scope.end !== undefined) { - marker.start = scope.end; - marker.end = scope.end; - } - if (scope.loc != null) - marker.loc = { ...scope.loc, start: scope.loc.end, end: scope.loc.end }; - scopeExitMarkers.set(scope, marker); - scopeExitOwners.set(marker, { scope, positionOwner }); - return marker; -}; +): t.Node => semanticScopeEffect(scope, positionOwner, "exit"); + +/** An array's iterator acquisition precedes the pattern's element targets. */ +export const semanticArrayPatternAcquisitionEffect = ( + scope: t.ArrayPattern, + positionOwner: t.Node | undefined, +): t.Node => semanticScopeEffect(scope, positionOwner ?? scope, "acquire"); /** The array pattern that owns a recorded native iterator close. */ export const semanticArrayPatternCloseScope = ( effect: t.Node | undefined, ): t.ArrayPattern | undefined => { - const scope = - effect === undefined ? undefined : scopeExitOwners.get(effect)?.scope; - return t.isArrayPattern(scope) ? scope : undefined; + const owner = + effect === undefined ? undefined : scopeEffectOwners.get(effect); + return owner?.phase === "exit" && t.isArrayPattern(owner.scope) + ? owner.scope + : undefined; }; +/** Whether an effect belongs to the opening or closing of an array pattern. */ +export const isSemanticArrayPatternEffect = ( + effect: t.Node | undefined, +): boolean => + effect !== undefined && + t.isArrayPattern(scopeEffectOwners.get(effect)?.scope); + const withinScopeExit = ( reference: t.Node, scope: t.Node, @@ -304,9 +338,13 @@ export const semanticEffectFollowsReference = ( parents: WeakMap, ): boolean => { if (reference === effect) return false; - const exit = effect === undefined ? undefined : scopeExitOwners.get(effect); + const exit = effect === undefined ? undefined : scopeEffectOwners.get(effect); if (exit !== undefined) { - if (withinScopeExit(reference, exit.scope, parents)) return true; + if ( + (exit.phase === "exit" || reference === exit.scope) && + withinScopeExit(reference, exit.scope, parents) + ) + return true; effect = exit.scope; } let current: t.Node | undefined = reference; @@ -359,9 +397,10 @@ export const semanticEffectTiming = ( state: JavaScriptSemanticAnalysisState, ): JavaScriptSemanticEffectTiming => { if (effect === undefined) return "unknown"; - const exit = scopeExitOwners.get(effect); + const exit = scopeEffectOwners.get(effect); if (exit !== undefined) { - if (withinScopeExit(site, exit.scope, state.parentsByNode)) return "after"; + if (withinScopeExit(site, exit.scope, state.parentsByNode)) + return exit.phase === "exit" || site === exit.scope ? "after" : "before"; effect = exit.scope; } // Invocation receives arguments after their values have been selected. @@ -1984,7 +2023,7 @@ export const semanticEscapeFollowsCapture = ( ) return false; const capturePosition = semanticCapturePosition(capture, parents); - const exit = scopeExitOwners.get(escape); + const exit = scopeEffectOwners.get(escape); if (exit !== undefined) { // Unlike a source-global ordering proof, this binding was initialized in // the captured body. Its later sibling scope exits follow this activation. @@ -1998,7 +2037,7 @@ export const semanticEscapeFollowsCapture = ( positionOwner.init === capture) || (t.isAssignmentExpression(positionOwner) && positionOwner.right === capture))) || - withinScopeExit(capture, scope, parents) || + (exit.phase === "exit" && withinScopeExit(capture, scope, parents)) || (capturePosition !== null && exitPosition !== null && (positionPrecedes(capturePosition, exitPosition) || diff --git a/src/domain/javascript/javascriptSemanticObjects.ts b/src/domain/javascript/javascriptSemanticObjects.ts index cb0bf0808d..60ee58cc51 100644 --- a/src/domain/javascript/javascriptSemanticObjects.ts +++ b/src/domain/javascript/javascriptSemanticObjects.ts @@ -146,7 +146,7 @@ const collectDestructuring = ( ): void => { const source = expressionObjectIdentity(initializer, state); const rootArray = t.isArrayPattern(root); - let ownSlot = + const sourcePresence = initializer != null && source.path !== null ? readPresence( source.bindingId, @@ -154,13 +154,15 @@ const collectDestructuring = ( rootArray ? source.path : undefined, ) : undefined; + let ownSlot = sourcePresence; // 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 | undefined; readonly path: readonly string[]; + readonly plainObjectPath?: boolean; readonly lookup?: "own" | "unproven"; - } | null)[] = [{ pattern: root, path: [] }]; + } | null)[] = [{ pattern: root, path: [], plainObjectPath: !rootArray }]; while (pending.length > 0) { const next = pending.pop(); if (next === undefined) break; @@ -184,6 +186,8 @@ const collectDestructuring = ( // contributes no binding once the shared slot check has run. if (next.pattern === undefined) continue; const occurrence = unwrapJavaScriptExpression(next.pattern).node; + const plainObjectPath = + next.plainObjectPath === true && !t.isAssignmentPattern(occurrence); if (t.isAssignmentPattern(occurrence)) ownSlot = undefined; const pattern = t.isAssignmentPattern(occurrence) ? unwrapJavaScriptExpression(occurrence.left).node @@ -204,6 +208,7 @@ const collectDestructuring = ( pending.push({ pattern: property.value, path: [...path, name], + plainObjectPath: plainObjectPath && !property.computed, lookup: property.computed ? "unproven" : "own", }); } @@ -242,7 +247,12 @@ const collectDestructuring = ( objectBindingId: source.bindingId, targetBindingId: targetBinding?.bindingId ?? null, propertyPath, - provenOwnSlot: ownSlot !== undefined, + provenOwnSlot: + ownSlot !== undefined || + (plainObjectPath && + targetBinding !== undefined && + propertyPath !== null && + sourcePresence?.(propertyPath, occurrence) !== undefined), }, state, output, diff --git a/src/domain/javascript/javascriptSemanticReadPresence.ts b/src/domain/javascript/javascriptSemanticReadPresence.ts index 7195539e1f..c1f5898824 100644 --- a/src/domain/javascript/javascriptSemanticReadPresence.ts +++ b/src/domain/javascript/javascriptSemanticReadPresence.ts @@ -4,6 +4,7 @@ import { unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; import { + bindingPathOnlyEscapesAtLaterIteratorEffects, capturedBindingPathMayHaveChanged, hasRecordedReferenceEffects, opaqueCodeMayRebindBinding, @@ -160,7 +161,11 @@ export const createSemanticReadPresenceQuery = ( !semanticKnownArrayIteration(array, state, capture)) ) return undefined; - return (path: readonly string[]): t.Node | undefined => { + return ( + path: readonly string[], + beforeIterator?: t.Node, + ): t.Node | undefined => { + if (beforeIterator !== undefined) return undefined; const key = path[arrayPath.length]; if (key === undefined) return undefined; const index = semanticArrayIndex(key); @@ -190,13 +195,28 @@ export const createSemanticReadPresenceQuery = ( }; } if (!t.isObjectExpression(value)) return undefined; - return (path: readonly string[]): t.Node | undefined => { + return ( + path: readonly string[], + beforeIterator?: t.Node, + ): t.Node | undefined => { if (path.length === 0) return undefined; const selected = ownDataAtPath(value, path); - return selected === undefined || - capturedBindingPathMayHaveChanged(origin.binding, path, capture, state) - ? undefined - : selected; + if (selected === undefined) return undefined; + const stillPresent = + beforeIterator === undefined + ? !capturedBindingPathMayHaveChanged( + origin.binding, + path, + capture, + state, + ) + : bindingPathOnlyEscapesAtLaterIteratorEffects( + origin.binding, + path, + beforeIterator, + state, + ); + return stillPresent ? selected : undefined; }; }; }; diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index cd65818f69..1dcb470b0a 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -248,6 +248,34 @@ export const evaluateSemanticBinding = ( memo: createEvaluationMemo(state), }); +const expressionEvaluationContext = ( + state: JavaScriptSemanticAnalysisState, + captureScope: "state" | "query" = "state", +): EvaluationContext => ({ + state, + bindings: new Map(), + expressionDepth: 0, + primitiveBindingValues: primitiveBindingValuesFor(state), + dependence: { lowest: CALLER_INDEPENDENT }, + memo: createEvaluationMemo( + state, + captureScope === "query" ? new WeakMap() : undefined, + ), +}); + +/** Select control-flow branches without merging their distinct source values. */ +export const semanticSelectedBranchNodesAt = ( + node: t.ConditionalExpression | t.LogicalExpression, + state: JavaScriptSemanticAnalysisState, + capture: t.Node, +): readonly t.Node[] => { + const context = expressionEvaluationContext(state); + return semanticSelectedBranches( + node, + captureContextAt(capture, context) ?? context, + ).map(({ node }) => node); +}; + /** Evaluate an inert expression, optionally at an earlier reference capture. */ export const evaluateSemanticExpression = ( node: t.Node, @@ -255,17 +283,7 @@ export const evaluateSemanticExpression = ( capturePoint?: t.Node, captureScope: "state" | "query" = "state", ): JavaScriptSemanticValue => { - const context: EvaluationContext = { - state, - bindings: new Map(), - expressionDepth: 0, - primitiveBindingValues: primitiveBindingValuesFor(state), - dependence: { lowest: CALLER_INDEPENDENT }, - memo: createEvaluationMemo( - state, - captureScope === "query" ? new WeakMap() : undefined, - ), - }; + const context = expressionEvaluationContext(state, captureScope); return capturePoint === undefined ? evaluateCapturedExpression(node, context) : evaluateExpression( diff --git a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts index ac62f95ee6..5aed6fb692 100644 --- a/tests/boundary/cli/javascriptDestructuringEvidence.test.ts +++ b/tests/boundary/cli/javascriptDestructuringEvidence.test.ts @@ -19,8 +19,35 @@ const iteratorCloseSource = ` const restSource = [undefined, { mode: "before" }]; try { const [head = null.value, ...rest] = restSource; } catch {} const { 1: { mode: abruptAfterClose } } = restSource; + const replaced = { items: [0], next: { mode: "borrowed" } }; + const { replace = (replaced.items = [0, replaced.next]), next: { mode: replacedBeforeClose }, items: [use], next: { mode: replacedAfterClose } } = replaced; + const holder = { parent: { items: [0], next: { mode: "before" } } }; + const custom = { child: holder.parent.next, [Symbol.iterator]() { delete this.child.mode; return [0].values(); } }; + const { useCustom = (holder.parent.items = custom), items: [read], next: { mode: projectedAfterAcquisition } } = holder.parent; `; +const expectedDependencies = [ + ["declared", ["a"]], + ["a", ["a"]], + ["plain", ["a", "0"]], + ["fallback", ["a", "0"]], + ["scalar", ["b"]], + ["ordinary", ["0"]], + ["arrayAssigned", ["0"]], + ["elided", ["1"]], + ["projected", ["items", "0"]], + ["arrayObject", ["0", "mode"]], + ["selected", ["0"], "candidate"], + ["beforeClose", ["label"]], + ["consumed", ["items", "0", "mode"]], + ["afterClose", ["items", "1", "mode"], "candidate"], + ["storedAfterClose", ["next", "mode"], "candidate"], + ["abruptAfterClose", ["1", "mode"], "candidate"], + ["replacedBeforeClose", ["next", "mode"]], + ["replacedAfterClose", ["next", "mode"], "candidate"], + ["projectedAfterAcquisition", ["parent", "next", "mode"], "candidate"], +] as const; + cliTest( "traces proved destructuring dependencies and leaves custom iteration uncertain", async ({ cli }) => { @@ -82,24 +109,7 @@ cliTest( .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) .parse(output.json); const graph = result.semantic_graph; - for (const [name, path, resolution = "resolved"] of [ - ["declared", ["a"]], - ["a", ["a"]], - ["plain", ["a", "0"]], - ["fallback", ["a", "0"]], - ["scalar", ["b"]], - ["ordinary", ["0"]], - ["arrayAssigned", ["0"]], - ["elided", ["1"]], - ["projected", ["items", "0"]], - ["arrayObject", ["0", "mode"]], - ["selected", ["0"], "candidate"], - ["beforeClose", ["label"]], - ["consumed", ["items", "0", "mode"]], - ["afterClose", ["items", "1", "mode"], "candidate"], - ["storedAfterClose", ["next", "mode"], "candidate"], - ["abruptAfterClose", ["1", "mode"], "candidate"], - ] as const) { + for (const [name, path, resolution = "resolved"] of expectedDependencies) { const binding = graph.nodes.find( (node) => node.kind === "binding" && node.label === name, );