mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 11:43:20 +00:00
* refactor(javascript): ask one owner whether opaque code changed an intrinsic global read Six intrinsic global readers combined semanticOpaqueGlobalMayHaveChanged and semanticOpaqueNameMayHaveChanged themselves, each choosing which effect kinds applied and where to time them. isIntrinsicGlobalReference and opaqueCodeMayChangeGlobalRead in javascriptSemanticGlobalReference.ts now own both proofs: a sloppy direct eval visible from the reference may introduce its root name, and global code that may run before the observation site may replace a writable global. The owner also knows that undefined, NaN and Infinity are non-writable, so global code cannot replace them. Map lookups and XMLHttpRequest open calls pass the call as the observation site, keeping their call-time timing. An architecture guard forbids the two helpers outside their owners. Slice 1 of docs/adr/javascript/pushed-effect-invalidation.md (#11188). * refactor(javascript): ask one owner whether opaque code rebound a binding (#11254) Ten binding readers combined semanticBindingCanBeRebound, semanticBindingMayHaveOpaqueEffect and semanticOpaqueBindingReadMayHaveChanged themselves; three repeated the same rebindability-and-effect pairing. opaqueCodeMayRebindBinding(binding, state, read?) and opaqueCodeMayReachBindingReference(binding, state, capturePoint) in javascriptSemanticOpaqueEffects.ts now own the rebinding, read-timing, capture and introduced-name proofs. semanticBindingMayHaveOpaqueEffect is private to the owner and semanticOpaqueBindingReadMayHaveChanged is removed, so a reader cannot pick effect kinds again. Slice 2 of docs/adr/javascript/pushed-effect-invalidation.md (#11188). * refactor(javascript): ask one owner whether an intrinsic instance method changed (#11266) * refactor(javascript): ask one owner whether an intrinsic instance method changed Map lookups and XMLHttpRequest.open each walked receiver aliases and combined member-effect checks for the method, the instance prototype link and the intrinsic prototypes. isIntrinsicInstanceMethodCall now owns that walk; Map lookups also gain the prototype-link check XHR already made. The member-effect view asks semanticOpaqueReferenceEffects for opaque sites instead of combining the rebinding and reach helpers, which become private. Refs docs/adr/javascript/pushed-effect-invalidation.md (slice 3). * refactor(javascript): keep global opaque-effect checks private to their owner opaqueCodeMayChangeGlobalRead moves into javascriptSemanticOpaqueEffects.ts, so semanticOpaqueGlobalMayHaveChanged and semanticOpaqueNameMayHaveChanged are no longer exported and the slice 1 text guard is replaced by the compiler. * refactor(javascript): make the effect log the one reader of recorded opaque sites (#11282) * refactor(javascript): make the effect log the one reader of recorded opaque sites Rename javascriptSemanticOpaqueEffects.ts to javascriptSemanticEffectLog.ts (ADR decision 1) and move the reference-effects view (visitSemanticReferenceEffectsAtSite, the effect report, the member-path query and its completeness gate) out of javascriptSemanticAnalysis.ts into it. Recorded opaque sites move behind javascriptSemanticEffectRecord.ts accessors (direct-eval site, recorded direct eval, global-code sites), which the timing producer in javascriptSemanticMutationInitializers.ts and the call frontier in javascriptSemanticCalls.ts now ask instead of reading state.opaqueEffects. The member-mutation completeness WeakSet duplicated state.memberMutationFactsComplete and is removed. An architecture guard keeps `.opaqueEffects` reads inside the log and its record module. * refactor(javascript): keep the opaque reference-effect generator private to the effect log * refactor(javascript): drop analysis-hub imports that only the moved effect queries used * refactor(javascript): ask the effect log for a binding reference's recorded effects (#11295) The value engine applied member writes, escapes and direct-eval reach to a binding's reference itself, with its own capture proofs. That application moves into javascriptSemanticEffectLog.ts as applySemanticBindingReferenceEffects, and opaqueCodeMayReachBindingReference becomes private to the log. A counted guard (javascript-effect-index-read) records every remaining read of the per-kind effect indexes outside the log; it can only shrink, so new reader-side checks fail the guard. * refactor(javascript): ask the effect log whether an ambient path may have changed (#11308) * refactor(javascript): ask the effect log mayObserve for member-path reads (#11313) * refactor(javascript): name the member-path effect query mayObserve * refactor(javascript): ask the effect log whether an ambient path effect may precede a read * refactor(javascript): ask the effect log about require and process rebinding (#11318) refactor(javascript): ask the effect log about require and process rebinding and effect generations * refactor(javascript): build the ambient-write module interop in one owner (#11323) * refactor(javascript): build the ambient-write module interop in one owner and ask the effect log in CommonJS receivers * refactor(javascript): ask the effect log whether binding assignments precede a read (#11329) refactor(javascript): ask the effect log whether binding assignments or prototype writes precede a read * fix(javascript): count prototype escapes before resolving a URL object request target (#11368) fix(javascript): count URL and Object prototype escapes before resolving a URL object target
649 lines
23 KiB
TypeScript
649 lines
23 KiB
TypeScript
import * as t from "@babel/types";
|
|
|
|
import {
|
|
semanticStaticPropertyKey,
|
|
semanticFinalObjectProperty,
|
|
semanticWriteTargets,
|
|
unwrapJavaScriptExpression,
|
|
} from "./javascriptAstValues.js";
|
|
import {
|
|
resolveSemanticBindingState,
|
|
semanticResolutionBlocked,
|
|
type JavaScriptSemanticAnalysisState,
|
|
} from "./javascriptSemanticState.js";
|
|
import { isUnmodifiedGlobalReference } from "./javascriptSemanticGlobalReference.js";
|
|
import { traverseJavaScriptValueAstSteps } from "./javascriptSemanticTraversal.js";
|
|
import { semanticModuleInteropWithAmbientWrites } from "./javascriptModuleInterop.js";
|
|
import {
|
|
ambientPathWriteSites,
|
|
bindingMemberEffectMayPrecede,
|
|
} from "./javascriptSemanticEffectLog.js";
|
|
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
|
|
import type { JavaScriptSemanticPropertyPath } from "./javascriptSemanticPropertyPaths.js";
|
|
import { semanticProjectedSourcesAtRead } from "./javascriptSemanticProjectedSources.js";
|
|
import {
|
|
isUnshadowedGlobal,
|
|
semanticBindingHasPriorValueWrite,
|
|
} from "./javascriptSemanticMutationInitializers.js";
|
|
import { javaScriptRuntimeContext } from "./javascriptSourceParser.js";
|
|
|
|
/** Share the intrinsic owner's positional and capture proofs across CJS consumers. */
|
|
const commonJsExportInvocation = (
|
|
node: t.CallExpression,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
) => semanticModuleInteropWithAmbientWrites(state).intrinsicInvocation(node);
|
|
|
|
type ReceiverStatus = "connected" | "detached" | "uncertain";
|
|
export interface CommonJsExportReceiverEffect {
|
|
readonly receiver: ReceiverStatus;
|
|
readonly fields?: ReadonlyMap<string, ReceiverStatus>;
|
|
}
|
|
|
|
/** Publication is selected per field; one assign site can publish many fields. */
|
|
export const commonJsExportApplicability = (
|
|
effect: CommonJsExportReceiverEffect | undefined,
|
|
name: string,
|
|
): ReceiverStatus =>
|
|
effect?.receiver === "detached"
|
|
? "detached"
|
|
: (effect?.fields?.get(name) ?? effect?.receiver ?? "connected");
|
|
|
|
/** A CommonJS export assignment or `Object.defineProperty` export call. */
|
|
export type CommonJsExportSite = t.AssignmentExpression | t.CallExpression;
|
|
|
|
interface CopiedOwnFields {
|
|
readonly definite: ReadonlySet<string>;
|
|
readonly complete: boolean;
|
|
}
|
|
|
|
/** Definite own fields survive aliases, but not a possible prior shape change. */
|
|
const copiedOwnFields = (
|
|
source: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): CopiedOwnFields => {
|
|
const unknown = { definite: new Set<string>(), complete: false };
|
|
const pending = [source];
|
|
const seen = new Set<t.Node>();
|
|
let common: Set<string> | undefined;
|
|
let complete = true;
|
|
while (pending.length > 0) {
|
|
const node = unwrapJavaScriptExpression(pending.pop()!).node;
|
|
if (seen.has(node)) continue;
|
|
if (seen.size >= state.precision.alias_selections) {
|
|
state.valueResourceLimits.add("alias-selections");
|
|
return unknown;
|
|
}
|
|
seen.add(node);
|
|
if (t.isIdentifier(node)) {
|
|
const binding = resolveSemanticBindingState(state, node, node.name);
|
|
if (binding === undefined) return unknown;
|
|
if (bindingMemberEffectMayPrecede(state, binding, source)) return unknown;
|
|
const selected = semanticProjectedSourcesAtRead(
|
|
binding,
|
|
node,
|
|
[],
|
|
state,
|
|
false,
|
|
source,
|
|
);
|
|
if (
|
|
selected === undefined ||
|
|
selected.length === 0 ||
|
|
selected.some((value) => value.path.length !== 0)
|
|
)
|
|
return unknown;
|
|
if (
|
|
seen.size + pending.length + selected.length >
|
|
state.precision.alias_selections
|
|
) {
|
|
state.valueResourceLimits.add("alias-selections");
|
|
return unknown;
|
|
}
|
|
for (const value of selected) pending.push(value.node);
|
|
continue;
|
|
}
|
|
// A getter can remove a later own slot while Object.assign is copying.
|
|
// Its initial presence cannot prove an earlier source was overwritten.
|
|
if (
|
|
t.isObjectExpression(node) &&
|
|
node.properties.some(
|
|
(property) => t.isObjectMethod(property) && property.kind !== "method",
|
|
)
|
|
)
|
|
return unknown;
|
|
const selected = evaluateSemanticExpression(node, state, source);
|
|
const fields =
|
|
selected.status === "object"
|
|
? selected.properties
|
|
: selected.status === "array"
|
|
? selected.items
|
|
: [];
|
|
const own = new Set(
|
|
fields
|
|
.filter((field) => field.presence === "present")
|
|
.map((field) => field.name),
|
|
);
|
|
const exact =
|
|
selected.status === "object"
|
|
? !selected.unknownProperties
|
|
: selected.status === "array"
|
|
? !selected.unknownItems
|
|
: selected.status === "literal" && selected.value === null;
|
|
complete &&=
|
|
exact &&
|
|
(common === undefined ||
|
|
(common.size === own.size && [...common].every((key) => own.has(key))));
|
|
common =
|
|
common === undefined
|
|
? own
|
|
: new Set([...common].filter((key) => own.has(key)));
|
|
}
|
|
return { definite: common ?? new Set(), complete };
|
|
};
|
|
|
|
/** A possible wrapper export remains a candidate when its host is unknown. */
|
|
const isCommonJsExportReference = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
name: string,
|
|
): boolean => {
|
|
const context = javaScriptRuntimeContext(state.program);
|
|
if (context === "module") return false;
|
|
if (isUnshadowedGlobal(node, state, name)) return true;
|
|
if (
|
|
context !== "unknown" ||
|
|
!t.isIdentifier(node, { name }) ||
|
|
semanticResolutionBlocked(state, node, name)
|
|
)
|
|
return false;
|
|
const binding = resolveSemanticBindingState(state, node, name);
|
|
return (
|
|
binding !== undefined &&
|
|
state.scopesById.get(binding.scopeId)?.kind === "program" &&
|
|
binding.declarationKinds.size === 1 &&
|
|
binding.declarationKinds.has("var") &&
|
|
!semanticBindingHasPriorValueWrite(node, binding, state)
|
|
);
|
|
};
|
|
|
|
const isCommonJsModuleExports = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): boolean =>
|
|
(t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) &&
|
|
isCommonJsExportReference(node.object, state, "module") &&
|
|
semanticStaticPropertyKey(node.property, node.computed) === "exports";
|
|
|
|
/** One syntax owner for CJS export names and their receiver identities. */
|
|
export const commonJsExportName = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): string | undefined => {
|
|
if (!t.isMemberExpression(node) && !t.isOptionalMemberExpression(node))
|
|
return undefined;
|
|
const key = semanticStaticPropertyKey(node.property, node.computed);
|
|
if (
|
|
isCommonJsExportReference(node.object, state, "exports") ||
|
|
isCommonJsModuleExports(node.object, state)
|
|
)
|
|
return key === null ? "*" : key;
|
|
return isCommonJsModuleExports(node, state) ? "default" : undefined;
|
|
};
|
|
|
|
/**
|
|
* `Object.defineProperty(exports, key, descriptor)`, as tsc and Babel emit
|
|
* for CommonJS re-exports, defines the same export as an assignment.
|
|
*/
|
|
export const commonJsDefinedExport = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
):
|
|
| {
|
|
readonly exportedName: string;
|
|
readonly receiver: t.Node;
|
|
readonly descriptor: t.Node;
|
|
}
|
|
| undefined => {
|
|
if (!t.isCallExpression(node)) return undefined;
|
|
const [target, key, descriptor] = node.arguments;
|
|
if (
|
|
target === undefined ||
|
|
key === undefined ||
|
|
descriptor === undefined ||
|
|
t.isSpreadElement(target) ||
|
|
t.isSpreadElement(key) ||
|
|
t.isSpreadElement(descriptor) ||
|
|
t.isArgumentPlaceholder(target) ||
|
|
t.isArgumentPlaceholder(key) ||
|
|
t.isArgumentPlaceholder(descriptor)
|
|
)
|
|
return undefined;
|
|
const receiver = unwrapJavaScriptExpression(target).node;
|
|
if (
|
|
(!isCommonJsExportReference(receiver, state, "exports") &&
|
|
!isCommonJsModuleExports(receiver, state)) ||
|
|
!isUnmodifiedGlobalReference(node.callee, state, [
|
|
"Object",
|
|
"defineProperty",
|
|
])
|
|
)
|
|
return undefined;
|
|
return {
|
|
exportedName: semanticStaticPropertyKey(key, true) ?? "*",
|
|
receiver,
|
|
descriptor,
|
|
};
|
|
};
|
|
|
|
/** Native Object.assign publishes source values only through a CJS receiver. */
|
|
const commonJsAssignedExports = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
):
|
|
| {
|
|
readonly receiver: t.Node;
|
|
readonly sources: readonly {
|
|
readonly value: t.Node | null;
|
|
readonly iterationSource?: t.Node;
|
|
}[];
|
|
}
|
|
| undefined => {
|
|
if (!t.isCallExpression(node)) return undefined;
|
|
const invocation = commonJsExportInvocation(node, state);
|
|
if (
|
|
invocation?.kind !== "known" ||
|
|
invocation.path.length !== 3 ||
|
|
invocation.path[0] !== "intrinsic" ||
|
|
invocation.path[1] !== "Object" ||
|
|
invocation.path[2] !== "assign"
|
|
)
|
|
return undefined;
|
|
const [target, ...sources] = invocation.arguments ?? [];
|
|
if (!t.isExpression(target)) return undefined;
|
|
const receiver = unwrapJavaScriptExpression(target).node;
|
|
if (
|
|
!isCommonJsExportReference(receiver, state, "exports") &&
|
|
!isCommonJsModuleExports(receiver, state)
|
|
)
|
|
return undefined;
|
|
return {
|
|
receiver,
|
|
sources: sources.map((source) => ({
|
|
// The invocation owner expands only proven argument positions. An
|
|
// unresolved spread is a sequence of sources, not one array source.
|
|
value: t.isExpression(source) ? source : null,
|
|
...(t.isSpreadElement(source)
|
|
? { iterationSource: source.argument }
|
|
: {}),
|
|
})),
|
|
};
|
|
};
|
|
|
|
interface CommonJsRuntimeExportValue {
|
|
readonly loaderAuthority?: "candidate";
|
|
readonly exportedName: string;
|
|
readonly value: t.Node | null;
|
|
/** Retained input to unresolved iteration; never a selected yielded value. */
|
|
readonly iterationSource?: t.Node;
|
|
/** Own enumerable fields copied at this source, after later-source overwrites. */
|
|
readonly projection?: JavaScriptSemanticPropertyPath;
|
|
readonly ownEnumerable?: true;
|
|
}
|
|
|
|
/** Runtime values published by the CommonJS syntax owner, before receiver applicability. */
|
|
const commonJsExportValues = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): readonly CommonJsRuntimeExportValue[] => {
|
|
if (t.isAssignmentExpression(node)) {
|
|
const exportedName = commonJsExportName(node.left, state);
|
|
return exportedName === undefined
|
|
? []
|
|
: [{ exportedName, value: node.operator === "=" ? node.right : null }];
|
|
}
|
|
const assigned = commonJsAssignedExports(node, state);
|
|
if (assigned !== undefined) {
|
|
const exported: CommonJsRuntimeExportValue[] = [];
|
|
const overwritten = new Set<string>();
|
|
for (let index = assigned.sources.length - 1; index >= 0; index--) {
|
|
const { value, iterationSource } = assigned.sources[index]!;
|
|
if (value === null) {
|
|
exported.push({
|
|
exportedName: "*",
|
|
value: null,
|
|
...(iterationSource === undefined ? {} : { iterationSource }),
|
|
});
|
|
continue;
|
|
}
|
|
const fields = copiedOwnFields(value, state);
|
|
if (fields.complete) {
|
|
for (const name of fields.definite)
|
|
if (!overwritten.has(name))
|
|
exported.push({
|
|
exportedName: name,
|
|
value,
|
|
projection: [name],
|
|
ownEnumerable: true,
|
|
});
|
|
} else
|
|
exported.push({
|
|
exportedName: "*",
|
|
value,
|
|
projection: [{ excludedKeys: [...overwritten] }],
|
|
ownEnumerable: true,
|
|
});
|
|
// Copy applicability belongs to the shared own-slot inventory. Unknown
|
|
// later fields cannot prove that an earlier native field was replaced.
|
|
for (const field of fields.definite) overwritten.add(field);
|
|
}
|
|
return exported;
|
|
}
|
|
const defined = commonJsDefinedExport(node, state);
|
|
if (defined === undefined) return [];
|
|
const descriptor = unwrapJavaScriptExpression(defined.descriptor).node;
|
|
return [
|
|
{
|
|
exportedName: defined.exportedName,
|
|
value: t.isObjectExpression(descriptor)
|
|
? (semanticFinalObjectProperty(descriptor, "value") ?? null)
|
|
: null,
|
|
},
|
|
];
|
|
};
|
|
|
|
/** Preserve potential exports without asserting an unobserved CommonJS wrapper. */
|
|
export const commonJsRuntimeExportValues = (
|
|
node: t.Node,
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): readonly CommonJsRuntimeExportValue[] => {
|
|
const values = commonJsExportValues(node, state);
|
|
return javaScriptRuntimeContext(state.program) === "unknown"
|
|
? values.map((value) => ({
|
|
...value,
|
|
loaderAuthority: "candidate" as const,
|
|
}))
|
|
: values;
|
|
};
|
|
|
|
type Identity = t.Node | null;
|
|
type Execution = "ordered" | "conditional" | "deferred";
|
|
|
|
/** Pattern evaluation follows the RHS, unlike Babel's child visit order. */
|
|
const hasDestructuringEvaluationOrder = (node: t.Node): boolean => {
|
|
const pattern = t.isAssignmentExpression(node)
|
|
? unwrapJavaScriptExpression(node.left).node
|
|
: t.isVariableDeclarator(node)
|
|
? node.id
|
|
: undefined;
|
|
return t.isObjectPattern(pattern) || t.isArrayPattern(pattern);
|
|
};
|
|
|
|
/**
|
|
* Capture receivers before their RHS, then compare with the final public
|
|
* identity. Fresh allocations prove distinctness; explicit wrapper reads
|
|
* preserve even opaque identities. Branches and deferred execution remain
|
|
* uncertain, as do local aliases. Facts live for one analysis and the
|
|
* cooperative traversal bounds work to the source tree size.
|
|
*/
|
|
export function* indexCommonJsExportReceiversSteps(
|
|
state: JavaScriptSemanticAnalysisState,
|
|
): Generator<
|
|
void,
|
|
ReadonlyMap<CommonJsExportSite, CommonJsExportReceiverEffect>
|
|
> {
|
|
const initial = state.program;
|
|
let publicIdentity: Identity = initial;
|
|
let exportsIdentity: Identity = initial;
|
|
let moduleIntact = true;
|
|
let deferredReplacement = false;
|
|
const fresh = new WeakSet<t.Node>([initial]);
|
|
const values = new WeakMap<t.Node, Identity>();
|
|
const captures = new Map<CommonJsExportSite, Identity>();
|
|
const describedFields = new Map<Identity, Set<string>>();
|
|
const deletions = new Map<
|
|
Identity,
|
|
Map<string, { readonly node: t.Node; readonly mode: Execution }>
|
|
>();
|
|
const execution: Execution[] = [];
|
|
const publicCallWrites = new WeakSet<t.Node>();
|
|
// Consume the shared write owner's resolved aliases, intrinsic invocation
|
|
// and keyed mutator facts instead of reinterpreting call names here.
|
|
for (const node of ambientPathWriteSites(state, [
|
|
"commonjs-module",
|
|
"exports",
|
|
]))
|
|
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
|
|
publicCallWrites.add(node);
|
|
const valueOf = (node: t.Node): Identity => {
|
|
const value = unwrapJavaScriptExpression(node).node;
|
|
// An opaque result may alias another object, but reading the current
|
|
// module.exports and explicitly reconnecting exports preserves that result.
|
|
return values.has(value) ? (values.get(value) ?? null) : value;
|
|
};
|
|
|
|
const write = (target: t.Node, identity: Identity, mode: Execution): void => {
|
|
target = unwrapJavaScriptExpression(target).node;
|
|
const possiblePublicWrite =
|
|
(t.isMemberExpression(target) || t.isOptionalMemberExpression(target)) &&
|
|
isCommonJsExportReference(target.object, state, "module") &&
|
|
semanticStaticPropertyKey(target.property, target.computed) === null;
|
|
const publicWrite =
|
|
isCommonJsModuleExports(target, state) || possiblePublicWrite;
|
|
const exportsWrite = isCommonJsExportReference(target, state, "exports");
|
|
const moduleWrite = isCommonJsExportReference(target, state, "module");
|
|
if (!publicWrite && !exportsWrite && !moduleWrite) return;
|
|
if (mode === "deferred") {
|
|
// A source offset cannot order an invocation against module completion.
|
|
deferredReplacement = true;
|
|
return;
|
|
}
|
|
const selected =
|
|
mode === "ordered" && !possiblePublicWrite ? identity : null;
|
|
if (moduleWrite) moduleIntact = false;
|
|
if (publicWrite || moduleWrite)
|
|
publicIdentity = moduleIntact ? selected : null;
|
|
if (exportsWrite) exportsIdentity = selected;
|
|
};
|
|
|
|
yield* traverseJavaScriptValueAstSteps(
|
|
state.program,
|
|
state.erasedSyntaxNodes,
|
|
{
|
|
enter: (node, parent) => {
|
|
const outer = execution.at(-1) ?? "ordered";
|
|
const mode: Execution =
|
|
outer === "deferred" || t.isFunction(node) || t.isClass(node)
|
|
? "deferred"
|
|
: outer === "conditional" ||
|
|
// Mark the whole operation: a later tree-visited RHS must not
|
|
// restore certainty after an earlier tree-visited pattern write.
|
|
hasDestructuringEvaluationOrder(node) ||
|
|
t.isIfStatement(node) ||
|
|
t.isSwitchStatement(node) ||
|
|
t.isLoop(node) ||
|
|
t.isTryStatement(node) ||
|
|
t.isObjectPattern(node) ||
|
|
t.isArrayPattern(node) ||
|
|
(t.isLogicalExpression(parent) && parent.right === node) ||
|
|
(t.isAssignmentPattern(parent) && parent.right === node) ||
|
|
(t.isAssignmentExpression(parent) &&
|
|
["&&=", "||=", "??="].includes(parent.operator) &&
|
|
parent.right === node) ||
|
|
t.isOptionalCallExpression(parent) ||
|
|
(t.isOptionalMemberExpression(parent) &&
|
|
parent.property === node) ||
|
|
(t.isConditionalExpression(parent) && parent.test !== node)
|
|
? "conditional"
|
|
: "ordered";
|
|
execution.push(mode);
|
|
if (
|
|
t.isAssignmentExpression(node) &&
|
|
commonJsExportName(node.left, state) !== undefined &&
|
|
!isCommonJsModuleExports(node.left, state)
|
|
) {
|
|
const receiver =
|
|
t.isMemberExpression(node.left) ||
|
|
t.isOptionalMemberExpression(node.left)
|
|
? node.left.object
|
|
: null;
|
|
captures.set(
|
|
node,
|
|
mode !== "ordered"
|
|
? null
|
|
: receiver !== null &&
|
|
isCommonJsExportReference(receiver, state, "exports")
|
|
? exportsIdentity
|
|
: publicIdentity,
|
|
);
|
|
}
|
|
const descriptor = commonJsDefinedExport(node, state);
|
|
if (descriptor !== undefined) {
|
|
const receiver = isCommonJsExportReference(
|
|
descriptor.receiver,
|
|
state,
|
|
"exports",
|
|
)
|
|
? exportsIdentity
|
|
: publicIdentity;
|
|
const names = describedFields.get(receiver) ?? new Set<string>();
|
|
names.add(descriptor.exportedName);
|
|
describedFields.set(receiver, names);
|
|
}
|
|
const defined = descriptor ?? commonJsAssignedExports(node, state);
|
|
if (defined !== undefined && t.isCallExpression(node))
|
|
captures.set(
|
|
node,
|
|
mode !== "ordered"
|
|
? null
|
|
: isCommonJsExportReference(defined.receiver, state, "exports")
|
|
? exportsIdentity
|
|
: publicIdentity,
|
|
);
|
|
},
|
|
exit: (node) => {
|
|
const mode = execution.pop() ?? "conditional";
|
|
if (publicCallWrites.has(node)) {
|
|
if (mode === "deferred") deferredReplacement = true;
|
|
else publicIdentity = null;
|
|
}
|
|
if (t.isAssignmentExpression(node)) {
|
|
const left = unwrapJavaScriptExpression(node.left).node;
|
|
const identity =
|
|
node.operator === "=" &&
|
|
(t.isIdentifier(left) ||
|
|
t.isMemberExpression(left) ||
|
|
t.isOptionalMemberExpression(left))
|
|
? valueOf(node.right)
|
|
: null;
|
|
for (const target of semanticWriteTargets(node.left))
|
|
write(target, identity, mode);
|
|
values.set(node, identity);
|
|
} else if (t.isVariableDeclarator(node) && node.init != null) {
|
|
for (const target of semanticWriteTargets(node.id))
|
|
write(
|
|
target,
|
|
t.isIdentifier(node.id) ? valueOf(node.init) : null,
|
|
mode,
|
|
);
|
|
} else if (t.isForOfStatement(node) || t.isForInStatement(node)) {
|
|
if (!t.isVariableDeclaration(node.left))
|
|
for (const target of semanticWriteTargets(node.left))
|
|
write(target, null, mode);
|
|
} else if (
|
|
t.isUpdateExpression(node) ||
|
|
t.isUnaryExpression(node, { operator: "delete" })
|
|
) {
|
|
if (t.isUnaryExpression(node, { operator: "delete" })) {
|
|
const name = commonJsExportName(node.argument, state);
|
|
if (
|
|
name !== undefined &&
|
|
!isCommonJsModuleExports(node.argument, state) &&
|
|
(t.isMemberExpression(node.argument) ||
|
|
t.isOptionalMemberExpression(node.argument))
|
|
) {
|
|
const receiver = isCommonJsExportReference(
|
|
node.argument.object,
|
|
state,
|
|
"exports",
|
|
)
|
|
? exportsIdentity
|
|
: publicIdentity;
|
|
const fields = deletions.get(receiver) ?? new Map();
|
|
fields.set(name, {
|
|
node,
|
|
mode: name === "*" && mode === "ordered" ? "conditional" : mode,
|
|
});
|
|
deletions.set(receiver, fields);
|
|
}
|
|
}
|
|
write(node.argument, null, mode);
|
|
} else if (isCommonJsExportReference(node, state, "exports")) {
|
|
values.set(node, exportsIdentity);
|
|
} else if (isCommonJsModuleExports(node, state)) {
|
|
values.set(node, publicIdentity);
|
|
} else if (
|
|
t.isObjectExpression(node) ||
|
|
t.isArrayExpression(node) ||
|
|
t.isFunctionExpression(node) ||
|
|
t.isArrowFunctionExpression(node) ||
|
|
t.isClassExpression(node)
|
|
) {
|
|
values.set(node, node);
|
|
fresh.add(node);
|
|
} else if (t.isSequenceExpression(node)) {
|
|
const last = node.expressions.at(-1);
|
|
values.set(node, last === undefined ? null : valueOf(last));
|
|
}
|
|
},
|
|
},
|
|
);
|
|
const effects = new Map<CommonJsExportSite, CommonJsExportReceiverEffect>();
|
|
for (const [node, receiver] of captures) {
|
|
const status: ReceiverStatus =
|
|
deferredReplacement || receiver === null || publicIdentity === null
|
|
? "uncertain"
|
|
: receiver === publicIdentity
|
|
? "connected"
|
|
: fresh.has(receiver) && fresh.has(publicIdentity)
|
|
? "detached"
|
|
: "uncertain";
|
|
if (status === "detached") {
|
|
effects.set(node, { receiver: status });
|
|
continue;
|
|
}
|
|
const fields = new Map<string, ReceiverStatus>();
|
|
for (const { exportedName } of commonJsRuntimeExportValues(node, state)) {
|
|
const removed = [
|
|
deletions.get(receiver)?.get(exportedName),
|
|
deletions.get(receiver)?.get("*"),
|
|
].filter(
|
|
(deletion) =>
|
|
deletion !== undefined &&
|
|
(deletion.mode === "deferred" ||
|
|
(deletion.node.start ?? -1) > (node.start ?? -1)),
|
|
);
|
|
if (removed.length === 0) continue;
|
|
// An ordinary publication creates configurable data slots. Descriptor
|
|
// definitions do not establish deletion success without their flags.
|
|
const configurable =
|
|
(t.isAssignmentExpression(node) ||
|
|
commonJsAssignedExports(node, state) !== undefined) &&
|
|
!describedFields.get(receiver)?.has(exportedName) &&
|
|
!describedFields.get(receiver)?.has("*");
|
|
fields.set(
|
|
exportedName,
|
|
configurable &&
|
|
status !== "uncertain" &&
|
|
removed.every((deletion) => deletion?.mode === "ordered")
|
|
? "detached"
|
|
: "uncertain",
|
|
);
|
|
}
|
|
effects.set(node, {
|
|
receiver: status,
|
|
...(fields.size === 0 ? {} : { fields }),
|
|
});
|
|
}
|
|
return effects;
|
|
}
|