fix(javascript): retain array-pattern iterator close effects (#12534)

* fix(javascript): retain array-pattern iterator close effects

* fix(javascript): bound array-pattern close exposure

* fix(javascript): follow stored array elements at iterator close

* fix(javascript): retain iterator closes before array rest
This commit is contained in:
morluto authored and GitHub committed 2026-11-19 21:57:50 +00:00
1 parent 756f772430
commit 8ef5a34ff5
9 files changed
+601 -49

No files matched your search

@@ -1117,3 +1117,370 @@ it.each([
).toEqual(path);
},
);
const closeHandler =
"function () { delete this.next().value.mode; return {}; }";
it.each([
["native close", "", "resolved"],
[
"direct Array Iterator prototype",
"Object.getPrototypeOf([].values()).return = " + closeHandler + ";",
"candidate",
],
[
"captured Array Iterator prototype",
"const iterator=[].values(); const p=Object.getPrototypeOf(iterator); p.return = " +
closeHandler +
";",
"candidate",
],
[
"inherited Iterator prototype",
"Object.getPrototypeOf(Object.getPrototypeOf([].values())).return = " +
closeHandler +
";",
"candidate",
],
[
"global Iterator prototype",
"Iterator.prototype.return = " + closeHandler + ";",
"candidate",
],
[
"inherited Object prototype",
"Object.prototype.return = " + closeHandler + ";",
"candidate",
],
[
"unrelated Array prototype",
"Array.prototype.return = " + closeHandler + ";",
"resolved",
],
] as const)(
"tracks a nested array-pattern close through %s",
(_name, hook, resolution) => {
const graph = graphForJavaScript(`
const box={label:"ready",items:[0,{mode:"before"}]};
${hook}
const {label:before,items:[first],items:{0:primitive,1:{mode:selected}}}=box;
`);
const edge = (name: string) => {
const binding = graph.nodes.find(
(n) => n.kind === "binding" && n.label === name,
);
return graph.relations.find(
(r) =>
r.relation === "destructures" &&
r.target_node_id === binding?.node_id,
);
};
expect(edge("before")).toMatchObject({ resolution: "resolved" });
expect(edge("primitive")).toMatchObject({ resolution: "resolved" });
expect(edge("selected")).toMatchObject({ resolution });
},
);
it.each([
[
"hook before read",
`Object.getPrototypeOf([].values()).return = ${closeHandler};`,
"",
"candidate",
],
[
"hook after read",
"",
`Object.getPrototypeOf([].values()).return = ${closeHandler};`,
"resolved",
],
] as const)(
"preserves outer iterator close timing for %s",
(_name, before, after, resolution) => {
const graph = graphForJavaScript(`
const box=[0,{mode:"before"}];
${before}
const [first]=box;
const {1:{mode:selected}}=box;
${after}
`);
for (const [name, expected] of [
["first", "resolved"],
["selected", resolution],
]) {
const binding = graph.nodes.find(
(n) => n.kind === "binding" && n.label === name,
);
expect(
graph.relations.find(
(r) =>
r.relation === "destructures" &&
r.target_node_id === binding?.node_id,
),
).toMatchObject({ resolution: expected });
}
},
);
it.each([
["empty pattern", "", "candidate"],
["rest drains iterator", "...rest", "resolved"],
] as const)("preserves close presence for %s", (_name, pattern, resolution) => {
const graph = graphForJavaScript(`
const box={items:[{mode:"before"}]};
Object.getPrototypeOf([].values()).return = ${closeHandler};
const {items:[${pattern}],items:{0:{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 });
});
const closeNextObject =
"Object.getPrototypeOf([].values()).return=function(){const next=this.next().value;if(next)delete next.mode;return {}};";
it.each([
[
"unconsumed suffix",
'const items=[{mode:"first"},{mode:"second"}];',
"const [used]=items;",
"resolved",
"candidate",
],
[
"shared element identity",
'const value={mode:"shared"};const items=[value,value];',
"const [used]=items;",
"candidate",
"candidate",
],
[
"all slots consumed",
'const items=[{mode:"first"},{mode:"second"}];',
"const [used,alsoUsed]=items;",
"resolved",
"resolved",
],
[
"native exhaustion observed",
'const items=[{mode:"first"},{mode:"second"}];',
"const [used,alsoUsed,done]=items;",
"resolved",
"resolved",
],
[
"earlier default",
'const items=[undefined,{mode:"second"}];',
'const [used=(items.push({mode:"added"}),0)]=items;',
"candidate",
"candidate",
],
] as const)(
"bounds native close exposure for %s",
(_name, setup, pattern, first, second) => {
const graph = graphForJavaScript(`
${setup}
${closeNextObject}
${pattern}
const {0:{mode:first},1:{mode:second}}=items;
`);
for (const [name, resolution] of [
["first", first],
["second", second],
]) {
const binding = graph.nodes.find(
(n) => n.kind === "binding" && n.label === name,
);
expect(
graph.relations.find(
(r) =>
r.relation === "destructures" &&
r.target_node_id === binding?.node_id,
),
).toMatchObject({ resolution });
}
},
);
it.each([
[
"earlier declarator",
"const {1:{mode:selected}}=items,[used]=items;",
"resolved",
],
[
"later declarator",
"const [used]=items,{1:{mode:selected}}=items;",
"candidate",
],
[
"earlier assignment",
"let selected,used; (({1:{mode:selected}}=items),[used]=items);",
"resolved",
],
[
"later assignment",
"let selected,used; ([used]=items,({1:{mode:selected}}=items));",
"candidate",
],
] as const)(
"orders a native close relative to an %s",
(_name, pattern, resolution) => {
const graph = graphForJavaScript(`
const items=[0,{mode:"inherited"}]; ${closeNextObject}
${pattern}
`);
const binding = graph.nodes.find(
(n) => n.kind === "binding" && n.label === "selected",
);
expect(
graph.relations.find(
(r) =>
r.relation === "destructures" &&
r.target_node_id === binding?.node_id,
),
).toMatchObject({ resolution });
},
);
it.each([
[
"after close",
"items:[used], missing=(Object.getPrototypeOf([].values()).return=hook)",
"resolved",
],
[
"before close",
"missing=(Object.getPrototypeOf([].values()).return=hook), items:[used]",
"candidate",
],
] as const)(
"keeps a hook assigned by a default %s in order",
(_name, prefix, resolution) => {
const graph = graphForJavaScript(`
const box={items:[0,{mode:"initial"}]};
function hook(){const next=this.next().value;if(next)delete next.mode;return {};}
const {${prefix}, items:{1:{mode:selected}}}=box;
`);
const binding = graph.nodes.find(
(n) => n.kind === "binding" && n.label === "selected",
);
expect(
graph.relations.find(
(r) =>
r.relation === "destructures" &&
r.target_node_id === binding?.node_id,
),
).toMatchObject({ resolution });
},
);
it.each([
["before close", "none=(box.items[1]=box.next), items:[used]", "candidate"],
["after close", "items:[used], none=(box.items[1]=box.next)", "resolved"],
] as const)(
"follows an array-pattern close through a slot assigned %s",
(_name, prefix, resolution) => {
const graph = graphForJavaScript(`
const box={items:[0],next:{mode:"second"}};
${closeNextObject}
const {${prefix},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("keeps consumed objects uncertain when an earlier default also stores them in the suffix", () => {
const graph = graphForJavaScript(`
const box={items:[{mode:"first"}]};
${closeNextObject}
const {none=(box.items[1]=box.items[0]),items:[used],items:{0:{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: "candidate" });
});
it.each([
[
"throwing default",
"undefined,",
"const [first = null.value, ...rest] = items;",
"1",
"candidate",
],
[
"plain lexical prefix",
"undefined,",
"const [first, ...rest] = items;",
"1",
"resolved",
],
[
"known unused default",
"0,",
"const [first = null.value, ...rest] = items;",
"1",
"resolved",
],
[
"nested target that throws",
"null,",
"const [{first}, ...rest] = items;",
"1",
"candidate",
],
[
"immutable assignment target",
"0,",
"const first = 0; let rest; [first, ...rest] = items;",
"1",
"candidate",
],
[
"computed rest target that throws before draining",
"",
"const target = {}; [...target[null.value]] = items;",
"0",
"candidate",
],
] as const)(
"models a native close before rest for %s",
(_name, prefix, pattern, key, resolution) => {
const graph = graphForJavaScript(`
const items=[${prefix}{mode:"before"}];
Object.getPrototypeOf([].values()).return = ${closeHandler};
try { ${pattern} } catch {}
const {${key}:{mode:selected}}=items;
`);
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 });
},
);
@@ -22,8 +22,11 @@ export const semanticEffectPathMatches = (
semanticAliasSelectionChoices(selected).some(
(choice) =>
choice === null ||
typeof choice === "object" ||
semanticPropertyPathKeyMatches(key, String(choice)),
(typeof choice === "object"
? key === null ||
typeof key === "object" ||
semanticPropertyPathKeyMatches(choice, String(key))
: semanticPropertyPathKeyMatches(key, String(choice))),
)
);
});
@@ -13,6 +13,8 @@ export interface SemanticIterationSource extends IterationSourceValue {
readonly iterationSources?: readonly IterationSourceValue[];
readonly kind: "iteration" | "reference-store";
readonly mutation: t.Node;
/** A declaration or assignment can close this iterator when its pattern finishes. */
readonly arrayPattern?: t.ArrayPattern;
readonly target?: t.MemberExpression;
readonly fallbackSources?: readonly IterationSourceValue[];
readonly requiredSources?: readonly IterationSourceValue[];
@@ -236,7 +236,17 @@ const visit = (
}
if (t.isArrayPattern(pattern)) {
if (source !== undefined && source.restStartIndex === undefined)
add(sources, source, mutation, guards);
sources.push({
kind: "iteration",
node: source.node,
projection: source.projection,
mutation,
...(t.isVariableDeclarator(mutation) ||
t.isAssignmentExpression(mutation)
? { arrayPattern: pattern }
: {}),
...guards,
});
const selectedGuards = {
...guards,
iterationSources: [
@@ -38,6 +38,7 @@ import {
evaluateSemanticExpression,
evaluateSemanticExpressionProvenance,
} from "./javascriptSemanticValues.js";
import { bindingHasMemberWrites } from "./javascriptSemanticEffectLog.js";
import { semanticContainer } from "./javascriptSemanticSlots.js";
import {
semanticProjectedSourceFactsAtRead,
@@ -70,6 +71,7 @@ import {
semanticMutationInitializers,
semanticBindingAtRead,
semanticCaptureOrderingIdentity,
semanticArrayPatternCloseScope,
semanticScopeExitEffect,
} from "./javascriptSemanticMutationInitializers.js";
import {
@@ -79,6 +81,7 @@ import {
type JavaScriptExecution,
} from "./javascriptSemanticExecutionPoints.js";
import {
semanticArrayPatternCloseSelection,
semanticKnownArrayIteration,
semanticReferenceSourcesInactive,
semanticSelectedReferenceSlot,
@@ -872,6 +875,7 @@ export function* collectSemanticMemberMutationsSteps(
reference.memberReadAt?.end,
capturedSelectionKey(reference.capturedSelections),
reference.iterationOnly,
reference.arrayPattern?.start,
reference.widenedGetterResult === true,
reference.definiteReceiver === true,
reference.assignedSources?.[0]?.target?.start,
@@ -932,6 +936,7 @@ export function* collectSemanticMemberMutationsSteps(
readonly value: JoinedProjection;
};
};
const patternClose = semanticArrayPatternCloseScope(mutation);
const pending: PendingValue[] = [];
const schedule = (value: PendingValue): void => {
work.charge();
@@ -1046,7 +1051,8 @@ export function* collectSemanticMemberMutationsSteps(
bindings,
originAt,
definiteReceiver,
memberReadAt: selection?.memberReadAt ?? mutation ?? originAt,
memberReadAt:
selection?.memberReadAt ?? patternClose ?? mutation ?? originAt,
capturedSelections: selection?.capturedSelections,
...(ownerInitializer === undefined ? {} : { ownerInitializer }),
});
@@ -1369,7 +1375,7 @@ export function* collectSemanticMemberMutationsSteps(
...origins.initializers,
...origins.referenceInitializers,
];
const receiver =
const storedReceiverPath =
effect === "write" &&
current.path.length > 1 &&
binding.memberWrites.some(
@@ -1377,16 +1383,24 @@ export function* collectSemanticMemberMutationsSteps(
write.assignedSources !== undefined &&
write.path.length < current.path.length,
)
? semanticProjectedSourceFactsAtRead(
? current.path.slice(0, -1)
: patternClose !== undefined &&
current.path.length > 0 &&
bindingHasMemberWrites(binding)
? current.path
: undefined;
const receiver =
storedReceiverPath === undefined
? undefined
: semanticProjectedSourceFactsAtRead(
binding,
current.node,
current.path.slice(0, -1),
storedReceiverPath,
state,
false,
current.memberReadAt ?? current.originAt ?? current.node,
current.capturedSelections,
)
: undefined;
);
// Stored receiver projections preserve their raw capture authority.
// Initializer origins retain the normalized mutation traversal below.
retainsInitializers = receiver?.retainsOrigin !== false;
@@ -1420,15 +1434,21 @@ export function* collectSemanticMemberMutationsSteps(
for (const source of receiver.storedSources)
enqueue({
node: source.node,
path: [...source.path, current.path.at(-1)!],
path:
patternClose === undefined
? [...source.path, current.path.at(-1)!]
: source.path,
bindings: nested,
definiteReceiver: false,
originAt: source.node,
memberReadAt: current.memberReadAt,
memberReadAt:
patternClose === undefined
? current.memberReadAt
: source.node,
capturedSelections: semanticNormalizeCapturedSelections([
...(semanticShiftCapturedSelections(
current.capturedSelections,
source.path.length - (current.path.length - 1),
source.path.length - storedReceiverPath!.length,
) ?? []),
...(source.capturedSelections ?? []),
]),
@@ -1898,6 +1918,9 @@ export function* collectSemanticMemberMutationsSteps(
effect: "escape",
originAt: source.mutation,
iterationOnly: source.kind === "iteration",
...(source.arrayPattern === undefined
? {}
: { arrayPattern: source.arrayPattern }),
});
}
for (const source of semanticPropertyReadSources(node, parent, state)) {
@@ -2094,7 +2117,28 @@ export function* collectSemanticMemberMutationsSteps(
state,
reference.node,
);
if (knownArray && reference.iterationOnly) continue;
if (knownArray && reference.iterationOnly) {
const pattern = reference.arrayPattern;
const selection =
pattern === undefined
? undefined
: semanticArrayPatternCloseSelection(
pattern,
mutation,
slot.value,
state,
);
if (pattern !== undefined && selection !== undefined)
markValue(
node,
[...projection, selection],
reference.bindings,
"escape",
semanticScopeExitEffect(pattern, mutation),
reference.originAt,
);
continue;
}
markValue(
reference.node,
knownArray ? reference.path : reference.fallbackPath,
@@ -2143,6 +2187,7 @@ interface IterableReference extends ReferencedValue, MutationSelectionContext {
readonly mutation?: t.Node;
readonly originAt: t.Node | undefined;
readonly iterationOnly?: boolean;
readonly arrayPattern?: t.ArrayPattern;
readonly definiteReceiver?: boolean;
readonly assignedSources?: readonly SemanticIterationSource[];
readonly requiredSources?: NonNullable<
@@ -169,6 +169,14 @@ const positionPrecedes = (
left.declaratorIndex >= 0 &&
left.declaratorIndex < right.declaratorIndex));
const sameStatementPosition = (
left: StatementPosition,
right: StatementPosition,
): boolean =>
left.body === right.body &&
left.index === right.index &&
left.declaratorIndex === right.declaratorIndex;
/** Statement position of a node evaluated once by the program, outside loops and functions. */
const computeTopLevelStatementPosition = (
node: t.Node | undefined,
@@ -223,20 +231,23 @@ export const semanticTopLevelEffectFollowsCapture = (
const after = topLevelStatementPosition(effect, parents);
if (before === null || after === null) return false;
if (positionPrecedes(before, after)) return true;
if (
before.body !== after.body ||
before.index !== after.index ||
before.declaratorIndex !== after.declaratorIndex
)
return false;
return expressionEvaluationOrder(capture, effect, parents) === "before";
return (
sameStatementPosition(before, after) &&
expressionEvaluationOrder(capture, effect, parents) === "before"
);
};
const scopeExitMarkers = new WeakMap<t.Node, t.EmptyStatement>();
const scopeExitOwners = new WeakMap<t.Node, t.Node>();
const scopeExitOwners = new WeakMap<
t.Node,
{ readonly scope: t.Node; readonly positionOwner: t.Node }
>();
/** A derived scope-end effect keeps disposal separate from initializer evaluation. */
export const semanticScopeExitEffect = (scope: t.Node): t.Node => {
/** 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();
@@ -247,10 +258,19 @@ export const semanticScopeExitEffect = (scope: t.Node): t.Node => {
if (scope.loc != null)
marker.loc = { ...scope.loc, start: scope.loc.end, end: scope.loc.end };
scopeExitMarkers.set(scope, marker);
scopeExitOwners.set(marker, scope);
scopeExitOwners.set(marker, { scope, positionOwner });
return marker;
};
/** 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 withinScopeExit = (
reference: t.Node,
scope: t.Node,
@@ -286,8 +306,8 @@ export const semanticEffectFollowsReference = (
if (reference === effect) return false;
const exit = effect === undefined ? undefined : scopeExitOwners.get(effect);
if (exit !== undefined) {
if (withinScopeExit(reference, exit, parents)) return true;
effect = exit;
if (withinScopeExit(reference, exit.scope, parents)) return true;
effect = exit.scope;
}
let current: t.Node | undefined = reference;
let child: t.Node | undefined;
@@ -341,8 +361,8 @@ export const semanticEffectTiming = (
if (effect === undefined) return "unknown";
const exit = scopeExitOwners.get(effect);
if (exit !== undefined) {
if (withinScopeExit(site, exit, state.parentsByNode)) return "after";
effect = exit;
if (withinScopeExit(site, exit.scope, state.parentsByNode)) return "after";
effect = exit.scope;
}
// Invocation receives arguments after their values have been selected.
if (
@@ -480,8 +500,10 @@ const expressionChildIndices = (
if (cached !== undefined) return cached;
const children = ((): readonly (t.Node | null)[] | null => {
if (t.isSequenceExpression(node)) return node.expressions;
if (t.isArrayExpression(node)) return node.elements;
if (t.isObjectExpression(node)) return node.properties;
if (t.isArrayExpression(node) || t.isArrayPattern(node))
return node.elements;
if (t.isObjectExpression(node) || t.isObjectPattern(node))
return node.properties;
if (t.isObjectProperty(node))
return node.computed ? [node.key, node.value] : [node.value];
if (
@@ -650,9 +672,7 @@ export const semanticDefiniteEffectPrecedesReference = (
return false;
if (positionPrecedes(before, after.position)) return true;
return (
before.body === after.position.body &&
before.index === after.position.index &&
before.declaratorIndex === after.position.declaratorIndex &&
sameStatementPosition(before, after.position) &&
expressionEvaluationOrder(effect, reference, parents) === "before"
);
};
@@ -669,9 +689,7 @@ export const semanticReadPrecedesEffectWithinActivation = (
return false;
if (positionPrecedes(before.position, after)) return true;
return (
before.position.body === after.body &&
before.position.index === after.index &&
before.position.declaratorIndex === after.declaratorIndex &&
sameStatementPosition(before.position, after) &&
expressionEvaluationOrder(read, effect, parents) === "before"
);
};
@@ -1970,14 +1988,24 @@ export const semanticEscapeFollowsCapture = (
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.
const exitPosition = t.isStatement(exit)
? statementPosition(exit, parents)
: null;
const { scope, positionOwner } = exit;
const exitPosition = t.isStatement(scope)
? statementPosition(scope, parents)
: directMutationPosition(positionOwner, parents);
return (
withinScopeExit(capture, exit, parents) ||
(t.isArrayPattern(scope) &&
((t.isVariableDeclarator(positionOwner) &&
positionOwner.init === capture) ||
(t.isAssignmentExpression(positionOwner) &&
positionOwner.right === capture))) ||
withinScopeExit(capture, scope, parents) ||
(capturePosition !== null &&
exitPosition !== null &&
positionPrecedes(capturePosition, exitPosition))
(positionPrecedes(capturePosition, exitPosition) ||
(t.isArrayPattern(scope) &&
sameStatementPosition(capturePosition, exitPosition) &&
expressionEvaluationOrder(capture, positionOwner, parents) ===
"before")))
);
}
const escapePosition = directMutationPosition(escape, parents);
@@ -134,10 +134,18 @@ export const createSemanticReadPresenceQuery = (
)
return undefined;
const { value } = origin;
if (iterationPath !== undefined) {
// An identifier RHS in an object pattern can select numeric own data
// without starting an iterator, even when a later read closes one.
const arrayPath =
iterationPath ??
(t.isArrayExpression(value) &&
t.isIdentifier(unwrapJavaScriptExpression(capture).node)
? []
: undefined);
if (arrayPath !== undefined) {
// The RHS must select an own data value before numeric array slots can
// explain the binding. Temporal checks still use the full origin path.
const literal = ownDataAtPath(value, iterationPath);
const literal = ownDataAtPath(value, arrayPath);
if (!t.isArrayExpression(literal)) return undefined;
const array = evaluateSemanticExpression(
capture,
@@ -146,12 +154,14 @@ export const createSemanticReadPresenceQuery = (
"query",
);
if (
!semanticKnownArrayIteration(array, state, capture) ||
array.unknownItems
array.status !== "array" ||
array.unknownItems ||
(iterationPath !== undefined &&
!semanticKnownArrayIteration(array, state, capture))
)
return undefined;
return (path: readonly string[]): t.Node | undefined => {
const key = path[iterationPath.length];
const key = path[arrayPath.length];
if (key === undefined) return undefined;
const index = semanticArrayIndex(key);
if (index === null) return undefined;
@@ -166,7 +176,7 @@ export const createSemanticReadPresenceQuery = (
const selected = ownDataAtPath(
unwrapJavaScriptExpression(element).node,
path,
iterationPath.length + 1,
arrayPath.length + 1,
);
return selected === undefined ||
capturedBindingPathMayHaveChanged(
@@ -1,7 +1,8 @@
import type * as t from "@babel/types";
import * as t from "@babel/types";
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
import {
semanticArrayIndex,
type JavaScriptSemanticPropertySelection,
type JavaScriptSemanticPropertyPath as PropertyPath,
} from "./javascriptSemanticPropertyPaths.js";
import {
@@ -53,6 +54,68 @@ export const semanticKnownArrayIteration = (
!ambientPathMayObserveAt(state, read, arrayIteratorNextPath, "contents") &&
value.items.every((item) => semanticArrayIndex(item.name) !== null);
const arrayIteratorReturnPaths = [
[...semanticArrayIteratorPrototypePath, "return"],
[...semanticArrayIteratorPrototypePath, "__proto__", "return"],
[...semanticArrayIteratorPrototypePath, "__proto__", "__proto__", "return"],
["global", "Iterator", "prototype", "return"],
["global", "Object", "prototype", "return"],
] as const;
/** References a possible native close hook can still obtain by advancing its iterator. */
export const semanticArrayPatternCloseSelection = (
pattern: t.ArrayPattern,
owner: t.Node | undefined,
array: Extract<JavaScriptSemanticValue, { status: "array" }>,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticPropertySelection | undefined => {
if (
!arrayIteratorReturnPaths.some((path) =>
ambientPathMayObserveAt(state, pattern, path, "contents"),
)
)
return undefined;
const declaration =
owner === undefined ? undefined : state.parentsByNode.get(owner);
const last = pattern.elements.at(-1);
const hasRest = t.isRestElement(last);
let consumed = 0;
if (
t.isVariableDeclarator(owner) &&
t.isVariableDeclaration(declaration) &&
(declaration.kind === "const" || declaration.kind === "let")
) {
for (const [index, element] of pattern.elements.entries()) {
// A lexical rest drains the iterator only after earlier pattern work
// reaches it. A preceding default or nested binding can throw first.
if (hasRest && element === last) return undefined;
const slot = array.items[index];
const ownSlot =
consumed === index &&
slot?.name === String(index) &&
slot.presence === "present";
if (
element !== null &&
!t.isIdentifier(element) &&
!(
hasRest &&
owner.id === pattern &&
ownSlot &&
t.isAssignmentPattern(element) &&
t.isIdentifier(element.left) &&
semanticValueDefinitelyDefined(slot.value)
)
)
break;
if (ownSlot) consumed += 1;
else if (!hasRest) break;
}
}
// The literal suffix can be empty while the iterator still has references
// from stored writes. Resolve those separately at the close site.
return { excludedKeys: [], startIndex: consumed };
};
/** Invocation spreads use the same native-iteration proof at their source read. */
export const semanticKnownArrayIterationAt = (
node: t.Node,
@@ -7,6 +7,20 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const iteratorCloseSource = `
const box = { label: "ready", items: [{ mode: "kept" }, { mode: "old" }] };
Object.getPrototypeOf([].values()).return = function () {
delete this.next().value.mode;
return {};
};
const { label: beforeClose, items: [first], items: { 0: { mode: consumed }, 1: { mode: afterClose } } } = box;
const stored = { items: [0], next: { mode: "borrowed" } };
const { insert = (stored.items[1] = stored.next), items: [assigned], next: { mode: storedAfterClose } } = stored;
const restSource = [undefined, { mode: "before" }];
try { const [head = null.value, ...rest] = restSource; } catch {}
const { 1: { mode: abruptAfterClose } } = restSource;
`;
cliTest(
"traces proved destructuring dependencies and leaves custom iteration uncertain",
async ({ cli }) => {
@@ -59,6 +73,7 @@ cliTest(
[selected] = after;
`,
);
await writeFile(join(root, "iterator-close.js"), iteratorCloseSource);
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
@@ -79,6 +94,11 @@ cliTest(
["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) {
const binding = graph.nodes.find(
(node) => node.kind === "binding" && node.label === name,
@@ -116,6 +136,9 @@ cliTest(
"projected",
"arrayObject",
"selected",
"beforeClose",
"consumed",
"afterClose",
]) {
const binding = graph.nodes.find(
({ kind, label }) => kind === "binding" && label === name,
@@ -144,7 +167,8 @@ cliTest(
]),
},
};
if (name === "selected") expect(trace.json).not.toMatchObject(relation);
if (name === "selected" || name === "afterClose")
expect(trace.json).not.toMatchObject(relation);
else expect(trace.json).toMatchObject(relation);
}
},