mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
fix(javascript): preserve uncertainty after nullish patterns
This commit is contained in:
1 parent
6b7b09f008
commit
8ae636b6ab
8 files changed
+182
-26
No files matched your search
@@ -244,6 +244,8 @@ remain opt-in through `include_ambiguous_dynamic_edges`.
|
||||
|
||||
Destructuring retains dependencies from the source slots proved at the time
|
||||
of the read. A later write does not replace an earlier proved dependency.
|
||||
After a nested pattern is proved to receive a nullish value and throw, later
|
||||
bindings in that pattern retain candidate paths with no proven initializer.
|
||||
A numeric key in an object pattern selects a named property directly.
|
||||
Nested array patterns can preserve dependencies for later bindings when
|
||||
element selection is known and iterator closing cannot invoke a return hook.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
|
||||
import { graphForJavaScript } from "../../../tests/fixtures/javascriptSemanticGraph.js";
|
||||
|
||||
const projection = (source: string) => {
|
||||
const ir = analyzeJavaScriptSemantics(source);
|
||||
const graph = graphForJavaScript(source, ir);
|
||||
return (name: string) => {
|
||||
const binding = graph.nodes.find(
|
||||
({ kind, label }) => kind === "binding" && label === name,
|
||||
);
|
||||
const relation = graph.relations.find(
|
||||
({ relation: kind, target_node_id }) =>
|
||||
kind === "destructures" && target_node_id === binding?.node_id,
|
||||
);
|
||||
return {
|
||||
resolution: relation?.resolution,
|
||||
value: ir.bindings.find((item) => item.name === name)?.value,
|
||||
sourcePath: graph.nodes.find(
|
||||
({ node_id }) => node_id === relation?.source_node_id,
|
||||
)?.properties.property_path,
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
it.each([
|
||||
["null", "{}"],
|
||||
["undefined", "{}"],
|
||||
["void 0", "{}"],
|
||||
["null", "[]"],
|
||||
["null", "{} = {}"],
|
||||
] as const)(
|
||||
"leaves bindings after %s matched against %s unproven",
|
||||
(value, pattern) => {
|
||||
const inspect = projection(`
|
||||
const model = { bad: ${value}, mode: "one" };
|
||||
const { mode: before, bad: ${pattern}, mode: selected } = model;
|
||||
`);
|
||||
expect(inspect("before")).toMatchObject({
|
||||
resolution: "resolved",
|
||||
sourcePath: ["mode"],
|
||||
});
|
||||
expect(inspect("selected")).toMatchObject({
|
||||
resolution: "candidate",
|
||||
value: { status: "unknown" },
|
||||
sourcePath: ["mode"],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["const model = { bad: 0, mode: 'one' };", "{}"],
|
||||
["const model = { bad: {}, mode: 'one' };", "{}"],
|
||||
["const model = { bad: [], mode: 'one' };", "[]"],
|
||||
["const model = { bad: undefined, mode: 'one' };", "{} = {}"],
|
||||
["const undefined = 0; const model = { bad: undefined, mode: 'one' };", "{}"],
|
||||
] as const)(
|
||||
"preserves the reachable sibling for %s against %s",
|
||||
(setup, pattern) => {
|
||||
const inspect = projection(`
|
||||
${setup}
|
||||
const { bad: ${pattern}, mode: selected } = model;
|
||||
`);
|
||||
expect(inspect("selected")).toMatchObject({
|
||||
resolution: "resolved",
|
||||
value: { status: "literal", value: "one" },
|
||||
sourcePath: ["mode"],
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -115,6 +115,7 @@ import {
|
||||
resolveSemanticModuleCallables,
|
||||
} from "./javascriptSemanticReturns.js";
|
||||
import { collectJavaScriptDerivedSemanticsSteps } from "./javascriptSemanticDerivedAnalysis.js";
|
||||
import { collectJavaScriptSemanticObjects } from "./javascriptSemanticObjects.js";
|
||||
import {
|
||||
evaluateSemanticProvenance,
|
||||
clearSemanticValueCaches,
|
||||
@@ -327,6 +328,12 @@ export function* analyzeParsedJavaScriptSemanticsSteps(
|
||||
yield;
|
||||
const references = yield* collectSemanticReferencesSteps(file.program, state);
|
||||
const parserPartial = recoveredJavaScriptSyntaxErrorCount(file.errors) > 0;
|
||||
const objectOperations = collectJavaScriptSemanticObjects(
|
||||
file.program,
|
||||
state,
|
||||
state.callables,
|
||||
);
|
||||
yield;
|
||||
const bindings = immutableSemanticBindings(state);
|
||||
yield;
|
||||
const callables = collectSemanticReturns(state, parserPartial);
|
||||
@@ -360,6 +367,7 @@ export function* analyzeParsedJavaScriptSemanticsSteps(
|
||||
callables,
|
||||
references,
|
||||
moduleLinks,
|
||||
objectOperations,
|
||||
...derived,
|
||||
coverage: derived.expressionFlowsTruncated
|
||||
? { ...coverage, status: "partial", omittedCount: null }
|
||||
@@ -2242,6 +2250,7 @@ const bindPattern = (input: BindPatternInput): void => {
|
||||
binding.referenceInitializers.push({
|
||||
node: initializer,
|
||||
projection,
|
||||
patternTarget: pattern,
|
||||
...(input.entryBody === undefined
|
||||
? {}
|
||||
: { entryBody: input.entryBody }),
|
||||
@@ -2429,6 +2438,9 @@ const addBinding = (input: AddBindingInput): void => {
|
||||
binding.initializers.push({
|
||||
node: initializer,
|
||||
projection,
|
||||
...(projection.length > 0 && t.isIdentifier(definitionNode)
|
||||
? { patternTarget: definitionNode }
|
||||
: {}),
|
||||
...(iterationSources === undefined ? {} : { iterationSources }),
|
||||
});
|
||||
if (directOrigin !== undefined)
|
||||
|
||||
@@ -11,7 +11,6 @@ import type {
|
||||
JavaScriptSemanticReference,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import { collectJavaScriptSemanticPromises } from "./javascriptSemanticPromises.js";
|
||||
import { collectJavaScriptSemanticObjects } from "./javascriptSemanticObjects.js";
|
||||
import { collectJavaScriptSemanticResources } from "./javascriptSemanticResources.js";
|
||||
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
|
||||
|
||||
@@ -44,7 +43,6 @@ type DerivedSemanticAnalysis = Pick<
|
||||
| "eventOperations"
|
||||
| "frontiers"
|
||||
| "functionFingerprints"
|
||||
| "objectOperations"
|
||||
| "promiseOperations"
|
||||
| "requestOperations"
|
||||
| "resourceOperations"
|
||||
@@ -96,12 +94,6 @@ export function* collectJavaScriptDerivedSemanticsSteps(
|
||||
callables,
|
||||
);
|
||||
yield;
|
||||
const objectOperations = collectJavaScriptSemanticObjects(
|
||||
program,
|
||||
state,
|
||||
callables,
|
||||
);
|
||||
yield;
|
||||
const assignmentFlows = yield* collectAssignmentFlowsSteps(
|
||||
program,
|
||||
state,
|
||||
@@ -140,7 +132,6 @@ export function* collectJavaScriptDerivedSemanticsSteps(
|
||||
...childProcesses,
|
||||
...dataEffects,
|
||||
resourceOperations,
|
||||
objectOperations,
|
||||
functionFingerprints,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
JavaScriptSemanticObjectOperation,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import { createSemanticCallableIdStack } from "./javascriptSemanticCallableStack.js";
|
||||
import { createSemanticExpressionShapeResolver } from "./javascriptSemanticExpressionShapes.js";
|
||||
import { semanticBindingMayRejectAssignmentAt } from "./javascriptSemanticMutationInitializers.js";
|
||||
import {
|
||||
semanticStaticPropertyKey,
|
||||
@@ -16,8 +17,10 @@ import {
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticInitializer,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js";
|
||||
import { clearSemanticValueCaches } from "./javascriptSemanticValues.js";
|
||||
import { range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import {
|
||||
createSemanticReadPresenceQuery,
|
||||
@@ -42,6 +45,8 @@ export const collectJavaScriptSemanticObjects = (
|
||||
output,
|
||||
writeTargets: new Map(),
|
||||
readPresence: createSemanticReadPresenceQuery(state),
|
||||
isNullish: createSemanticExpressionShapeResolver(state).isNullish,
|
||||
skippedBindings: new Set(),
|
||||
};
|
||||
traverseJavaScriptValueAst(program, state.erasedSyntaxNodes, {
|
||||
enter: (node, parent) => {
|
||||
@@ -84,6 +89,7 @@ export const collectJavaScriptSemanticObjects = (
|
||||
},
|
||||
exit: (node) => callableStack.exit(node),
|
||||
});
|
||||
discardSkippedInitializers(state, context.skippedBindings);
|
||||
return output;
|
||||
};
|
||||
|
||||
@@ -92,8 +98,40 @@ interface ObjectCollectionContext {
|
||||
readonly output: JavaScriptSemanticObjectOperation[];
|
||||
readonly writeTargets: Map<t.Node, t.Node>;
|
||||
readonly readPresence: ReturnType<typeof createSemanticReadPresenceQuery>;
|
||||
readonly isNullish: (node: t.Node) => boolean;
|
||||
readonly skippedBindings: Set<t.Identifier>;
|
||||
}
|
||||
|
||||
const discardSkippedInitializers = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
skipped: ReadonlySet<t.Identifier>,
|
||||
): void => {
|
||||
if (skipped.size === 0) return;
|
||||
const discard = (sources: JavaScriptSemanticInitializer[]): void => {
|
||||
let retained = 0;
|
||||
for (const source of sources) {
|
||||
const target = source.patternTarget;
|
||||
if (target === undefined || !skipped.has(target))
|
||||
sources[retained++] = source;
|
||||
}
|
||||
sources.length = retained;
|
||||
};
|
||||
for (const binding of state.bindingsById.values()) {
|
||||
discard(binding.initializers);
|
||||
discard(binding.referenceInitializers);
|
||||
}
|
||||
clearSemanticValueCaches(state);
|
||||
};
|
||||
|
||||
const isNestedReceiver = (occurrence: t.Node | null): boolean => {
|
||||
if (occurrence === null) return false;
|
||||
const { node } = unwrapJavaScriptExpression(occurrence);
|
||||
const target = t.isAssignmentPattern(node)
|
||||
? unwrapJavaScriptExpression(node.left).node
|
||||
: node;
|
||||
return t.isObjectPattern(target) || t.isArrayPattern(target);
|
||||
};
|
||||
|
||||
const collectMember = (
|
||||
node: t.MemberExpression | t.OptionalMemberExpression,
|
||||
parent: t.Node | null,
|
||||
@@ -150,21 +188,36 @@ const collectDestructuring = (
|
||||
root: t.Node,
|
||||
initializer: t.Node | null | undefined,
|
||||
ownerCallableId: string | null,
|
||||
{ state, output, readPresence }: ObjectCollectionContext,
|
||||
{
|
||||
state,
|
||||
output,
|
||||
readPresence,
|
||||
isNullish,
|
||||
skippedBindings,
|
||||
}: ObjectCollectionContext,
|
||||
): void => {
|
||||
const source = expressionObjectIdentity(initializer, state);
|
||||
const rootArray = t.isArrayPattern(root);
|
||||
const owner = state.parentsByNode.get(root);
|
||||
const assignment = t.isAssignmentExpression(owner);
|
||||
const hasNestedReceiver = rootArray
|
||||
? root.elements.some(isNestedReceiver)
|
||||
: t.isObjectPattern(root) &&
|
||||
root.properties.some(
|
||||
(property) =>
|
||||
t.isObjectProperty(property) && isNestedReceiver(property.value),
|
||||
);
|
||||
const sourcePresence =
|
||||
initializer != null && source.path !== null
|
||||
? readPresence(source.bindingId, initializer, {
|
||||
path: source.path,
|
||||
selection: rootArray ? "array-iterator" : "own-data",
|
||||
proveNestedCompletion: hasNestedReceiver,
|
||||
})
|
||||
: undefined;
|
||||
let ownSlot = sourcePresence?.read;
|
||||
let assignmentBlocked = false;
|
||||
let abrupt = false;
|
||||
// A null path keeps a target in evaluation order without emitting an
|
||||
// operation for a source slot we cannot identify.
|
||||
const pending: (
|
||||
@@ -205,16 +258,31 @@ const collectDestructuring = (
|
||||
if (next.pattern === undefined) continue;
|
||||
const occurrence = unwrapJavaScriptExpression(next.pattern).node;
|
||||
const hasDefault = t.isAssignmentPattern(occurrence);
|
||||
const pattern = hasDefault
|
||||
? unwrapJavaScriptExpression(occurrence.left).node
|
||||
: occurrence;
|
||||
const plainObjectPath = next.plainObjectPath === true && !hasDefault;
|
||||
// A default can replace undefined. It cannot replace a known null.
|
||||
if (
|
||||
selected !== undefined &&
|
||||
(t.isObjectPattern(pattern) || t.isArrayPattern(pattern)) &&
|
||||
(!hasDefault || t.isNullLiteral(selected)) &&
|
||||
isNullish(selected)
|
||||
) {
|
||||
abrupt = true;
|
||||
ownSlot = undefined;
|
||||
}
|
||||
if (abrupt && path === null) {
|
||||
for (const target of semanticWriteTargets(pattern))
|
||||
if (t.isIdentifier(target)) skippedBindings.add(target);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
hasDefault &&
|
||||
(!isKnownDefinedSource(selected) ||
|
||||
!isLexicalPatternDeclaration(owner, state))
|
||||
)
|
||||
ownSlot = undefined;
|
||||
const pattern = hasDefault
|
||||
? unwrapJavaScriptExpression(occurrence.left).node
|
||||
: occurrence;
|
||||
if (t.isRestElement(pattern)) {
|
||||
ownSlot = undefined;
|
||||
if (assignment) pending.push({ pattern: pattern.argument, path: null });
|
||||
@@ -239,15 +307,11 @@ const collectDestructuring = (
|
||||
? null
|
||||
: semanticStaticPropertyKey(prop.key, prop.computed);
|
||||
if (path === null || prop === undefined || name === null) {
|
||||
pending.push(
|
||||
assignment
|
||||
? {
|
||||
pattern: prop?.value ?? property,
|
||||
path: null,
|
||||
lookup: "unproven",
|
||||
}
|
||||
: null,
|
||||
);
|
||||
pending.push({
|
||||
pattern: prop?.value ?? property,
|
||||
path: null,
|
||||
lookup: "unproven",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
pending.push({
|
||||
@@ -288,8 +352,9 @@ const collectDestructuring = (
|
||||
}
|
||||
for (let index = pattern.elements.length - 1; index >= 0; index -= 1) {
|
||||
const element = pattern.elements[index];
|
||||
if (element === undefined || (!assignment && t.isRestElement(element)))
|
||||
pending.push(null);
|
||||
if (element === undefined) pending.push(null);
|
||||
else if (!assignment && t.isRestElement(element))
|
||||
pending.push({ pattern: element, path: null, lookup: "unproven" });
|
||||
else
|
||||
pending.push({
|
||||
pattern: element ?? undefined,
|
||||
@@ -308,6 +373,7 @@ const collectDestructuring = (
|
||||
pattern,
|
||||
pattern.name,
|
||||
);
|
||||
if (abrupt) skippedBindings.add(pattern);
|
||||
assignmentBlocked ||=
|
||||
assignment &&
|
||||
targetBinding !== undefined &&
|
||||
@@ -322,8 +388,9 @@ const collectDestructuring = (
|
||||
objectBindingId: source.bindingId,
|
||||
targetBindingId: targetBinding?.bindingId ?? null,
|
||||
propertyPath,
|
||||
partial: assignmentBlocked,
|
||||
partial: abrupt || assignmentBlocked,
|
||||
provenOwnSlot:
|
||||
!abrupt &&
|
||||
!assignmentBlocked &&
|
||||
(ownSlot !== undefined ||
|
||||
(plainObjectPath &&
|
||||
|
||||
@@ -41,6 +41,7 @@ type ReadOwnData = (
|
||||
interface DestructuringSource {
|
||||
readonly path: readonly string[];
|
||||
readonly selection: "array-iterator" | "own-data";
|
||||
readonly proveNestedCompletion?: boolean;
|
||||
}
|
||||
|
||||
interface ReadPresence {
|
||||
@@ -160,7 +161,8 @@ export const createSemanticReadPresenceQuery = (
|
||||
: { binding, value: initialValue };
|
||||
if (
|
||||
origin === undefined ||
|
||||
!hasRecordedReferenceEffects(origin.binding, state) ||
|
||||
(destructuring?.proveNestedCompletion !== true &&
|
||||
!hasRecordedReferenceEffects(origin.binding, state)) ||
|
||||
(origin.binding !== binding &&
|
||||
!semanticBindingPrecedesCapture(
|
||||
origin.binding,
|
||||
|
||||
@@ -32,6 +32,8 @@ import type {
|
||||
export interface JavaScriptSemanticInitializer {
|
||||
readonly node: t.Node;
|
||||
readonly projection: readonly (string | number | null)[];
|
||||
/** Binding occurrence that must be reached before this source is used. */
|
||||
readonly patternTarget?: t.Identifier;
|
||||
readonly entryBody?: t.BlockStatement;
|
||||
readonly iterationSources?: readonly {
|
||||
readonly node: t.Node;
|
||||
|
||||
@@ -43,6 +43,11 @@ const abruptObjectPatternSource = `
|
||||
box.sibling[0] = "later";
|
||||
`;
|
||||
|
||||
const nullishReceiverSource = `
|
||||
const record = { stop: null, value: "present" };
|
||||
const { value: reachedBeforeNullish, stop: {}, value: unreachedAfterNullish } = record;
|
||||
`;
|
||||
|
||||
const firstDefaultSource = `
|
||||
const defined = [0, ["one"]];
|
||||
const [used = (defined[1][0] = "dormant"), [inactiveDefaultElement]] = defined;
|
||||
@@ -100,6 +105,7 @@ const additionalFixtures = [
|
||||
["iterator-close.js", iteratorCloseSource],
|
||||
["array-prototype-alias.js", arrayPrototypeAliasSource],
|
||||
["abrupt-object-pattern.js", abruptObjectPatternSource],
|
||||
["nullish-receiver.js", nullishReceiverSource],
|
||||
["first-default.js", firstDefaultSource],
|
||||
["immutable-target.js", immutableTargetSource],
|
||||
["class-name-target.js", classNameTargetSource],
|
||||
@@ -135,6 +141,8 @@ const expectedDependencies = [
|
||||
["siblingObjectElement", ["sibling", "0"]],
|
||||
["projectedNumericInnerElement", ["pairs", "0", "0"]],
|
||||
["unreachedSibling", ["sibling", "0"], "candidate"],
|
||||
["reachedBeforeNullish", ["value"]],
|
||||
["unreachedAfterNullish", ["value"], "candidate"],
|
||||
["innerElement", ["0", "0"]],
|
||||
["siblingInnerElement", ["1", "0"]],
|
||||
["inactiveDefaultElement", ["1", "0"]],
|
||||
@@ -175,6 +183,8 @@ const tracedBindings = [
|
||||
"siblingObjectElement",
|
||||
"projectedNumericInnerElement",
|
||||
"unreachedSibling",
|
||||
"reachedBeforeNullish",
|
||||
"unreachedAfterNullish",
|
||||
"innerElement",
|
||||
"siblingInnerElement",
|
||||
"inactiveDefaultElement",
|
||||
|
||||
Reference in new issue
Block a user