Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix(javascript): bound cyclic mutation captures by their paths
  • Loading branch information
gensokyo-dev committed Oct 24, 2026
commit cdbe1d5d6dc5b421754b8d9c960b7cce39603b47
136 changes: 79 additions & 57 deletions src/domain/javascript/javascriptSemanticMemberMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -886,42 +886,6 @@ export function* collectSemanticMemberMutationsSteps(
]);
const lifetime = lifetimeKey(captureKey, current.path);
if (current.bindings.has(lifetime)) continue;
// A self alias such as `node = node[key]` revisits its capture with the
// same prefix added on every cycle, so exact paths never repeat. When
// that prefix can never be pruned, escaping it once covers every longer
// effect, including writes below shared children.
// Only a capture already on this alias chain can repeat a prefix.
const revisited = current.bindings.has(captureKey);
let repeatedPrefix: PropertyPath | undefined;
for (
let start = 1;
revisited && start <= current.path.length;
start++
) {
const suffix = current.path.slice(start);
if (!current.bindings.has(lifetimeKey(captureKey, suffix))) continue;
repeatedPrefix = current.path.slice(0, start);
break;
}
if (
repeatedPrefix !== undefined &&
observablePaths.repeatsUnpruned(binding.bindingId, repeatedPrefix)
) {
markValue(
current.node,
repeatedPrefix,
new Set(),
"escape",
mutation,
current.originAt,
current.ownerInitializer,
widenedGetterResult,
undefined,
undefined,
current,
);
continue;
}
// Union compatible copied-slot selections at each binding. Carrying every
// combination of exclusions through branch diamonds is exponential.
// Preserve paths that can change observed slots or Array prototype
Expand Down Expand Up @@ -981,6 +945,85 @@ export function* collectSemanticMemberMutationsSteps(
current.originAt,
parents,
);
// Keep an antichain of exact paths. Widening distinct member keys would
// also invalidate unrelated siblings that never reach this effect.
// This map is local to the file scan. Escaping the binding id keeps a
// field separator injective while avoiding a fresh JSON array encode.
const pathState = `${JSON.stringify(binding.bindingId)}\u0001${
effect
}\u0001${
// Short writes stop at owned literal slots, whereas longer writes
// reach shared children. Only equal-depth writes cover one another.
effect === "write" ? path.length : -1
}\u0001${mutation?.start ?? -1}\u0001${mutation?.end ?? -1}\u0001${
current.originAt?.start ?? -1
}\u0001${current.originAt?.end ?? -1}\u0001${
current.ownerInitializer?.start ?? -1
}\u0001${current.ownerInitializer?.end ?? -1}\u0001${widenedGetterResult}\u0001${current.definiteReceiver}\u0001${assignedSources?.[0]?.target?.start ?? -1}\u0001${current.memberReadAt?.start ?? -1}\u0001${current.memberReadAt?.end ?? -1}`;
let covering = coveringPaths.get(pathState);
if (covering === undefined) {
covering = new SemanticPropertyPathCoverage();
coveringPaths.set(pathState, covering);
}
// Captures belong to their projected slots. A shorter escape prefix
// covers a longer path only when the receiver captures along that
// prefix agree; deeper capture history cannot split the same fact.
const captures = semanticNormalizeCapturedSelections(
current.capturedSelections,
path.length,
);
let captureIndex = 0;
const captureContexts = captures?.length
? path.map((_, index) => {
while ((captures[captureIndex]?.depth ?? Infinity) < index + 1)
captureIndex++;
const capture = captures[captureIndex];
if (capture === undefined) return undefined;
return JSON.stringify([
capture.at.start,
capture.at.end,
capture.depth === index + 1 && capture.ownEnumerable === true,
]);
})
: undefined;
// An active normalized prefix owns its closure before nested traversals.
if (!covering.retain(path, captureContexts)) continue;
// A self alias such as `node = node[key]` revisits its capture with the
// same prefix added on every cycle, so exact paths never repeat. When
// that prefix can never be pruned, escaping it once covers every longer
// effect, including writes below shared children.
// Only a capture already on this alias chain can repeat a prefix.
const revisited = current.bindings.has(captureKey);
let repeatedPrefix: PropertyPath | undefined;
for (
let start = 1;
revisited && start <= current.path.length;
start++
) {
const suffix = current.path.slice(start);
if (!current.bindings.has(lifetimeKey(captureKey, suffix))) continue;
repeatedPrefix = current.path.slice(0, start);
break;
}
if (
repeatedPrefix !== undefined &&
observablePaths.repeatsUnpruned(binding.bindingId, repeatedPrefix)
) {
markValue(
current.node,
repeatedPrefix,
new Set(),
"escape",
mutation,
current.originAt,
current.ownerInitializer,
widenedGetterResult,
undefined,
undefined,
current,
);
continue;
}
// Invoking a setter exposes the receiver, including shared children.
// Preserve the explicit target write separately; deleting never invokes it.
if (
Expand Down Expand Up @@ -1014,27 +1057,6 @@ export function* collectSemanticMemberMutationsSteps(
current,
);
}
// Keep an antichain of exact paths. Widening distinct member keys would
// also invalidate unrelated siblings that never reach this effect.
// This map is local to the file scan. Escaping the binding id keeps a
// field separator injective while avoiding a fresh JSON array encode.
const pathState = `${JSON.stringify(binding.bindingId)}\u0001${
effect
}\u0001${
// Short writes stop at owned literal slots, whereas longer writes
// reach shared children. Only equal-depth writes cover one another.
effect === "write" ? path.length : -1
}\u0001${mutation?.start ?? -1}\u0001${mutation?.end ?? -1}\u0001${
current.originAt?.start ?? -1
}\u0001${current.originAt?.end ?? -1}\u0001${
current.ownerInitializer?.start ?? -1
}\u0001${current.ownerInitializer?.end ?? -1}\u0001${widenedGetterResult}\u0001${current.definiteReceiver}\u0001${assignedSources?.[0]?.target?.start ?? -1}\u0001${captureSelectionIdentity}`;
let covering = coveringPaths.get(pathState);
if (covering === undefined) {
covering = new SemanticPropertyPathCoverage();
coveringPaths.set(pathState, covering);
}
if (!covering.retain(path)) continue;
// A recorded write invalidates the binding to a non-primitive value, so
// only its first write can target a primitive. Re-evaluating it would
// replay every earlier write and make repeated writes superlinear.
Expand Down
58 changes: 58 additions & 0 deletions src/domain/javascript/javascriptSemanticPropertyPaths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { expect, it } from "vitest";

import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";

it("covers deeper capture history only below the same captured receiver", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(coverage.retain(["child"], ["first"])).toBe(true);
expect(coverage.retain(["child", "value"], ["first", "later"])).toBe(false);
expect(coverage.covers(["child", "value"], ["second", "later"])).toBe(false);
expect(coverage.retain(["child"], ["second"])).toBe(true);
});

it("retains distinct deep captures until their common receiver escapes", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(coverage.retain(["child", "value"], ["outer", "before"])).toBe(true);
expect(coverage.retain(["child", "value"], ["outer", "after"])).toBe(true);
expect(coverage.covers(["child", "value"], ["outer", "unknown"])).toBe(false);
expect(coverage.retain(["child"], ["outer"])).toBe(true);
expect(coverage.covers(["child", "value"], ["outer", "unknown"])).toBe(true);
expect(coverage.covers(["sibling"], ["outer"])).toBe(false);
});

it("keeps wildcard coverage within its capture context", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(coverage.retain([null, "value"], ["receiver", "slot"])).toBe(true);
expect(coverage.covers(["child", "value"], ["receiver", "slot"])).toBe(true);
expect(coverage.covers(["child", "value"], ["other", "slot"])).toBe(false);
expect(coverage.covers(["child", "value"], ["receiver", "other"])).toBe(
false,
);
});

it("preserves copied-slot exclusions and array prefixes with captures", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(
coverage.retain([{ excludedKeys: ["2"], startIndex: 1 }], ["copy"]),
).toBe(true);
expect(coverage.covers([1, "nested"], ["copy", "later"])).toBe(true);
expect(coverage.covers([0], ["copy"])).toBe(false);
expect(coverage.covers([2], ["copy"])).toBe(false);
expect(coverage.covers([1], ["other"])).toBe(false);
expect(coverage.retain([null], ["copy"])).toBe(true);
expect(coverage.covers([2], ["copy"])).toBe(true);
expect(coverage.covers([2], ["other"])).toBe(false);
});

it("preserves numeric key identity and absent capture identity", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(coverage.retain([1])).toBe(true);
expect(coverage.covers(["1", "value"], [undefined, "nested"])).toBe(true);
expect(coverage.covers([1], ["captured"])).toBe(false);
});

it("lets an escaped root cover every deeper capture", () => {
const coverage = new SemanticPropertyPathCoverage();
expect(coverage.retain([])).toBe(true);
expect(coverage.retain(["child"], ["captured"])).toBe(false);
});
31 changes: 21 additions & 10 deletions src/domain/javascript/javascriptSemanticPropertyPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ interface PropertyPathCoverageNode {
string,
{
readonly key: JavaScriptSemanticPropertyPath[number];
readonly context: string | undefined;
readonly node: PropertyPathCoverageNode;
}
>;
Expand All @@ -109,24 +110,28 @@ const coverageNode = (): PropertyPathCoverageNode => ({
export class SemanticPropertyPathCoverage {
readonly #root = coverageNode();

/** Retain a path only when no previously retained prefix covers it. */
retain(path: JavaScriptSemanticPropertyPath): boolean {
if (this.covers(path)) return false;
/** Match optional per-slot receiver identities along the covering prefix. */
retain(
path: JavaScriptSemanticPropertyPath,
contexts?: readonly (string | undefined)[],
): boolean {
if (this.covers(path, contexts)) return false;
let node = this.#root;
for (const key of path) {
for (const [offset, key] of path.entries()) {
const context = contexts?.[offset];
if (key !== null && typeof key !== "object") {
const name = String(key);
const name = JSON.stringify([String(key), context]);
let child = node.exact.get(name);
if (child === undefined) {
child = coverageNode();
node.exact.set(name, child);
}
node = child;
} else {
const identity = JSON.stringify(key);
const identity = JSON.stringify([key, context]);
let selected = node.selectors.get(identity);
if (selected === undefined) {
selected = { key, node: coverageNode() };
selected = { key, context, node: coverageNode() };
node.selectors.set(identity, selected);
}
node = selected.node;
Expand All @@ -139,21 +144,27 @@ export class SemanticPropertyPathCoverage {
}

/** Query retained prefixes without changing the coverage index. */
covers(path: JavaScriptSemanticPropertyPath): boolean {
covers(
path: JavaScriptSemanticPropertyPath,
contexts?: readonly (string | undefined)[],
): boolean {
const pending = [{ node: this.#root, offset: 0 }];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
if (current.node.terminal) return true;
const key = path[current.offset];
if (key === undefined) continue;
const context = contexts?.[current.offset];
if (key !== null && typeof key !== "object") {
const exact = current.node.exact.get(String(key));
const exact = current.node.exact.get(
JSON.stringify([String(key), context]),
);
if (exact !== undefined)
pending.push({ node: exact, offset: current.offset + 1 });
}
for (const selected of current.node.selectors.values()) {
if (keyCovers(selected.key, key))
if (selected.context === context && keyCovers(selected.key, key))
pending.push({ node: selected.node, offset: current.offset + 1 });
}
}
Expand Down
Loading