fix(javascript): correct lexical and dynamic scope analysis (#538)

* fix(javascript): gate CommonJS exports on unshadowed globals and record dynamic scope

* fix(javascript): correct dynamic and switch scope boundaries
This commit is contained in:
morluto
2026-10-05 23:42:48 +08:00
committed by GitHub
parent 00fa97422f
commit 6fa6f1f9b1
13 changed files with 337 additions and 28 deletions
@@ -382,6 +382,64 @@ describe("JavaScript semantic analysis: structure 2", () => {
"read", // const observed = total
]);
});
});
describe("JavaScript semantic analysis: dynamic and case scopes", () => {
it("marks with and eval as unresolved dynamic scope instead of staying silent", () => {
const ir = analyzeJavaScriptSemantics(`
function load(source) {
with (host) { consume(target); }
eval("var injected = 1;");
}
`);
const reasons = ir.frontiers
.filter(({ kind }) => kind === "dynamic-scope")
.map(({ reason }) => reason);
expect(reasons).toHaveLength(2);
expect(reasons.join("\n")).toContain("`with`");
expect(reasons.join("\n")).toContain("`eval`");
});
it("does not assign CommonJS exports to lexically shadowed module or exports", () => {
const ir = analyzeJavaScriptSemantics(`
function shadowed(module, exports) {
module.exports.value = 1;
exports.other = 2;
exports[key] = 3;
module.exports[key] = 4;
unrelated[key] = 5;
}
`);
expect(
ir.moduleLinks.filter(({ kind }) => kind === "commonjs-export"),
).toEqual([]);
});
it("shares one lexical scope across switch cases and isolates static blocks", () => {
const switchIr = analyzeJavaScriptSemantics(`
const kind = select();
switch (kind) {
case "a": let shared = 1; break;
case "b": shared = 2; break;
}
`);
// One declaration, one binding — and it belongs to a scope of its own, so
// it cannot leak past the switch statement.
const shared = switchIr.bindings.filter(({ name }) => name === "shared");
expect(shared).toHaveLength(1);
expect(shared[0]?.scopeId).not.toBe(
topLevelBinding(switchIr, "kind").scopeId,
);
const classIr = analyzeJavaScriptSemantics(`
class Holder {
static { let isolated = 1; }
static { let isolated = 2; }
}
`);
expect(
classIr.bindings.filter(({ name }) => name === "isolated"),
).toHaveLength(2);
});
it("keeps function, class, and method identities separate from bindings", () => {
const ir = analyzeJavaScriptSemantics(`
+42 -6
View File
@@ -141,15 +141,34 @@ const collectDefinitions = (
const stack: JavaScriptSemanticScopeState[] = [
currentSemanticScope(state.scopes),
];
const openedScopes = new WeakSet<t.Node>();
const openedScopes = new WeakMap<t.Node, number>();
traverseJavaScriptAst(program, {
enter: (node, parent) => {
const parentScope = currentSemanticScope(stack);
let parentScope = currentSemanticScope(stack);
if (
parent !== null &&
t.isWithStatement(parent) &&
parent.body === node
) {
const dynamicScope: JavaScriptSemanticScopeState = {
scopeId: `${semanticScopeId("block", parent)}:with`,
parentScopeId: parentScope.scopeId,
kind: "block",
location: range(parent),
bindingsComplete: false,
bindings: new Map(),
};
state.scopes.push(dynamicScope);
state.scopesById.set(dynamicScope.scopeId, dynamicScope);
stack.push(dynamicScope);
openedScopes.set(node, 1);
parentScope = dynamicScope;
}
bindOuterDeclaration(node, parentScope, state);
const nested = nestedScope(node, parent, parentScope, state);
if (nested !== undefined) {
stack.push(nested);
openedScopes.add(node);
openedScopes.set(node, (openedScopes.get(node) ?? 0) + 1);
}
const scope = currentSemanticScope(stack);
state.scopeByNode.set(node, scope);
@@ -163,7 +182,8 @@ const collectDefinitions = (
bindInnerDeclaration(node, parent, scope, state);
},
exit: (node) => {
if (openedScopes.has(node)) stack.pop();
for (let count = openedScopes.get(node) ?? 0; count > 0; count--)
stack.pop();
},
});
};
@@ -243,13 +263,23 @@ const nestedScope = (
parentScope: JavaScriptSemanticScopeState,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticScopeState | undefined => {
const switchOwner =
t.isSwitchCase(node) && parent !== null && t.isSwitchStatement(parent)
? parent
: undefined;
if (switchOwner !== undefined) {
const existing = state.scopesById.get(
semanticScopeId("block", switchOwner),
);
if (existing !== undefined) return existing;
}
const kind = scopeKind(node, parent);
if (kind === undefined) return undefined;
const scope: JavaScriptSemanticScopeState = {
scopeId: semanticScopeId(kind, node),
scopeId: semanticScopeId(kind, switchOwner ?? node),
parentScopeId: parentScope.scopeId,
kind,
location: range(node),
location: range(switchOwner ?? node),
bindingsComplete: true,
bindings: new Map(),
};
@@ -271,6 +301,12 @@ const scopeKind = (
t.isForInStatement(node)
)
return "block";
// A switch body is one lexical scope shared by all its cases, so `let` in
// two cases must resolve to one binding rather than collide or leak.
if (t.isSwitchCase(node)) return "block";
// Each `static {}` block is its own lexical scope; otherwise a `let` in two
// static blocks would collide in the enclosing class scope.
if (t.isStaticBlock(node)) return "static-block";
if (
t.isBlockStatement(node) &&
!(parent !== null && t.isFunction(parent) && parent.body === node)
+32
View File
@@ -16,6 +16,7 @@ import {
} from "./javascriptSemanticProjection.js";
import {
resolveSemanticBindingState,
isUnshadowedGlobal,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
@@ -91,6 +92,7 @@ export const collectJavaScriptSemanticCalls = (
const owner = enclosingFunction(callableStack);
collectCapture(node, parent, owner, context);
collectDynamicProperty(node, owner, state, output);
collectDynamicScope(node, owner, state, output);
if (
t.isCallExpression(node) ||
t.isOptionalCallExpression(node) ||
@@ -365,6 +367,36 @@ const collectDynamicProperty = (
);
};
/**
* `with (o) { … }` and `eval("…")` decide at runtime which bindings exist, so
* every name inside them is unresolvable statically. Recording the frontier
* is what keeps the analyzer from presenting an empty or partial resolution as
* an observed fact — silence here would read as "nothing to resolve".
*/
const collectDynamicScope = (
node: t.Node,
owner: JavaScriptSemanticCallable | undefined,
state: JavaScriptSemanticAnalysisState,
output: MutableCallAnalysis,
): void => {
const reason = t.isWithStatement(node)
? "`with` introduces a runtime binding environment; names inside are not statically resolvable."
: t.isCallExpression(node) && isUnshadowedGlobal(node.callee, state, "eval")
? "`eval` can declare bindings at runtime; names inside the evaluated source are not statically resolvable."
: null;
if (reason === null) return;
addFrontier(
{
kind: "dynamic-scope",
callableId: owner?.callableId ?? null,
location: range(node),
reason,
},
state,
output,
);
};
const addFrontier = (
frontier: JavaScriptSemanticFrontier,
state: JavaScriptSemanticAnalysisState,
@@ -246,6 +246,7 @@ export const JAVASCRIPT_SEMANTIC_UNKNOWN_REASONS = [
"bound-reached",
"dynamic-call",
"dynamic-property",
"dynamic-scope",
"eval-or-generated-code",
"incomplete-module",
"missing-source",
+13 -2
View File
@@ -44,7 +44,13 @@ export type JavaScriptBindingProvenance =
export interface JavaScriptSemanticScope {
readonly scopeId: string;
readonly parentScopeId: string | null;
readonly kind: "program" | "function" | "block" | "class" | "catch";
readonly kind:
| "program"
| "function"
| "block"
| "static-block"
| "class"
| "catch";
readonly location: JavaScriptSourceRange;
readonly bindingsComplete: boolean;
readonly bindingIds: readonly string[];
@@ -369,7 +375,12 @@ export interface JavaScriptSemanticObjectOperation {
/** One syntax location where exact local semantic continuation is unavailable. */
export interface JavaScriptSemanticFrontier {
readonly kind: "dynamic-call" | "dynamic-property";
/**
* `dynamic-call`/`dynamic-property` mark a callee or key the analyzer could
* not resolve. `dynamic-scope` marks `with`/`eval`, where the binding
* environment itself is not statically knowable.
*/
readonly kind: "dynamic-call" | "dynamic-property" | "dynamic-scope";
readonly callableId: string | null;
readonly location: JavaScriptSourceRange;
readonly reason: string;
+12 -8
View File
@@ -10,6 +10,7 @@ import type {
import {
resolveSemanticBindingState,
semanticResolutionBlocked,
isUnshadowedGlobal,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticScopeState,
} from "./javascriptSemanticState.js";
@@ -357,7 +358,7 @@ const collectCommonJsExport = (
node: t.AssignmentExpression,
state: JavaScriptSemanticAnalysisState,
): void => {
const exportedName = commonJsExportName(node.left);
const exportedName = commonJsExportName(node.left, state);
if (exportedName === undefined) return;
const origin = semanticModuleOrigin(node.right, [], state);
addModuleLink(state, {
@@ -610,24 +611,27 @@ const defaultDeclarationName = (
? declaration.id.name
: null;
const commonJsExportName = (node: t.Node): string | undefined => {
if (t.isIdentifier(node, { name: "exports" })) return "default";
const commonJsExportName = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): string | undefined => {
if (isUnshadowedGlobal(node, state, "exports")) return "default";
if (!t.isMemberExpression(node) && !t.isOptionalMemberExpression(node))
return undefined;
const key = memberKey(node);
// `exports[key]`/`module.exports[key]` assign an export whose name is not
// knowable. Report the wildcard rather than the variable name, and never
// collapse it into `default`, which would claim a real default export.
if (key === null) return "*";
if (t.isIdentifier(node.object, { name: "exports" })) return key || "*";
if (isUnshadowedGlobal(node.object, state, "exports"))
return key === null ? "*" : key || "*";
if (
t.isMemberExpression(node.object) &&
t.isIdentifier(node.object.object, { name: "module" }) &&
isUnshadowedGlobal(node.object.object, state, "module") &&
memberKey(node.object) === "exports"
)
return key || "default";
return key === null ? "*" : key || "default";
if (
t.isIdentifier(node.object, { name: "module" }) &&
isUnshadowedGlobal(node.object, state, "module") &&
memberKey(node) === "exports"
)
return "default";
+10
View File
@@ -138,3 +138,13 @@ export const semanticVariableScope = (
}
return candidate;
};
/** Identify a global name only when no lexical or dynamic environment shadows it. */
export const isUnshadowedGlobal = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
name: string,
): boolean =>
t.isIdentifier(node, { name }) &&
resolveSemanticBindingState(state, node, name) === undefined &&
!semanticResolutionBlocked(state, node, name);