mirror of
https://github.com/morluto/rea.git
synced 2026-11-20 05:32:44 +00:00
fix(javascript): retain effects only from reachable first defaults (#12659)
This commit is contained in:
1 parent
2a6786168a
commit
fd2bc88d53
7 files changed
+192
-31
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
|
||||
import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js";
|
||||
|
||||
it.each([
|
||||
@@ -2513,3 +2514,70 @@ it("keeps a retained alias unknown after a possible close on a captured receiver
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"defined guard",
|
||||
'const xs=[0,["one"]];const [used=(xs[1][0]="dormant"),[selected]]=xs;xs[1][0]="later";',
|
||||
"resolved",
|
||||
"literal",
|
||||
],
|
||||
[
|
||||
"undefined guard",
|
||||
'const xs=[undefined,["one"]];const [used=(xs[1][0]="active"),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"unknown",
|
||||
],
|
||||
[
|
||||
"default can change the guard",
|
||||
'const xs=[0,["one"]];const [used=(xs[0]=undefined),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"literal",
|
||||
],
|
||||
[
|
||||
"default can change the guard and later slot",
|
||||
'const xs=[0,["one"]];const [used=(xs[0]=undefined,xs[1][0]="dormant"),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"unknown",
|
||||
],
|
||||
[
|
||||
"unknown guard",
|
||||
'const xs=[unknown(),["one"]];const [used=(xs[1][0]="maybe"),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"unknown",
|
||||
],
|
||||
[
|
||||
"earlier guard write",
|
||||
'const xs=[0,["one"]];xs[0]=undefined;const [used=(xs[1][0]="active"),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"unknown",
|
||||
],
|
||||
[
|
||||
"custom iterator",
|
||||
'const xs=[0,["one"]];xs[Symbol.iterator]=function*(){yield undefined;yield xs[1]};const [used=(xs[1][0]="active"),[selected]]=xs;xs[1][0]="later";',
|
||||
"candidate",
|
||||
"unknown",
|
||||
],
|
||||
] as const)(
|
||||
"applies a first default's possible effects with %s",
|
||||
(_name, source, resolution, status) => {
|
||||
const semantics = analyzeJavaScriptSemantics(source);
|
||||
const graph = graphForJavaScript(source, semantics);
|
||||
const selected = graph.nodes.find(
|
||||
({ kind, label }) => kind === "binding" && label === "selected",
|
||||
);
|
||||
expect(selected).toBeDefined();
|
||||
expect(
|
||||
graph.relations.find(
|
||||
(edge) =>
|
||||
edge.relation === "destructures" &&
|
||||
edge.target_node_id === selected?.node_id,
|
||||
),
|
||||
).toMatchObject({ resolution });
|
||||
expect(
|
||||
semantics.bindings.find(({ name }) => name === "selected")?.value,
|
||||
).toMatchObject(
|
||||
status === "literal" ? { status, value: "one" } : { status },
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
semanticReadMayObserveEffect,
|
||||
semanticReferenceRoot,
|
||||
type SemanticAmbientRootPaths,
|
||||
retainSemanticInactiveMemberWrites,
|
||||
} from "./javascriptSemanticEffectLog.js";
|
||||
import type { JavaScriptOpenReceiverFact } from "./javascriptSemanticReceiverFacts.js";
|
||||
import * as t from "@babel/types";
|
||||
@@ -88,6 +89,7 @@ import {
|
||||
semanticBundledRequireOriginCandidate,
|
||||
} from "./javascriptBundledRequireOrigin.js";
|
||||
import { collectSemanticMemberMutationsSteps } from "./javascriptSemanticMemberMutations.js";
|
||||
import { semanticInactiveFirstDefaultWritesSteps } from "./javascriptSemanticReadPresence.js";
|
||||
import {
|
||||
DEFAULT_JAVASCRIPT_MEMBER_MUTATION_ALLOWANCE,
|
||||
type JavaScriptMemberMutationAllowance,
|
||||
@@ -251,7 +253,7 @@ function* indexSemanticMemberMutationFactsSteps(
|
||||
): Generator<void, void> {
|
||||
if (state.memberMutationFactsComplete) return;
|
||||
yield* indexSemanticAmbientWritesSteps(state);
|
||||
yield* collectSemanticMemberMutationsSteps(
|
||||
const candidateDefaults = yield* collectSemanticMemberMutationsSteps(
|
||||
state.program,
|
||||
state,
|
||||
(site, reference, path) =>
|
||||
@@ -264,6 +266,15 @@ function* indexSemanticMemberMutationFactsSteps(
|
||||
),
|
||||
);
|
||||
state.memberMutationFactsComplete = true;
|
||||
const inactiveWrites = yield* semanticInactiveFirstDefaultWritesSteps(
|
||||
state,
|
||||
candidateDefaults,
|
||||
);
|
||||
// Every guard is proved before any inactive write is excluded.
|
||||
if (inactiveWrites.length > 0) {
|
||||
retainSemanticInactiveMemberWrites(state, inactiveWrites);
|
||||
clearSemanticValueCaches(state);
|
||||
}
|
||||
invalidateSemanticRequireDelegateWrites(state);
|
||||
}
|
||||
|
||||
|
||||
@@ -1030,15 +1030,33 @@ const opaqueCodeMayReachBindingReference = (
|
||||
): boolean =>
|
||||
semanticBindingMayHaveOpaqueEffect(binding, state, capturePoint, "reference");
|
||||
|
||||
const inactiveMemberWriteNodes = new WeakMap<
|
||||
JavaScriptSemanticAnalysisState,
|
||||
WeakSet<t.Node>
|
||||
>();
|
||||
|
||||
export const retainSemanticInactiveMemberWrites = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
nodes: readonly t.Node[],
|
||||
): void => {
|
||||
inactiveMemberWriteNodes.set(state, new WeakSet(nodes));
|
||||
};
|
||||
|
||||
const observesCapturedWrite = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
capture: t.Node | undefined,
|
||||
node: t.Node | undefined,
|
||||
parents: JavaScriptSemanticAnalysisState["parentsByNode"],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): boolean =>
|
||||
capture === undefined ||
|
||||
node === undefined ||
|
||||
!semanticBindingEffectFollowsCapture(binding, capture, node, parents);
|
||||
(inactiveMemberWriteNodes.get(state)?.has(node) !== true &&
|
||||
(capture === undefined ||
|
||||
!semanticBindingEffectFollowsCapture(
|
||||
binding,
|
||||
capture,
|
||||
node,
|
||||
state.parentsByNode,
|
||||
)));
|
||||
|
||||
const observesCapturedEscape = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
@@ -1064,12 +1082,7 @@ export const capturedBindingPathMayHaveChanged = (
|
||||
path,
|
||||
(effect) =>
|
||||
semanticEffectPathMatches(effect.path, path) &&
|
||||
observesCapturedWrite(
|
||||
binding,
|
||||
capture,
|
||||
effect.node,
|
||||
state.parentsByNode,
|
||||
),
|
||||
observesCapturedWrite(binding, capture, effect.node, state),
|
||||
) ||
|
||||
semanticSomeEffectPathCandidate(
|
||||
binding.escapedPaths,
|
||||
@@ -1134,7 +1147,7 @@ export const applySemanticBindingReferenceEffects = (
|
||||
value,
|
||||
binding.memberWrites
|
||||
.filter(({ node }) =>
|
||||
observesCapturedWrite(binding, capturePoint, node, state.parentsByNode),
|
||||
observesCapturedWrite(binding, capturePoint, node, state),
|
||||
)
|
||||
.map(({ path }) => path),
|
||||
);
|
||||
|
||||
@@ -517,7 +517,11 @@ export function* collectSemanticMemberMutationsSteps(
|
||||
program: t.Program,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
mayObserve: JavaScriptBindingIndex["mayObserve"],
|
||||
): Generator<void, void> {
|
||||
): Generator<void, ReadonlyMap<t.VariableDeclarator, t.AssignmentPattern>> {
|
||||
const firstArrayDefaults = new Map<
|
||||
t.VariableDeclarator,
|
||||
t.AssignmentPattern
|
||||
>();
|
||||
const deferredMapReceivers = new Set<
|
||||
t.CallExpression | t.OptionalCallExpression
|
||||
>();
|
||||
@@ -1888,6 +1892,14 @@ export function* collectSemanticMemberMutationsSteps(
|
||||
for (const target of semanticWriteTargets(execution.target))
|
||||
writeOnlyMembers.add(target);
|
||||
for (const source of semanticIterationSources(node, parent)) {
|
||||
const first = source.arrayPattern?.elements[0];
|
||||
if (
|
||||
source.kind === "iteration" &&
|
||||
t.isVariableDeclarator(node) &&
|
||||
node.id === source.arrayPattern &&
|
||||
t.isAssignmentPattern(first)
|
||||
)
|
||||
firstArrayDefaults.set(node, first);
|
||||
// Local stores retain their sources on member writes. Only the ambient
|
||||
// identity owner can establish that storing itself exposes a reference.
|
||||
if (
|
||||
@@ -2287,6 +2299,7 @@ export function* collectSemanticMemberMutationsSteps(
|
||||
// Gathering effects can evaluate a primitive projection before its object
|
||||
// escapes. Final values must use the completed mutation state.
|
||||
clearSemanticValueCaches(state);
|
||||
return firstArrayDefaults;
|
||||
}
|
||||
|
||||
interface ReferencedValue extends JavaScriptSemanticObjectReference {
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
semanticWriteSiteReadsFirst,
|
||||
semanticWriteSiteTarget,
|
||||
semanticWriteTargets,
|
||||
staticJavaScriptTruthiness,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
import {
|
||||
@@ -19,7 +18,10 @@ import {
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js";
|
||||
import { range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { createSemanticReadPresenceQuery } from "./javascriptSemanticReadPresence.js";
|
||||
import {
|
||||
createSemanticReadPresenceQuery,
|
||||
isKnownDefinedSource,
|
||||
} from "./javascriptSemanticReadPresence.js";
|
||||
import {
|
||||
isLexicalPatternDeclaration,
|
||||
semanticArrayPatternCanResumeAfterClose,
|
||||
@@ -143,13 +145,6 @@ const collectMember = (
|
||||
);
|
||||
};
|
||||
|
||||
/** A proved own slot yields its initializer's result, even if that result is null. */
|
||||
const isKnownDefinedSource = (node: t.Node | undefined): boolean =>
|
||||
node !== undefined &&
|
||||
(t.isLiteral(node) ||
|
||||
t.isObjectMethod(node) ||
|
||||
staticJavaScriptTruthiness(node) === true);
|
||||
|
||||
const collectDestructuring = (
|
||||
root: t.Node,
|
||||
initializer: t.Node | null | undefined,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as t from "@babel/types";
|
||||
import {
|
||||
semanticMemberChain,
|
||||
staticJavaScriptTruthiness,
|
||||
staticObjectPropertyReader,
|
||||
unwrapJavaScriptExpression,
|
||||
} from "./javascriptAstValues.js";
|
||||
@@ -11,7 +13,10 @@ import {
|
||||
} from "./javascriptSemanticEffectLog.js";
|
||||
import { semanticBindingPrecedesCapture } from "./javascriptSemanticMutationInitializers.js";
|
||||
import { semanticArrayIndex } from "./javascriptSemanticPropertyPaths.js";
|
||||
import { semanticKnownArrayIteration } from "./javascriptSemanticReferenceSources.js";
|
||||
import {
|
||||
isLexicalPatternDeclaration,
|
||||
semanticKnownArrayIteration,
|
||||
} from "./javascriptSemanticReferenceSources.js";
|
||||
import { semanticArrayLiteralSlots } from "./javascriptSemanticArrayLayout.js";
|
||||
import { semanticSlotAtPath } from "./javascriptSemanticSlots.js";
|
||||
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
|
||||
@@ -48,6 +53,13 @@ interface ReadPresence {
|
||||
) => ReadOwnData | undefined;
|
||||
}
|
||||
|
||||
/** A proved own slot yields its initializer's result, even if that result is null. */
|
||||
export const isKnownDefinedSource = (node: t.Node | undefined): boolean =>
|
||||
node !== undefined &&
|
||||
(t.isLiteral(node) ||
|
||||
t.isObjectMethod(node) ||
|
||||
staticJavaScriptTruthiness(node) === true);
|
||||
|
||||
/** Prove a direct data slot in its source at the time of the read. */
|
||||
export const createSemanticReadPresenceQuery = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
@@ -258,3 +270,41 @@ export const createSemanticReadPresenceQuery = (
|
||||
return { read, readNestedArray: arraySlots };
|
||||
};
|
||||
};
|
||||
|
||||
/** Check first default guards against the completed conservative effect inventory. */
|
||||
export function* semanticInactiveFirstDefaultWritesSteps(
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
defaults: ReadonlyMap<t.VariableDeclarator, t.AssignmentPattern>,
|
||||
): Generator<void, t.AssignmentExpression[]> {
|
||||
if (defaults.size === 0) return [];
|
||||
const inactive: t.AssignmentExpression[] = [];
|
||||
const readPresence = createSemanticReadPresenceQuery(state);
|
||||
let index = 0;
|
||||
for (const [declarator, pattern] of defaults) {
|
||||
if (index++ % 64 === 0) yield;
|
||||
const capture = declarator.init;
|
||||
const effect = unwrapJavaScriptExpression(pattern.right).node;
|
||||
if (
|
||||
!isLexicalPatternDeclaration(declarator, state) ||
|
||||
!t.isIdentifier(capture) ||
|
||||
!t.isIdentifier(pattern.left) ||
|
||||
!t.isAssignmentExpression(effect, { operator: "=" }) ||
|
||||
!t.isMemberExpression(effect.left)
|
||||
)
|
||||
continue;
|
||||
const receiver = semanticMemberChain(effect.left)?.root;
|
||||
const binding = resolveSemanticBindingState(state, capture, capture.name);
|
||||
if (
|
||||
binding === undefined ||
|
||||
!t.isIdentifier(receiver) ||
|
||||
resolveSemanticBindingState(state, receiver, receiver.name) !== binding
|
||||
)
|
||||
continue;
|
||||
const guard = readPresence(binding.bindingId, capture, {
|
||||
path: [],
|
||||
selection: "array-iterator",
|
||||
})?.read(["0"]);
|
||||
if (isKnownDefinedSource(guard)) inactive.push(effect);
|
||||
}
|
||||
return inactive;
|
||||
}
|
||||
@@ -43,6 +43,15 @@ const abruptObjectPatternSource = `
|
||||
box.sibling[0] = "later";
|
||||
`;
|
||||
|
||||
const firstDefaultSource = `
|
||||
const defined = [0, ["one"]];
|
||||
const [used = (defined[1][0] = "dormant"), [inactiveDefaultElement]] = defined;
|
||||
defined[1][0] = "later";
|
||||
const missing = [undefined, ["one"]];
|
||||
const [other = (missing[1][0] = "active"), [activeDefaultElement]] = missing;
|
||||
missing[1][0] = "later";
|
||||
`;
|
||||
|
||||
const expectedDependencies = [
|
||||
["declared", ["a"]],
|
||||
["a", ["a"]],
|
||||
@@ -60,6 +69,8 @@ const expectedDependencies = [
|
||||
["unreachedSibling", ["sibling", "0"], "candidate"],
|
||||
["innerElement", ["0", "0"]],
|
||||
["siblingInnerElement", ["1", "0"]],
|
||||
["inactiveDefaultElement", ["1", "0"]],
|
||||
["activeDefaultElement", ["1", "0"], "candidate"],
|
||||
["spreadElement", ["1"]],
|
||||
["aliasedPrototypeElement", ["0", "0"], "candidate"],
|
||||
["selected", ["0"], "candidate"],
|
||||
@@ -86,6 +97,8 @@ const tracedBindings = [
|
||||
"unreachedSibling",
|
||||
"innerElement",
|
||||
"siblingInnerElement",
|
||||
"inactiveDefaultElement",
|
||||
"activeDefaultElement",
|
||||
"spreadElement",
|
||||
"aliasedPrototypeElement",
|
||||
"selected",
|
||||
@@ -160,15 +173,13 @@ cliTest(
|
||||
[selected] = after;
|
||||
`,
|
||||
);
|
||||
await writeFile(join(root, "iterator-close.js"), iteratorCloseSource);
|
||||
await writeFile(
|
||||
join(root, "array-prototype-alias.js"),
|
||||
arrayPrototypeAliasSource,
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "abrupt-object-pattern.js"),
|
||||
abruptObjectPatternSource,
|
||||
);
|
||||
for (const [path, source] of [
|
||||
["iterator-close.js", iteratorCloseSource],
|
||||
["array-prototype-alias.js", arrayPrototypeAliasSource],
|
||||
["abrupt-object-pattern.js", abruptObjectPatternSource],
|
||||
["first-default.js", firstDefaultSource],
|
||||
] as const)
|
||||
await writeFile(join(root, path), source);
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user