fix(javascript): resolve exported callables through lexical bindings (#1351)
* fix(javascript): resolve exported callables through lexical bindings * fix(javascript): preserve export scope and hoisted writes * test(javascript): consolidate export binding assertions * fix(javascript): account for skipped initializers and loop binding writes * fix(javascript): preserve parameters copied into body variables
This commit is contained in:
@@ -286,6 +286,8 @@ const createState = (program: t.Program): JavaScriptSemanticAnalysisState => {
|
||||
callables: [],
|
||||
callableNodesById: new Map(),
|
||||
moduleLinks: [],
|
||||
moduleLinkBindings: new WeakMap(),
|
||||
conditionalInitializers: new WeakSet(),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -297,9 +299,34 @@ const collectDefinitions = (
|
||||
currentSemanticScope(state.scopes),
|
||||
];
|
||||
const openedScopes = new WeakMap<t.Node, number>();
|
||||
const assignments: {
|
||||
readonly node: t.Node;
|
||||
readonly scope: JavaScriptSemanticScopeState;
|
||||
}[] = [];
|
||||
const functionBodies: {
|
||||
readonly body: t.BlockStatement;
|
||||
readonly scope: JavaScriptSemanticScopeState;
|
||||
readonly parameters: t.Function["params"];
|
||||
}[] = [];
|
||||
traverseJavaScriptAst(program, {
|
||||
enter: (node, parent) => {
|
||||
enter: (node, parent, readAncestors) => {
|
||||
let parentScope = currentSemanticScope(stack);
|
||||
if (
|
||||
parent !== null &&
|
||||
(t.isObjectMethod(parent) || t.isClassMethod(parent)) &&
|
||||
parent.computed &&
|
||||
parent.key === node &&
|
||||
parentScope.parentScopeId !== null
|
||||
) {
|
||||
// A computed method key is evaluated before entering the method's
|
||||
// parameter and body environments.
|
||||
const keyScope = state.scopesById.get(parentScope.parentScopeId);
|
||||
if (keyScope !== undefined) {
|
||||
stack.push(keyScope);
|
||||
openedScopes.set(node, 1);
|
||||
parentScope = keyScope;
|
||||
}
|
||||
}
|
||||
if (
|
||||
parent !== null &&
|
||||
t.isWithStatement(parent) &&
|
||||
@@ -324,6 +351,12 @@ const collectDefinitions = (
|
||||
if (nested !== undefined) {
|
||||
stack.push(nested);
|
||||
openedScopes.set(node, (openedScopes.get(node) ?? 0) + 1);
|
||||
if (t.isBlockStatement(node) && t.isFunction(parent))
|
||||
functionBodies.push({
|
||||
body: node,
|
||||
scope: nested,
|
||||
parameters: parent.params,
|
||||
});
|
||||
}
|
||||
const scope = currentSemanticScope(stack);
|
||||
state.scopeByNode.set(node, scope);
|
||||
@@ -335,12 +368,95 @@ const collectDefinitions = (
|
||||
state,
|
||||
});
|
||||
bindInnerDeclaration(node, parent, scope, state);
|
||||
if (
|
||||
t.isVariableDeclarator(node) &&
|
||||
node.init != null &&
|
||||
parent !== null &&
|
||||
t.isVariableDeclaration(parent, { kind: "var" }) &&
|
||||
hasConditionalInitializer(readAncestors())
|
||||
)
|
||||
state.conditionalInitializers.add(node.init);
|
||||
if (
|
||||
t.isAssignmentExpression(node) ||
|
||||
t.isUpdateExpression(node) ||
|
||||
t.isForOfStatement(node) ||
|
||||
t.isForInStatement(node)
|
||||
)
|
||||
assignments.push({ node, scope });
|
||||
},
|
||||
exit: (node) => {
|
||||
for (let count = openedScopes.get(node) ?? 0; count > 0; count--)
|
||||
stack.pop();
|
||||
},
|
||||
});
|
||||
// All declarations must exist before resolving writes, including hoisted
|
||||
// functions and local declarations that shadow an outer binding.
|
||||
for (const { node, scope } of assignments) bindAssignment(node, scope, state);
|
||||
for (const { body, scope, parameters } of functionBodies)
|
||||
for (const parameter of parameters)
|
||||
for (const identifier of assignedPatternIdentifiers(
|
||||
t.isTSParameterProperty(parameter) ? parameter.parameter : parameter,
|
||||
))
|
||||
copyParameterToBody({ identifier, body, scope, state });
|
||||
};
|
||||
|
||||
const copyParameterToBody = (input: {
|
||||
readonly identifier: t.Identifier;
|
||||
readonly body: t.BlockStatement;
|
||||
readonly scope: JavaScriptSemanticScopeState;
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
}): void => {
|
||||
const { identifier, body, scope, state } = input;
|
||||
const binding = scope.bindings.get(identifier.name);
|
||||
if (
|
||||
binding === undefined ||
|
||||
binding.kind !== "variable" ||
|
||||
binding.definitions.some(({ kind }) => kind === "function")
|
||||
)
|
||||
return;
|
||||
// A separate body var environment starts with the parameter's value. The
|
||||
// real parameter identifier retains its scope and source location; entryBody
|
||||
// records when the copy occurs without inventing an expression in the AST.
|
||||
binding.initializers.unshift({
|
||||
node: identifier,
|
||||
projection: [],
|
||||
entryBody: body,
|
||||
});
|
||||
for (let index = binding.initializers.length - 1; index >= 0; index -= 1) {
|
||||
const initializer = binding.initializers[index];
|
||||
if (
|
||||
initializer !== undefined &&
|
||||
initializer.entryBody === undefined &&
|
||||
initializer.projection.length === 0 &&
|
||||
t.isIdentifier(initializer.node) &&
|
||||
resolveSemanticBindingState(
|
||||
state,
|
||||
initializer.node,
|
||||
initializer.node.name,
|
||||
) === binding
|
||||
)
|
||||
// Direct self-initialization preserves the prior value, including any
|
||||
// actual overwrite before it. Keep the source definition/reference facts.
|
||||
binding.initializers.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
const hasConditionalInitializer = (ancestors: readonly t.Node[]): boolean => {
|
||||
// A hoisted var can remain undefined when control flow skips its initializer.
|
||||
// Conditions outside the owning callable/static block do not govern its body.
|
||||
for (let index = ancestors.length - 1; index >= 0; index -= 1) {
|
||||
const node = ancestors[index];
|
||||
if (t.isFunction(node) || t.isProgram(node) || t.isStaticBlock(node))
|
||||
return false;
|
||||
if (
|
||||
t.isIfStatement(node) ||
|
||||
t.isLoop(node) ||
|
||||
t.isSwitchCase(node) ||
|
||||
t.isTryStatement(node)
|
||||
)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const bindOuterDeclaration = (
|
||||
@@ -408,7 +524,14 @@ const bindInnerDeclaration = (
|
||||
mutable: true,
|
||||
kind: "catch",
|
||||
});
|
||||
else if (t.isAssignmentExpression(node)) {
|
||||
};
|
||||
|
||||
const bindAssignment = (
|
||||
node: t.Node,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
if (t.isAssignmentExpression(node)) {
|
||||
if (t.isIdentifier(node.left))
|
||||
addAssignment(
|
||||
node.left,
|
||||
@@ -426,8 +549,11 @@ const bindInnerDeclaration = (
|
||||
} else if (t.isUpdateExpression(node) && t.isIdentifier(node.argument))
|
||||
addAssignment(node.argument, node, scope, state);
|
||||
else if (t.isForOfStatement(node) || t.isForInStatement(node))
|
||||
for (const identifier of assignedPatternIdentifiers(node.left))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
for (const pattern of t.isVariableDeclaration(node.left)
|
||||
? node.left.declarations.map(({ id }) => id)
|
||||
: [node.left])
|
||||
for (const identifier of assignedPatternIdentifiers(pattern))
|
||||
addAssignment(identifier, node, scope, state);
|
||||
};
|
||||
|
||||
const assignedPatternIdentifiers = (
|
||||
@@ -539,12 +665,42 @@ const scopeKind = (
|
||||
if (t.isStaticBlock(node)) return "static-block";
|
||||
if (
|
||||
t.isBlockStatement(node) &&
|
||||
!(parent !== null && t.isFunction(parent) && parent.body === node)
|
||||
)
|
||||
return "block";
|
||||
parent !== null &&
|
||||
t.isFunction(parent) &&
|
||||
parent.body === node
|
||||
) {
|
||||
// Parameter expressions cannot see declarations in the function body.
|
||||
// Retain the outer function scope for parameters and callable ownership;
|
||||
// body declarations belong to a separate variable environment.
|
||||
return functionParametersHaveExpressions(parent) ? "function" : undefined;
|
||||
}
|
||||
if (t.isBlockStatement(node)) return "block";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const functionParametersHaveExpressions = (node: t.Function): boolean => {
|
||||
const pending: t.Node[] = [...node.params];
|
||||
while (pending.length > 0) {
|
||||
const parameter = pending.pop();
|
||||
if (t.isAssignmentPattern(parameter)) return true;
|
||||
if (t.isTSParameterProperty(parameter)) pending.push(parameter.parameter);
|
||||
else if (t.isRestElement(parameter)) pending.push(parameter.argument);
|
||||
else if (t.isArrayPattern(parameter)) {
|
||||
for (const element of parameter.elements)
|
||||
if (element !== null) pending.push(element);
|
||||
} else if (t.isObjectPattern(parameter)) {
|
||||
for (const property of parameter.properties) {
|
||||
if (t.isRestElement(property)) pending.push(property.argument);
|
||||
else {
|
||||
if (property.computed) return true;
|
||||
pending.push(property.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const bindImports = (
|
||||
node: t.ImportDeclaration,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
|
||||
@@ -171,8 +171,10 @@ const mutationInitializers = (
|
||||
if (binding.initializers.length < 2) return binding.initializers;
|
||||
const mutationPosition = directMutationPosition(mutation, parents);
|
||||
if (mutationPosition === null) return binding.initializers;
|
||||
const positions = binding.initializers.map(({ node }) =>
|
||||
directInitializerPosition(node, parents),
|
||||
const positions = binding.initializers.map(({ node, entryBody }) =>
|
||||
entryBody === undefined
|
||||
? directInitializerPosition(node, parents)
|
||||
: { body: entryBody.body, index: -1 },
|
||||
);
|
||||
if (
|
||||
positions.some(
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
evaluateSemanticBinding,
|
||||
evaluateSemanticProvenance,
|
||||
} from "./javascriptSemanticValues.js";
|
||||
import { range, stringValue } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import {
|
||||
propertyName,
|
||||
semanticStaticPropertyKey,
|
||||
@@ -68,25 +68,33 @@ export const collectSemanticModuleLink = (
|
||||
): void => {
|
||||
if (t.isImportDeclaration(node)) collectImports(node, state);
|
||||
else if (t.isExportAllDeclaration(node))
|
||||
addModuleLink(state, {
|
||||
kind: "re-export",
|
||||
specifier: node.source.value,
|
||||
importedName: "*",
|
||||
localName: null,
|
||||
exportedName: "*",
|
||||
location: range(node),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "re-export",
|
||||
specifier: node.source.value,
|
||||
importedName: "*",
|
||||
localName: null,
|
||||
exportedName: "*",
|
||||
location: range(node),
|
||||
},
|
||||
node,
|
||||
);
|
||||
else if (t.isExportNamedDeclaration(node)) collectNamedExports(node, state);
|
||||
else if (t.isExportDefaultDeclaration(node))
|
||||
addModuleLink(state, {
|
||||
kind: "export",
|
||||
specifier: null,
|
||||
importedName: null,
|
||||
localName: defaultDeclarationName(node.declaration),
|
||||
exportedName: "default",
|
||||
callableId: semanticCallableIdForNode(node.declaration),
|
||||
location: range(node),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "export",
|
||||
specifier: null,
|
||||
importedName: null,
|
||||
localName: defaultDeclarationName(node.declaration),
|
||||
exportedName: "default",
|
||||
callableId: semanticCallableIdForNode(node.declaration),
|
||||
location: range(node),
|
||||
},
|
||||
node,
|
||||
);
|
||||
else if (t.isVariableDeclarator(node)) collectRequireLink(node, state);
|
||||
else if (t.isAssignmentExpression(node)) collectCommonJsExport(node, state);
|
||||
};
|
||||
@@ -233,27 +241,35 @@ const collectImports = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
if (node.specifiers.length === 0)
|
||||
addModuleLink(state, {
|
||||
kind: "import",
|
||||
specifier: node.source.value,
|
||||
importedName: null,
|
||||
localName: null,
|
||||
exportedName: null,
|
||||
location: range(node),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "import",
|
||||
specifier: node.source.value,
|
||||
importedName: null,
|
||||
localName: null,
|
||||
exportedName: null,
|
||||
location: range(node),
|
||||
},
|
||||
node,
|
||||
);
|
||||
for (const specifier of node.specifiers)
|
||||
addModuleLink(state, {
|
||||
kind: "import",
|
||||
specifier: node.source.value,
|
||||
importedName: t.isImportDefaultSpecifier(specifier)
|
||||
? "default"
|
||||
: t.isImportNamespaceSpecifier(specifier)
|
||||
? "*"
|
||||
: propertyName(specifier.imported),
|
||||
localName: specifier.local.name,
|
||||
exportedName: null,
|
||||
location: range(specifier),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "import",
|
||||
specifier: node.source.value,
|
||||
importedName: t.isImportDefaultSpecifier(specifier)
|
||||
? "default"
|
||||
: t.isImportNamespaceSpecifier(specifier)
|
||||
? "*"
|
||||
: propertyName(specifier.imported),
|
||||
localName: specifier.local.name,
|
||||
exportedName: null,
|
||||
location: range(specifier),
|
||||
},
|
||||
node,
|
||||
);
|
||||
};
|
||||
|
||||
const collectNamedExports = (
|
||||
@@ -262,25 +278,33 @@ const collectNamedExports = (
|
||||
): void => {
|
||||
if (node.declaration !== null && node.declaration !== undefined)
|
||||
for (const localName of declarationNames(node.declaration))
|
||||
addModuleLink(state, {
|
||||
kind: "export",
|
||||
specifier: null,
|
||||
importedName: null,
|
||||
localName,
|
||||
exportedName: localName,
|
||||
callableId: declarationCallableId(node.declaration, localName),
|
||||
location: range(node.declaration),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "export",
|
||||
specifier: null,
|
||||
importedName: null,
|
||||
localName,
|
||||
exportedName: localName,
|
||||
callableId: declarationCallableId(node.declaration, localName),
|
||||
location: range(node.declaration),
|
||||
},
|
||||
node,
|
||||
);
|
||||
for (const specifier of node.specifiers)
|
||||
if (t.isExportSpecifier(specifier))
|
||||
addModuleLink(state, {
|
||||
kind: node.source == null ? "export" : "re-export",
|
||||
specifier: node.source?.value ?? null,
|
||||
importedName: propertyName(specifier.local),
|
||||
localName: node.source == null ? propertyName(specifier.local) : null,
|
||||
exportedName: propertyName(specifier.exported),
|
||||
location: range(specifier),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: node.source == null ? "export" : "re-export",
|
||||
specifier: node.source?.value ?? null,
|
||||
importedName: propertyName(specifier.local),
|
||||
localName: node.source == null ? propertyName(specifier.local) : null,
|
||||
exportedName: propertyName(specifier.exported),
|
||||
location: range(specifier),
|
||||
},
|
||||
node,
|
||||
);
|
||||
};
|
||||
|
||||
const collectRequireLink = (
|
||||
@@ -290,14 +314,18 @@ const collectRequireLink = (
|
||||
const origin = semanticRequireOrigin(node.init, state);
|
||||
if (origin === undefined) return;
|
||||
for (const binding of requirePatternBindings(node.id, origin.importedPath))
|
||||
addModuleLink(state, {
|
||||
kind: "require",
|
||||
specifier: origin.specifier,
|
||||
importedName: binding.importedName,
|
||||
localName: binding.localName,
|
||||
exportedName: null,
|
||||
location: range(node),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "require",
|
||||
specifier: origin.specifier,
|
||||
importedName: binding.importedName,
|
||||
localName: binding.localName,
|
||||
exportedName: null,
|
||||
location: range(node),
|
||||
},
|
||||
node,
|
||||
);
|
||||
};
|
||||
|
||||
const requirePatternBindings = (
|
||||
@@ -334,15 +362,19 @@ const collectCommonJsExport = (
|
||||
const exportedName = commonJsExportName(node.left, state);
|
||||
if (exportedName === undefined) return;
|
||||
const origin = semanticRequireOrigin(node.right, state);
|
||||
addModuleLink(state, {
|
||||
kind: "commonjs-export",
|
||||
specifier: origin?.specifier ?? null,
|
||||
importedName: origin?.importedPath.at(-1) ?? null,
|
||||
localName: t.isIdentifier(node.right) ? node.right.name : null,
|
||||
exportedName,
|
||||
callableId: semanticCallableIdForNode(node.right),
|
||||
location: range(node),
|
||||
});
|
||||
addModuleLink(
|
||||
state,
|
||||
{
|
||||
kind: "commonjs-export",
|
||||
specifier: origin?.specifier ?? null,
|
||||
importedName: origin?.importedPath.at(-1) ?? null,
|
||||
localName: t.isIdentifier(node.right) ? node.right.name : null,
|
||||
exportedName,
|
||||
callableId: semanticCallableIdForNode(node.right),
|
||||
location: range(node),
|
||||
},
|
||||
node,
|
||||
);
|
||||
};
|
||||
|
||||
const addModuleLink = (
|
||||
@@ -350,8 +382,18 @@ const addModuleLink = (
|
||||
link: Omit<JavaScriptSemanticModuleLink, "callableId"> & {
|
||||
readonly callableId?: string | null;
|
||||
},
|
||||
referenceNode: t.Node,
|
||||
): void => {
|
||||
state.moduleLinks.push({ ...link, callableId: link.callableId ?? null });
|
||||
const collected = { ...link, callableId: link.callableId ?? null };
|
||||
state.moduleLinks.push(collected);
|
||||
if (link.localName !== null) {
|
||||
const binding = resolveSemanticBindingState(
|
||||
state,
|
||||
referenceNode,
|
||||
link.localName,
|
||||
);
|
||||
if (binding !== undefined) state.moduleLinkBindings.set(collected, binding);
|
||||
}
|
||||
};
|
||||
|
||||
/** Deterministic callable identity shared by collection and return recovery. */
|
||||
|
||||
@@ -93,19 +93,14 @@ export const resolveSemanticModuleCallables = (
|
||||
callables: readonly JavaScriptSemanticCallable[],
|
||||
): JavaScriptSemanticModuleLink[] => {
|
||||
const callableIds = new Set(callables.map(({ callableId }) => callableId));
|
||||
const root = state.scopes.find(({ kind }) => kind === "program");
|
||||
return state.moduleLinks.map((link) => {
|
||||
if (link.callableId !== null && callableIds.has(link.callableId))
|
||||
return link;
|
||||
if (link.localName === null || root === undefined)
|
||||
return { ...link, callableId: null };
|
||||
const named = callables.filter(
|
||||
({ name, containerScopeId }) =>
|
||||
name === link.localName && containerScopeId === root.scopeId,
|
||||
);
|
||||
if (named.length === 1)
|
||||
return { ...link, callableId: named[0]?.callableId ?? null };
|
||||
const binding = root.bindings.get(link.localName);
|
||||
// Named exports follow their lexical binding, including every assignment.
|
||||
// A declaration's ID or a callable's display name cannot prove that link.
|
||||
if (link.localName === null)
|
||||
return link.callableId !== null && callableIds.has(link.callableId)
|
||||
? link
|
||||
: { ...link, callableId: null };
|
||||
const binding = state.moduleLinkBindings.get(link);
|
||||
const resolved =
|
||||
binding === undefined
|
||||
? []
|
||||
@@ -154,10 +149,24 @@ const callableIdsForBinding = (
|
||||
admitted: ReadonlySet<string>,
|
||||
seen: ReadonlySet<string>,
|
||||
): string[] => {
|
||||
if (seen.has(binding.bindingId) || binding.initializers.length !== 1)
|
||||
// A single initializer does not prove an assignment executes or replace
|
||||
// the unknown incoming value of a parameter/catch binding.
|
||||
if (
|
||||
seen.has(binding.bindingId) ||
|
||||
binding.initializers.length !== 1 ||
|
||||
binding.definitions.some(
|
||||
({ kind }) =>
|
||||
kind === "assignment" || kind === "parameter" || kind === "catch",
|
||||
)
|
||||
)
|
||||
return [];
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined || initializer.projection.length > 0) return [];
|
||||
if (
|
||||
initializer === undefined ||
|
||||
initializer.projection.length > 0 ||
|
||||
state.conditionalInitializers.has(initializer.node)
|
||||
)
|
||||
return [];
|
||||
return callableIdsForNode(
|
||||
initializer.node,
|
||||
state,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
interface JavaScriptSemanticInitializer {
|
||||
readonly node: t.Node;
|
||||
readonly projection: readonly (string | number | null)[];
|
||||
readonly entryBody?: t.BlockStatement;
|
||||
}
|
||||
|
||||
/** Mutable binding state used only while constructing the immutable IR. */
|
||||
@@ -46,6 +47,11 @@ export interface JavaScriptSemanticAnalysisState {
|
||||
readonly callables: JavaScriptSemanticCallable[];
|
||||
readonly callableNodesById: Map<string, t.Node>;
|
||||
readonly moduleLinks: JavaScriptSemanticModuleLink[];
|
||||
readonly moduleLinkBindings: WeakMap<
|
||||
JavaScriptSemanticModuleLink,
|
||||
JavaScriptSemanticBindingState
|
||||
>;
|
||||
readonly conditionalInitializers: WeakSet<t.Node>;
|
||||
}
|
||||
|
||||
/** Return the active scope from a non-empty construction stack. */
|
||||
|
||||
Reference in New Issue
Block a user