feat(javascript): add binding and constant-value semantic IR
This commit is contained in:
@@ -0,0 +1,518 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import {
|
||||
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
|
||||
failedJavaScriptSemanticIr,
|
||||
type JavaScriptModuleOrigin,
|
||||
type JavaScriptSemanticDefinition,
|
||||
type JavaScriptSemanticIr,
|
||||
type JavaScriptSemanticLimits,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
collectSemanticModuleLink,
|
||||
collectSemanticCallable,
|
||||
collectSemanticReferences,
|
||||
immutableSemanticBindings,
|
||||
immutableSemanticScopes,
|
||||
reachSemanticLimit,
|
||||
semanticModuleOrigin,
|
||||
semanticStaticPropertyName,
|
||||
} from "./javascriptSemanticProjection.js";
|
||||
import type {
|
||||
JavaScriptSemanticAnalysisState,
|
||||
JavaScriptSemanticBindingState,
|
||||
JavaScriptSemanticScopeState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import {
|
||||
currentSemanticScope,
|
||||
semanticScopeId,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
range,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
interface BindPatternInput {
|
||||
readonly pattern: t.Node;
|
||||
readonly initializer: t.Node | null;
|
||||
readonly scope: JavaScriptSemanticScopeState;
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
readonly mutable: boolean;
|
||||
readonly kind?: JavaScriptSemanticDefinition["kind"];
|
||||
readonly projection?: readonly (string | number | null)[];
|
||||
}
|
||||
|
||||
interface AddBindingInput {
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
readonly scope: JavaScriptSemanticScopeState;
|
||||
readonly name: string;
|
||||
readonly kind: JavaScriptSemanticDefinition["kind"];
|
||||
readonly mutable: boolean;
|
||||
readonly definitionNode: t.Node;
|
||||
readonly initializer: t.Node | null;
|
||||
readonly directOrigin?: JavaScriptModuleOrigin;
|
||||
readonly projection?: readonly (string | number | null)[];
|
||||
}
|
||||
|
||||
/** Recover bounded lexical bindings, aliases, constants, and module links. */
|
||||
export const analyzeJavaScriptSemantics = (
|
||||
source: string,
|
||||
inputLimits: Partial<JavaScriptSemanticLimits> = {},
|
||||
): JavaScriptSemanticIr => {
|
||||
const limits = { ...DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS, ...inputLimits };
|
||||
let file: ReturnType<typeof parse>;
|
||||
try {
|
||||
file = parse(source, {
|
||||
sourceType: "unambiguous",
|
||||
errorRecovery: true,
|
||||
plugins: ["jsx", "typescript"],
|
||||
});
|
||||
} catch {
|
||||
return failedJavaScriptSemanticIr();
|
||||
}
|
||||
const state = createState(file.program, limits);
|
||||
collectDefinitions(file.program, state);
|
||||
const references = collectSemanticReferences(file.program, state);
|
||||
const parserPartial = file.errors.length > 0;
|
||||
return {
|
||||
schema: "JavaScriptSemanticIR",
|
||||
schemaVersion: 1,
|
||||
scopes: immutableSemanticScopes(state),
|
||||
bindings: immutableSemanticBindings(state),
|
||||
callables: [...state.callables],
|
||||
references,
|
||||
moduleLinks: [...state.moduleLinks],
|
||||
coverage: {
|
||||
status:
|
||||
state.limitsReached.size > 0
|
||||
? "truncated"
|
||||
: parserPartial
|
||||
? "partial"
|
||||
: "complete",
|
||||
omittedCount: state.limitsReached.size > 0 ? state.omittedCount : 0,
|
||||
limitsReached: [...state.limitsReached].sort(compareCodePoints),
|
||||
},
|
||||
limitations: [
|
||||
...(parserPartial
|
||||
? [
|
||||
"The parser recovered from syntax errors; affected bindings are partial.",
|
||||
]
|
||||
: []),
|
||||
...(state.limitsReached.size === 0
|
||||
? []
|
||||
: ["Semantic recovery stopped retaining facts at explicit limits."]),
|
||||
"Values and aliases were recovered from inert syntax only; no JavaScript was executed.",
|
||||
"Cross-function mutation and dynamic property resolution remain unknown.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const createState = (
|
||||
program: t.Program,
|
||||
limits: JavaScriptSemanticLimits,
|
||||
): JavaScriptSemanticAnalysisState => {
|
||||
const root: JavaScriptSemanticScopeState = {
|
||||
scopeId: semanticScopeId("program", program),
|
||||
parentScopeId: null,
|
||||
kind: "program",
|
||||
location: range(program),
|
||||
bindingsComplete: true,
|
||||
bindings: new Map(),
|
||||
};
|
||||
return {
|
||||
limits,
|
||||
scopes: [root],
|
||||
scopesById: new Map([[root.scopeId, root]]),
|
||||
scopeByNode: new WeakMap([[program, root]]),
|
||||
bindingsById: new Map(),
|
||||
callables: [],
|
||||
moduleLinks: [],
|
||||
limitsReached: new Set(),
|
||||
omittedCount: 0,
|
||||
};
|
||||
};
|
||||
|
||||
const collectDefinitions = (
|
||||
program: t.Program,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const stack: JavaScriptSemanticScopeState[] = [
|
||||
currentSemanticScope(state.scopes),
|
||||
];
|
||||
const openedScopes = new WeakSet<t.Node>();
|
||||
traverseJavaScriptAst(program, {
|
||||
enter: (node, parent) => {
|
||||
const parentScope = currentSemanticScope(stack);
|
||||
bindOuterDeclaration(node, parentScope, state);
|
||||
const nested = nestedScope(node, parent, parentScope, state);
|
||||
if (nested !== undefined) {
|
||||
stack.push(nested);
|
||||
openedScopes.add(node);
|
||||
}
|
||||
const scope = currentSemanticScope(stack);
|
||||
state.scopeByNode.set(node, scope);
|
||||
collectSemanticCallable({
|
||||
node,
|
||||
parent,
|
||||
containerScope: parentScope,
|
||||
bodyScope: nested,
|
||||
state,
|
||||
});
|
||||
bindInnerDeclaration(node, parent, scope, state);
|
||||
collectSemanticModuleLink(node, state);
|
||||
},
|
||||
exit: (node) => {
|
||||
if (openedScopes.has(node)) stack.pop();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const bindOuterDeclaration = (
|
||||
node: t.Node,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
if (t.isFunctionDeclaration(node) && t.isIdentifier(node.id))
|
||||
addBinding({
|
||||
state,
|
||||
scope,
|
||||
name: node.id.name,
|
||||
kind: "function",
|
||||
mutable: false,
|
||||
definitionNode: node.id,
|
||||
initializer: node,
|
||||
});
|
||||
else if (t.isClassDeclaration(node) && t.isIdentifier(node.id))
|
||||
addBinding({
|
||||
state,
|
||||
scope,
|
||||
name: node.id.name,
|
||||
kind: "class",
|
||||
mutable: false,
|
||||
definitionNode: node.id,
|
||||
initializer: node,
|
||||
});
|
||||
};
|
||||
|
||||
const bindInnerDeclaration = (
|
||||
node: t.Node,
|
||||
parent: t.Node | null,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
if (t.isImportDeclaration(node)) bindImports(node, scope, state);
|
||||
else if (t.isVariableDeclarator(node))
|
||||
bindPattern({
|
||||
pattern: node.id,
|
||||
initializer: node.init ?? null,
|
||||
scope: variableScope(scope, parent, state),
|
||||
state,
|
||||
mutable:
|
||||
parent !== null && t.isVariableDeclaration(parent)
|
||||
? parent.kind !== "const"
|
||||
: true,
|
||||
});
|
||||
else if (t.isFunction(node)) bindFunctionLocals(node, scope, state);
|
||||
else if (t.isCatchClause(node) && node.param != null)
|
||||
bindPattern({
|
||||
pattern: node.param,
|
||||
initializer: null,
|
||||
scope,
|
||||
state,
|
||||
mutable: true,
|
||||
kind: "catch",
|
||||
});
|
||||
else if (t.isAssignmentExpression(node) && t.isIdentifier(node.left))
|
||||
addAssignment(node.left, node.right, scope, state);
|
||||
};
|
||||
|
||||
const nestedScope = (
|
||||
node: t.Node,
|
||||
parent: t.Node | null,
|
||||
parentScope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticScopeState | undefined => {
|
||||
const kind = scopeKind(node, parent);
|
||||
if (kind === undefined) return undefined;
|
||||
if (state.scopes.length >= state.limits.maxScopes) {
|
||||
reachSemanticLimit(state, "maxScopes");
|
||||
return {
|
||||
scopeId: `${semanticScopeId(kind, node)}:omitted`,
|
||||
parentScopeId: parentScope.scopeId,
|
||||
kind,
|
||||
location: range(node),
|
||||
bindingsComplete: false,
|
||||
bindings: new Map(),
|
||||
};
|
||||
}
|
||||
const scope: JavaScriptSemanticScopeState = {
|
||||
scopeId: semanticScopeId(kind, node),
|
||||
parentScopeId: parentScope.scopeId,
|
||||
kind,
|
||||
location: range(node),
|
||||
bindingsComplete: true,
|
||||
bindings: new Map(),
|
||||
};
|
||||
state.scopes.push(scope);
|
||||
state.scopesById.set(scope.scopeId, scope);
|
||||
return scope;
|
||||
};
|
||||
|
||||
const scopeKind = (
|
||||
node: t.Node,
|
||||
parent: t.Node | null,
|
||||
): JavaScriptSemanticScopeState["kind"] | undefined => {
|
||||
if (t.isFunction(node)) return "function";
|
||||
if (t.isClass(node)) return "class";
|
||||
if (t.isCatchClause(node)) return "catch";
|
||||
if (
|
||||
t.isBlockStatement(node) &&
|
||||
!(parent !== null && t.isFunction(parent) && parent.body === node)
|
||||
)
|
||||
return "block";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const bindImports = (
|
||||
node: t.ImportDeclaration,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
for (const specifier of node.specifiers) {
|
||||
const importedPath = t.isImportDefaultSpecifier(specifier)
|
||||
? ["default"]
|
||||
: t.isImportNamespaceSpecifier(specifier)
|
||||
? []
|
||||
: [propertyName(specifier.imported) || "[dynamic]"];
|
||||
addBinding({
|
||||
state,
|
||||
scope,
|
||||
name: specifier.local.name,
|
||||
kind: "import",
|
||||
mutable: false,
|
||||
definitionNode: specifier.local,
|
||||
initializer: null,
|
||||
directOrigin: { specifier: node.source.value, importedPath },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const bindFunctionLocals = (
|
||||
node: t.Function,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
if (t.isFunctionExpression(node) && t.isIdentifier(node.id))
|
||||
addBinding({
|
||||
state,
|
||||
scope,
|
||||
name: node.id.name,
|
||||
kind: "function",
|
||||
mutable: false,
|
||||
definitionNode: node.id,
|
||||
initializer: node,
|
||||
});
|
||||
for (const parameter of node.params)
|
||||
bindPattern({
|
||||
pattern: t.isTSParameterProperty(parameter)
|
||||
? parameter.parameter
|
||||
: parameter,
|
||||
initializer: null,
|
||||
scope,
|
||||
state,
|
||||
mutable: true,
|
||||
kind: "parameter",
|
||||
});
|
||||
};
|
||||
|
||||
const bindPattern = (input: BindPatternInput): void => {
|
||||
const {
|
||||
pattern,
|
||||
initializer,
|
||||
scope,
|
||||
state,
|
||||
mutable,
|
||||
kind = "variable",
|
||||
projection = [],
|
||||
} = input;
|
||||
if (t.isTSParameterProperty(pattern)) {
|
||||
bindPattern({ ...input, pattern: pattern.parameter });
|
||||
return;
|
||||
}
|
||||
if (t.isIdentifier(pattern)) {
|
||||
const baseOrigin = semanticModuleOrigin(initializer, []);
|
||||
const directOrigin =
|
||||
baseOrigin === undefined || projection.includes(null)
|
||||
? undefined
|
||||
: {
|
||||
...baseOrigin,
|
||||
importedPath: [
|
||||
...baseOrigin.importedPath,
|
||||
...projection.map((segment) => String(segment)),
|
||||
],
|
||||
};
|
||||
addBinding({
|
||||
state,
|
||||
scope,
|
||||
name: pattern.name,
|
||||
kind,
|
||||
mutable,
|
||||
definitionNode: pattern,
|
||||
initializer,
|
||||
...(directOrigin === undefined ? {} : { directOrigin }),
|
||||
projection,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (t.isAssignmentPattern(pattern)) {
|
||||
bindPattern({
|
||||
...input,
|
||||
pattern: pattern.left,
|
||||
initializer: initializer ?? pattern.right,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (t.isRestElement(pattern)) {
|
||||
bindPattern({
|
||||
...input,
|
||||
pattern: pattern.argument,
|
||||
initializer: null,
|
||||
mutable: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (t.isObjectPattern(pattern))
|
||||
for (const property of pattern.properties) {
|
||||
if (t.isRestElement(property))
|
||||
bindPattern({
|
||||
...input,
|
||||
pattern: property.argument,
|
||||
initializer: null,
|
||||
mutable: true,
|
||||
projection: [],
|
||||
});
|
||||
else {
|
||||
const name = semanticStaticPropertyName(
|
||||
property.key,
|
||||
property.computed,
|
||||
);
|
||||
bindPattern({
|
||||
...input,
|
||||
pattern: property.value,
|
||||
projection: [...projection, name === "" ? null : name],
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (t.isArrayPattern(pattern))
|
||||
pattern.elements.forEach((element, index) => {
|
||||
if (element !== null)
|
||||
bindPattern({
|
||||
...input,
|
||||
pattern: element,
|
||||
projection: [...projection, index],
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const addBinding = (input: AddBindingInput): void => {
|
||||
const {
|
||||
state,
|
||||
scope,
|
||||
name,
|
||||
kind,
|
||||
mutable,
|
||||
definitionNode,
|
||||
initializer,
|
||||
directOrigin,
|
||||
projection = [],
|
||||
} = input;
|
||||
let binding = scope.bindings.get(name);
|
||||
if (binding === undefined) {
|
||||
if (!scope.bindingsComplete) {
|
||||
state.omittedCount += 1;
|
||||
return;
|
||||
}
|
||||
if (state.bindingsById.size >= state.limits.maxBindings) {
|
||||
scope.bindingsComplete = false;
|
||||
reachSemanticLimit(state, "maxBindings");
|
||||
return;
|
||||
}
|
||||
binding = createBinding(scope, name, kind, mutable);
|
||||
scope.bindings.set(name, binding);
|
||||
state.bindingsById.set(binding.bindingId, binding);
|
||||
}
|
||||
binding.mutable ||= mutable;
|
||||
binding.definitions.push({ kind, location: range(definitionNode) });
|
||||
if (initializer !== null)
|
||||
binding.initializers.push({ node: initializer, projection });
|
||||
if (directOrigin !== undefined) binding.directOrigins.push(directOrigin);
|
||||
};
|
||||
|
||||
const createBinding = (
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
name: string,
|
||||
kind: JavaScriptSemanticDefinition["kind"],
|
||||
mutable: boolean,
|
||||
): JavaScriptSemanticBindingState => ({
|
||||
bindingId: `${scope.scopeId}:binding:${encodeURIComponent(name)}`,
|
||||
scopeId: scope.scopeId,
|
||||
name,
|
||||
kind,
|
||||
mutable,
|
||||
definitions: [],
|
||||
initializers: [],
|
||||
directOrigins: [],
|
||||
});
|
||||
|
||||
const addAssignment = (
|
||||
identifier: t.Identifier,
|
||||
initializer: t.Expression,
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const binding = resolveFromScope(scope, identifier.name, state);
|
||||
if (binding === undefined) return;
|
||||
binding.mutable = true;
|
||||
binding.definitions.push({ kind: "assignment", location: range(identifier) });
|
||||
binding.initializers.push({ node: initializer, projection: [] });
|
||||
};
|
||||
|
||||
const resolveFromScope = (
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
name: string,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticBindingState | undefined => {
|
||||
let candidate: JavaScriptSemanticScopeState | undefined = scope;
|
||||
while (candidate !== undefined) {
|
||||
const binding = candidate.bindings.get(name);
|
||||
if (binding !== undefined) return binding;
|
||||
if (!candidate.bindingsComplete) return undefined;
|
||||
candidate =
|
||||
candidate.parentScopeId === null
|
||||
? undefined
|
||||
: state.scopesById.get(candidate.parentScopeId);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const variableScope = (
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
parent: t.Node | null,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticScopeState => {
|
||||
if (!(parent !== null && t.isVariableDeclaration(parent, { kind: "var" })))
|
||||
return scope;
|
||||
let candidate = scope;
|
||||
while (candidate.kind === "block" || candidate.kind === "catch") {
|
||||
const outer =
|
||||
candidate.parentScopeId === null
|
||||
? undefined
|
||||
: state.scopesById.get(candidate.parentScopeId);
|
||||
if (outer === undefined) break;
|
||||
candidate = outer;
|
||||
}
|
||||
return candidate;
|
||||
};
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { JavaScriptSourceRange } from "./javascriptStaticAnalysisTypes.js";
|
||||
|
||||
/** Hard bounds for one execution-free JavaScript semantic analysis. */
|
||||
export interface JavaScriptSemanticLimits {
|
||||
readonly maxScopes: number;
|
||||
readonly maxBindings: number;
|
||||
readonly maxCallables: number;
|
||||
readonly maxReferences: number;
|
||||
readonly maxModuleLinks: number;
|
||||
readonly maxValueDepth: number;
|
||||
readonly maxUnionValues: number;
|
||||
readonly maxObjectProperties: number;
|
||||
}
|
||||
|
||||
/** Conservative defaults for one source file. */
|
||||
export const DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS: JavaScriptSemanticLimits = {
|
||||
maxScopes: 4_096,
|
||||
maxBindings: 20_000,
|
||||
maxCallables: 20_000,
|
||||
maxReferences: 100_000,
|
||||
maxModuleLinks: 20_000,
|
||||
maxValueDepth: 16,
|
||||
maxUnionValues: 32,
|
||||
maxObjectProperties: 256,
|
||||
};
|
||||
|
||||
/** Primitive values admitted into the bounded constant lattice. */
|
||||
export type JavaScriptSemanticPrimitive = string | number | boolean | null;
|
||||
|
||||
/** Bounded, execution-free value lattice for JavaScript expressions. */
|
||||
export type JavaScriptSemanticValue =
|
||||
| {
|
||||
readonly status: "literal";
|
||||
readonly value: JavaScriptSemanticPrimitive;
|
||||
}
|
||||
| {
|
||||
readonly status: "union";
|
||||
readonly values: readonly JavaScriptSemanticPrimitive[];
|
||||
}
|
||||
| {
|
||||
readonly status: "object";
|
||||
readonly properties: readonly JavaScriptSemanticProperty[];
|
||||
readonly unknownProperties: boolean;
|
||||
}
|
||||
| {
|
||||
readonly status: "array";
|
||||
readonly items: readonly JavaScriptSemanticValue[];
|
||||
readonly unknownItems: boolean;
|
||||
}
|
||||
| {
|
||||
readonly status: "unknown" | "ambiguous" | "cycle" | "limit-reached";
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** One statically named object-literal property. */
|
||||
export interface JavaScriptSemanticProperty {
|
||||
readonly name: string;
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
}
|
||||
|
||||
/** One exact module origin followed through imports, requires, or aliases. */
|
||||
export interface JavaScriptModuleOrigin {
|
||||
readonly specifier: string;
|
||||
readonly importedPath: readonly string[];
|
||||
}
|
||||
|
||||
/** Fail-closed provenance classification for one binding. */
|
||||
export interface JavaScriptBindingProvenance {
|
||||
readonly status:
|
||||
| "module"
|
||||
| "local"
|
||||
| "unknown"
|
||||
| "ambiguous"
|
||||
| "cycle"
|
||||
| "limit-reached";
|
||||
readonly origins: readonly JavaScriptModuleOrigin[];
|
||||
readonly reason: string | null;
|
||||
}
|
||||
|
||||
/** One lexical scope recovered without executing source. */
|
||||
export interface JavaScriptSemanticScope {
|
||||
readonly scopeId: string;
|
||||
readonly parentScopeId: string | null;
|
||||
readonly kind: "program" | "function" | "block" | "class" | "catch";
|
||||
readonly location: JavaScriptSourceRange;
|
||||
readonly bindingsComplete: boolean;
|
||||
readonly bindingIds: readonly string[];
|
||||
}
|
||||
|
||||
/** One declaration or assignment contributing to a binding. */
|
||||
export interface JavaScriptSemanticDefinition {
|
||||
readonly kind:
|
||||
| "import"
|
||||
| "variable"
|
||||
| "parameter"
|
||||
| "function"
|
||||
| "class"
|
||||
| "catch"
|
||||
| "assignment";
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One resolved lexical binding plus bounded value and provenance. */
|
||||
export interface JavaScriptSemanticBinding {
|
||||
readonly bindingId: string;
|
||||
readonly scopeId: string;
|
||||
readonly name: string;
|
||||
readonly kind: JavaScriptSemanticDefinition["kind"];
|
||||
readonly mutable: boolean;
|
||||
readonly definitions: readonly JavaScriptSemanticDefinition[];
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
readonly provenance: JavaScriptBindingProvenance;
|
||||
}
|
||||
|
||||
/** One identifier use and its fail-closed lexical resolution. */
|
||||
export interface JavaScriptSemanticReference {
|
||||
readonly name: string;
|
||||
readonly role: "read" | "write" | "export";
|
||||
readonly location: JavaScriptSourceRange;
|
||||
readonly bindingId: string | null;
|
||||
readonly resolution: "resolved" | "unbound" | "ambiguous" | "unknown";
|
||||
}
|
||||
|
||||
/** Function, class, or method identity without pretending it is a binding. */
|
||||
export interface JavaScriptSemanticCallable {
|
||||
readonly callableId: string;
|
||||
readonly kind: "function" | "class" | "method";
|
||||
readonly name: string | null;
|
||||
readonly containerScopeId: string;
|
||||
readonly bodyScopeId: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Static import/export relationship retained for cross-file composition. */
|
||||
export interface JavaScriptSemanticModuleLink {
|
||||
readonly kind:
|
||||
| "import"
|
||||
| "require"
|
||||
| "export"
|
||||
| "re-export"
|
||||
| "commonjs-export";
|
||||
readonly specifier: string | null;
|
||||
readonly importedName: string | null;
|
||||
readonly localName: string | null;
|
||||
readonly exportedName: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Coverage for bounded semantic recovery. */
|
||||
interface JavaScriptSemanticCoverage {
|
||||
readonly status: "complete" | "partial" | "truncated" | "failed";
|
||||
readonly omittedCount: number | null;
|
||||
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
|
||||
}
|
||||
|
||||
/** Provider-neutral JavaScript semantic IR v1. */
|
||||
export interface JavaScriptSemanticIr {
|
||||
readonly schema: "JavaScriptSemanticIR";
|
||||
readonly schemaVersion: 1;
|
||||
readonly scopes: readonly JavaScriptSemanticScope[];
|
||||
readonly bindings: readonly JavaScriptSemanticBinding[];
|
||||
readonly callables: readonly JavaScriptSemanticCallable[];
|
||||
readonly references: readonly JavaScriptSemanticReference[];
|
||||
readonly moduleLinks: readonly JavaScriptSemanticModuleLink[];
|
||||
readonly coverage: JavaScriptSemanticCoverage;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Find the innermost resolved reference at one source coordinate. */
|
||||
export const semanticReferenceAt = (
|
||||
ir: JavaScriptSemanticIr,
|
||||
line: number,
|
||||
column: number,
|
||||
): JavaScriptSemanticReference | undefined =>
|
||||
ir.references.find(
|
||||
({ location }) =>
|
||||
location.start.line === line && location.start.column === column,
|
||||
);
|
||||
|
||||
/** Read one binding by its deterministic semantic identifier. */
|
||||
export const semanticBinding = (
|
||||
ir: JavaScriptSemanticIr,
|
||||
bindingId: string,
|
||||
): JavaScriptSemanticBinding | undefined =>
|
||||
ir.bindings.find(({ bindingId: candidate }) => candidate === bindingId);
|
||||
|
||||
/** Fail-closed result when Babel cannot produce an inert syntax tree. */
|
||||
export const failedJavaScriptSemanticIr = (): JavaScriptSemanticIr => ({
|
||||
schema: "JavaScriptSemanticIR",
|
||||
schemaVersion: 1,
|
||||
scopes: [],
|
||||
bindings: [],
|
||||
callables: [],
|
||||
references: [],
|
||||
moduleLinks: [],
|
||||
coverage: { status: "failed", omittedCount: null, limitsReached: [] },
|
||||
limitations: [
|
||||
"JavaScript parsing failed; no semantic absence claim is available.",
|
||||
"No JavaScript was executed.",
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,480 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticBinding,
|
||||
JavaScriptSemanticModuleLink,
|
||||
JavaScriptSemanticReference,
|
||||
JavaScriptSemanticScope,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
semanticResolutionBlocked,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticScopeState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
evaluateSemanticBinding,
|
||||
evaluateSemanticProvenance,
|
||||
} from "./javascriptSemanticValues.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
range,
|
||||
stringValue,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
interface CollectCallableInput {
|
||||
readonly node: t.Node;
|
||||
readonly parent: t.Node | null;
|
||||
readonly containerScope: JavaScriptSemanticScopeState;
|
||||
readonly bodyScope: JavaScriptSemanticScopeState | undefined;
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
}
|
||||
|
||||
/** Retain callable identity without polluting lexical bindings. */
|
||||
export const collectSemanticCallable = (input: CollectCallableInput): void => {
|
||||
const { node, parent, containerScope, bodyScope, state } = input;
|
||||
const kind = callableKind(node);
|
||||
if (kind === undefined) return;
|
||||
if (state.callables.length >= state.limits.maxCallables) {
|
||||
reachSemanticLimit(state, "maxCallables");
|
||||
return;
|
||||
}
|
||||
state.callables.push({
|
||||
callableId: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
|
||||
kind,
|
||||
name: callableName(node, parent),
|
||||
containerScopeId: containerScope.scopeId,
|
||||
bodyScopeId:
|
||||
bodyScope === undefined || !bodyScope.bindingsComplete
|
||||
? null
|
||||
: bodyScope.scopeId,
|
||||
location: range(node),
|
||||
});
|
||||
};
|
||||
|
||||
/** Collect one static import/export relationship for later composition. */
|
||||
export const collectSemanticModuleLink = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): 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),
|
||||
});
|
||||
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",
|
||||
location: range(node),
|
||||
});
|
||||
else if (t.isVariableDeclarator(node)) collectRequireLink(node, state);
|
||||
else if (t.isAssignmentExpression(node)) collectCommonJsExport(node, state);
|
||||
};
|
||||
|
||||
/** Collect bounded lexical identifier references after definitions exist. */
|
||||
export const collectSemanticReferences = (
|
||||
program: t.Program,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticReference[] => {
|
||||
const output: JavaScriptSemanticReference[] = [];
|
||||
const seen = new Set<string>();
|
||||
traverseJavaScriptAst(program, {
|
||||
enter: (node, parent) => {
|
||||
if (!t.isIdentifier(node) || parent === null) return;
|
||||
const role = referenceRole(node, parent);
|
||||
if (role === null) return;
|
||||
const key = `${String(node.start)}:${role}:${node.name}`;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
if (output.length >= state.limits.maxReferences) {
|
||||
reachSemanticLimit(state, "maxReferences");
|
||||
return;
|
||||
}
|
||||
const binding = resolveSemanticBindingState(state, node, node.name);
|
||||
const blocked =
|
||||
binding === undefined &&
|
||||
semanticResolutionBlocked(state, node, node.name);
|
||||
output.push({
|
||||
name: node.name,
|
||||
role,
|
||||
location: range(node),
|
||||
bindingId: binding?.bindingId ?? null,
|
||||
resolution:
|
||||
binding !== undefined ? "resolved" : blocked ? "unknown" : "unbound",
|
||||
});
|
||||
},
|
||||
});
|
||||
return output;
|
||||
};
|
||||
|
||||
/** Freeze collected scopes into deterministic IR order. */
|
||||
export const immutableSemanticScopes = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticScope[] =>
|
||||
state.scopes.map((scope) => ({
|
||||
scopeId: scope.scopeId,
|
||||
parentScopeId: scope.parentScopeId,
|
||||
kind: scope.kind,
|
||||
location: scope.location,
|
||||
bindingsComplete: scope.bindingsComplete,
|
||||
bindingIds: [...scope.bindings.values()]
|
||||
.map(({ bindingId }) => bindingId)
|
||||
.sort(compareCodePoints),
|
||||
}));
|
||||
|
||||
/** Evaluate and freeze bindings into deterministic IR order. */
|
||||
export const immutableSemanticBindings = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticBinding[] =>
|
||||
[...state.bindingsById.values()]
|
||||
.map((binding) => ({
|
||||
bindingId: binding.bindingId,
|
||||
scopeId: binding.scopeId,
|
||||
name: binding.name,
|
||||
kind: binding.kind,
|
||||
mutable: binding.mutable,
|
||||
definitions: binding.definitions,
|
||||
value: evaluateSemanticBinding(binding, state),
|
||||
provenance: evaluateSemanticProvenance(binding, state),
|
||||
}))
|
||||
.sort((left, right) => compareCodePoints(left.bindingId, right.bindingId));
|
||||
|
||||
/** Recover a literal require origin plus an optional member chain. */
|
||||
export const semanticModuleOrigin = (
|
||||
node: t.Node | null | undefined,
|
||||
projection: readonly (string | number | null)[],
|
||||
): JavaScriptModuleOrigin | undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
const nested = t.isNode(node.object)
|
||||
? semanticModuleOrigin(node.object, projection)
|
||||
: undefined;
|
||||
const member = semanticStaticPropertyName(node.property, node.computed);
|
||||
return nested === undefined || member === ""
|
||||
? undefined
|
||||
: { ...nested, importedPath: [...nested.importedPath, member] };
|
||||
}
|
||||
if (
|
||||
!t.isCallExpression(node) ||
|
||||
!t.isIdentifier(node.callee, { name: "require" })
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(node.arguments[0]);
|
||||
return specifier === undefined || projection.includes(null)
|
||||
? undefined
|
||||
: {
|
||||
specifier,
|
||||
importedPath: projection.map((segment) => String(segment)),
|
||||
};
|
||||
};
|
||||
|
||||
/** Read a property only when its syntax commits an exact name. */
|
||||
export const semanticStaticPropertyName = (
|
||||
property: t.Node,
|
||||
computed: boolean,
|
||||
): string =>
|
||||
computed && !t.isStringLiteral(property) && !t.isNumericLiteral(property)
|
||||
? ""
|
||||
: propertyName(property);
|
||||
|
||||
/** Record one exact limit hit without inventing the total omitted population. */
|
||||
export const reachSemanticLimit = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: keyof JavaScriptSemanticAnalysisState["limits"],
|
||||
): void => {
|
||||
state.limitsReached.add(limit);
|
||||
state.omittedCount += 1;
|
||||
};
|
||||
|
||||
const callableKind = (
|
||||
node: t.Node,
|
||||
): "function" | "class" | "method" | undefined => {
|
||||
if (
|
||||
t.isClassMethod(node) ||
|
||||
t.isClassPrivateMethod(node) ||
|
||||
t.isObjectMethod(node)
|
||||
)
|
||||
return "method";
|
||||
if (t.isFunction(node)) return "function";
|
||||
if (t.isClass(node)) return "class";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const callableName = (node: t.Node, parent: t.Node | null): string | null => {
|
||||
if (
|
||||
(t.isFunctionDeclaration(node) ||
|
||||
t.isFunctionExpression(node) ||
|
||||
t.isClassDeclaration(node) ||
|
||||
t.isClassExpression(node)) &&
|
||||
t.isIdentifier(node.id)
|
||||
)
|
||||
return node.id.name;
|
||||
if (
|
||||
t.isClassMethod(node) ||
|
||||
t.isClassPrivateMethod(node) ||
|
||||
t.isObjectMethod(node)
|
||||
) {
|
||||
if (t.isPrivateName(node.key)) return `#${node.key.id.name}`;
|
||||
return propertyName(node.key) || `[computed@${String(node.start ?? -1)}]`;
|
||||
}
|
||||
if (
|
||||
parent !== null &&
|
||||
t.isVariableDeclarator(parent) &&
|
||||
t.isIdentifier(parent.id)
|
||||
)
|
||||
return parent.id.name;
|
||||
return null;
|
||||
};
|
||||
|
||||
const collectImports = (
|
||||
node: t.ImportDeclaration,
|
||||
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),
|
||||
});
|
||||
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),
|
||||
});
|
||||
};
|
||||
|
||||
const collectNamedExports = (
|
||||
node: t.ExportNamedDeclaration,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): 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,
|
||||
location: range(node.declaration),
|
||||
});
|
||||
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),
|
||||
});
|
||||
};
|
||||
|
||||
const collectRequireLink = (
|
||||
node: t.VariableDeclarator,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const origin = semanticModuleOrigin(node.init, []);
|
||||
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),
|
||||
});
|
||||
};
|
||||
|
||||
const requirePatternBindings = (
|
||||
pattern: t.Node,
|
||||
path: readonly string[],
|
||||
): { readonly importedName: string; readonly localName: string }[] => {
|
||||
if (t.isTSParameterProperty(pattern))
|
||||
return requirePatternBindings(pattern.parameter, path);
|
||||
if (t.isIdentifier(pattern))
|
||||
return [{ importedName: path.at(-1) ?? "*", localName: pattern.name }];
|
||||
if (t.isAssignmentPattern(pattern))
|
||||
return requirePatternBindings(pattern.left, path);
|
||||
if (t.isObjectPattern(pattern))
|
||||
return pattern.properties.flatMap((property) => {
|
||||
if (t.isRestElement(property)) return [];
|
||||
const name = semanticStaticPropertyName(property.key, property.computed);
|
||||
return name === ""
|
||||
? []
|
||||
: requirePatternBindings(property.value, [...path, name]);
|
||||
});
|
||||
if (t.isArrayPattern(pattern))
|
||||
return pattern.elements.flatMap((element, index) =>
|
||||
element === null
|
||||
? []
|
||||
: requirePatternBindings(element, [...path, String(index)]),
|
||||
);
|
||||
return [];
|
||||
};
|
||||
|
||||
const collectCommonJsExport = (
|
||||
node: t.AssignmentExpression,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const exportedName = commonJsExportName(node.left);
|
||||
if (exportedName === undefined) return;
|
||||
const origin = semanticModuleOrigin(node.right, []);
|
||||
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,
|
||||
location: range(node),
|
||||
});
|
||||
};
|
||||
|
||||
const addModuleLink = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
link: JavaScriptSemanticModuleLink,
|
||||
): void => {
|
||||
if (state.moduleLinks.length >= state.limits.maxModuleLinks) {
|
||||
reachSemanticLimit(state, "maxModuleLinks");
|
||||
return;
|
||||
}
|
||||
state.moduleLinks.push(link);
|
||||
};
|
||||
|
||||
const referenceRole = (
|
||||
node: t.Identifier,
|
||||
parent: t.Node,
|
||||
): JavaScriptSemanticReference["role"] | null => {
|
||||
if (isDeclarationIdentifier(node, parent) || isNonReferenceKey(node, parent))
|
||||
return null;
|
||||
if (
|
||||
(t.isAssignmentExpression(parent) && parent.left === node) ||
|
||||
t.isUpdateExpression(parent)
|
||||
)
|
||||
return "write";
|
||||
if (t.isExportSpecifier(parent) && parent.local === node) return "export";
|
||||
return "read";
|
||||
};
|
||||
|
||||
const isDeclarationIdentifier = (node: t.Identifier, parent: t.Node): boolean =>
|
||||
(t.isVariableDeclarator(parent) && patternContains(parent.id, node)) ||
|
||||
((t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) &&
|
||||
parent.id === node) ||
|
||||
(t.isFunction(parent) &&
|
||||
parent.params.some((value) => patternContains(value, node))) ||
|
||||
((t.isClassDeclaration(parent) || t.isClassExpression(parent)) &&
|
||||
parent.id === node) ||
|
||||
(t.isImportSpecifier(parent) &&
|
||||
(parent.local === node || parent.imported === node)) ||
|
||||
(t.isImportDefaultSpecifier(parent) && parent.local === node) ||
|
||||
(t.isImportNamespaceSpecifier(parent) && parent.local === node) ||
|
||||
(t.isCatchClause(parent) && parent.param === node);
|
||||
|
||||
const isNonReferenceKey = (node: t.Identifier, parent: t.Node): boolean =>
|
||||
((t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) &&
|
||||
parent.property === node &&
|
||||
!parent.computed) ||
|
||||
((t.isObjectProperty(parent) || t.isObjectMethod(parent)) &&
|
||||
parent.key === node &&
|
||||
!parent.computed &&
|
||||
!(t.isObjectProperty(parent) && parent.shorthand)) ||
|
||||
(t.isExportSpecifier(parent) && parent.exported === node) ||
|
||||
t.isLabeledStatement(parent) ||
|
||||
t.isBreakStatement(parent) ||
|
||||
t.isContinueStatement(parent);
|
||||
|
||||
const patternNames = (pattern: t.Node): string[] => {
|
||||
if (t.isTSParameterProperty(pattern)) return patternNames(pattern.parameter);
|
||||
if (t.isIdentifier(pattern)) return [pattern.name];
|
||||
if (t.isAssignmentPattern(pattern)) return patternNames(pattern.left);
|
||||
if (t.isRestElement(pattern)) return patternNames(pattern.argument);
|
||||
if (t.isObjectPattern(pattern))
|
||||
return pattern.properties.flatMap((property) =>
|
||||
t.isRestElement(property)
|
||||
? patternNames(property.argument)
|
||||
: patternNames(property.value),
|
||||
);
|
||||
if (t.isArrayPattern(pattern))
|
||||
return pattern.elements.flatMap((element) =>
|
||||
element === null ? [] : patternNames(element),
|
||||
);
|
||||
return [];
|
||||
};
|
||||
|
||||
const patternContains = (pattern: t.Node, target: t.Identifier): boolean =>
|
||||
pattern === target ||
|
||||
(t.isAssignmentPattern(pattern) && patternContains(pattern.left, target)) ||
|
||||
(t.isRestElement(pattern) && patternContains(pattern.argument, target)) ||
|
||||
(t.isObjectPattern(pattern) &&
|
||||
pattern.properties.some((property) =>
|
||||
t.isRestElement(property)
|
||||
? patternContains(property.argument, target)
|
||||
: patternContains(property.value, target),
|
||||
)) ||
|
||||
(t.isArrayPattern(pattern) &&
|
||||
pattern.elements.some(
|
||||
(element) => element !== null && patternContains(element, target),
|
||||
));
|
||||
|
||||
const declarationNames = (declaration: t.Declaration): string[] => {
|
||||
if (t.isVariableDeclaration(declaration))
|
||||
return declaration.declarations.flatMap(({ id }) => patternNames(id));
|
||||
if (
|
||||
(t.isFunctionDeclaration(declaration) ||
|
||||
t.isClassDeclaration(declaration)) &&
|
||||
t.isIdentifier(declaration.id)
|
||||
)
|
||||
return [declaration.id.name];
|
||||
return [];
|
||||
};
|
||||
|
||||
const defaultDeclarationName = (
|
||||
declaration: t.ExportDefaultDeclaration["declaration"],
|
||||
): string | null =>
|
||||
(t.isFunctionDeclaration(declaration) || t.isClassDeclaration(declaration)) &&
|
||||
t.isIdentifier(declaration.id)
|
||||
? declaration.id.name
|
||||
: null;
|
||||
|
||||
const commonJsExportName = (node: t.Node): string | undefined => {
|
||||
if (t.isIdentifier(node, { name: "exports" })) return "default";
|
||||
if (!t.isMemberExpression(node) && !t.isOptionalMemberExpression(node))
|
||||
return undefined;
|
||||
const name = propertyName(node.property);
|
||||
if (t.isIdentifier(node.object, { name: "exports" })) return name || "*";
|
||||
if (
|
||||
t.isMemberExpression(node.object) &&
|
||||
t.isIdentifier(node.object.object, { name: "module" }) &&
|
||||
propertyName(node.object.property) === "exports"
|
||||
)
|
||||
return name || "default";
|
||||
if (
|
||||
t.isIdentifier(node.object, { name: "module" }) &&
|
||||
propertyName(node.property) === "exports"
|
||||
)
|
||||
return "default";
|
||||
return undefined;
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import type * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticDefinition,
|
||||
JavaScriptSemanticLimits,
|
||||
JavaScriptSemanticModuleLink,
|
||||
JavaScriptSemanticCallable,
|
||||
JavaScriptSemanticScope,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
|
||||
/** Internal initializer plus a destructuring/member projection. */
|
||||
interface JavaScriptSemanticInitializer {
|
||||
readonly node: t.Node;
|
||||
readonly projection: readonly (string | number | null)[];
|
||||
}
|
||||
|
||||
/** Mutable binding state used only while constructing the immutable IR. */
|
||||
export interface JavaScriptSemanticBindingState {
|
||||
readonly bindingId: string;
|
||||
readonly scopeId: string;
|
||||
readonly name: string;
|
||||
kind: JavaScriptSemanticDefinition["kind"];
|
||||
mutable: boolean;
|
||||
readonly definitions: JavaScriptSemanticDefinition[];
|
||||
readonly initializers: JavaScriptSemanticInitializer[];
|
||||
readonly directOrigins: JavaScriptModuleOrigin[];
|
||||
}
|
||||
|
||||
/** Mutable lexical-scope state used only during AST recovery. */
|
||||
export interface JavaScriptSemanticScopeState {
|
||||
readonly scopeId: string;
|
||||
readonly parentScopeId: string | null;
|
||||
readonly kind: JavaScriptSemanticScope["kind"];
|
||||
readonly location: JavaScriptSemanticScope["location"];
|
||||
bindingsComplete: boolean;
|
||||
readonly bindings: Map<string, JavaScriptSemanticBindingState>;
|
||||
}
|
||||
|
||||
/** Shared bounded state for semantic collection and evaluation. */
|
||||
export interface JavaScriptSemanticAnalysisState {
|
||||
readonly limits: JavaScriptSemanticLimits;
|
||||
readonly scopes: JavaScriptSemanticScopeState[];
|
||||
readonly scopesById: Map<string, JavaScriptSemanticScopeState>;
|
||||
readonly scopeByNode: WeakMap<t.Node, JavaScriptSemanticScopeState>;
|
||||
readonly bindingsById: Map<string, JavaScriptSemanticBindingState>;
|
||||
readonly callables: JavaScriptSemanticCallable[];
|
||||
readonly moduleLinks: JavaScriptSemanticModuleLink[];
|
||||
readonly limitsReached: Set<keyof JavaScriptSemanticLimits>;
|
||||
omittedCount: number;
|
||||
}
|
||||
|
||||
/** Return the active scope from a non-empty construction stack. */
|
||||
export const currentSemanticScope = (
|
||||
stack: readonly JavaScriptSemanticScopeState[],
|
||||
): JavaScriptSemanticScopeState => {
|
||||
const scope = stack.at(-1);
|
||||
if (scope === undefined) throw new TypeError("Missing semantic scope");
|
||||
return scope;
|
||||
};
|
||||
|
||||
/** Create a stable source-position identity for one lexical scope. */
|
||||
export const semanticScopeId = (
|
||||
kind: JavaScriptSemanticScope["kind"],
|
||||
node: t.Node,
|
||||
): string =>
|
||||
`scope:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
|
||||
|
||||
/** Resolve one lexical name from the scope containing a node. */
|
||||
export const resolveSemanticBindingState = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
node: t.Node,
|
||||
name: string,
|
||||
): JavaScriptSemanticBindingState | undefined => {
|
||||
let scope = state.scopeByNode.get(node);
|
||||
while (scope !== undefined) {
|
||||
const binding = scope.bindings.get(name);
|
||||
if (binding !== undefined) return binding;
|
||||
if (!scope.bindingsComplete) return undefined;
|
||||
scope =
|
||||
scope.parentScopeId === null
|
||||
? undefined
|
||||
: state.scopesById.get(scope.parentScopeId);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Report whether an omitted binding scope blocks a trustworthy miss. */
|
||||
export const semanticResolutionBlocked = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
node: t.Node,
|
||||
name: string,
|
||||
): boolean => {
|
||||
let scope = state.scopeByNode.get(node);
|
||||
while (scope !== undefined) {
|
||||
if (scope.bindings.has(name)) return false;
|
||||
if (!scope.bindingsComplete) return true;
|
||||
scope =
|
||||
scope.parentScopeId === null
|
||||
? undefined
|
||||
: state.scopesById.get(scope.parentScopeId);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
/** Visit every Babel AST node in deterministic source-tree order. */
|
||||
export const traverseJavaScriptAst = (
|
||||
root: t.Node,
|
||||
visitor: {
|
||||
readonly enter: (node: t.Node, parent: t.Node | null) => void;
|
||||
readonly exit?: (node: t.Node, parent: t.Node | null) => void;
|
||||
},
|
||||
): void => {
|
||||
const visit = (node: t.Node, parent: t.Node | null): void => {
|
||||
visitor.enter(node, parent);
|
||||
for (const child of childNodes(node)) visit(child, node);
|
||||
visitor.exit?.(node, parent);
|
||||
};
|
||||
visit(root, null);
|
||||
};
|
||||
|
||||
const childNodes = (node: t.Node): t.Node[] => {
|
||||
const keys: readonly string[] = t.VISITOR_KEYS[node.type] ?? [];
|
||||
return keys.flatMap((key) => {
|
||||
const value: unknown = Reflect.get(node, key);
|
||||
if (t.isNode(value)) return [value];
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((item): item is t.Node => t.isNode(item));
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,529 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptBindingProvenance,
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticPrimitive,
|
||||
JavaScriptSemanticProperty,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticBindingState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
stringValue,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
interface EvaluationContext {
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
readonly bindings: ReadonlySet<string>;
|
||||
readonly depth: number;
|
||||
}
|
||||
|
||||
/** Evaluate one binding in the bounded constant-value lattice. */
|
||||
export const evaluateSemanticBinding = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticValue =>
|
||||
evaluateBinding(binding, { state, bindings: new Set(), depth: 0 });
|
||||
|
||||
/** Follow module provenance through destructuring, members, and aliases. */
|
||||
export const evaluateSemanticProvenance = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptBindingProvenance =>
|
||||
provenanceForBinding(binding, { state, bindings: new Set(), depth: 0 });
|
||||
|
||||
const evaluateBinding = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
if (context.bindings.has(binding.bindingId))
|
||||
return { status: "cycle", reason: `Alias cycle at ${binding.name}.` };
|
||||
if (context.depth >= context.state.limits.maxValueDepth)
|
||||
return limitValue(context.state, "maxValueDepth");
|
||||
if (binding.initializers.length === 0)
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: `Binding ${binding.name} has no constant initializer.`,
|
||||
};
|
||||
if (binding.initializers.length > 1)
|
||||
return {
|
||||
status: "ambiguous",
|
||||
reason: `Binding ${binding.name} has multiple possible assignments.`,
|
||||
};
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined)
|
||||
return { status: "unknown", reason: "Missing binding initializer." };
|
||||
const nested = nestedContext(context, binding.bindingId);
|
||||
return projectValue(
|
||||
evaluateExpression(initializer.node, nested),
|
||||
initializer.projection,
|
||||
);
|
||||
};
|
||||
|
||||
const evaluateExpression = (
|
||||
node: t.Node,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
if (context.depth >= context.state.limits.maxValueDepth)
|
||||
return limitValue(context.state, "maxValueDepth");
|
||||
const literal = primitiveValue(node);
|
||||
if (literal.found) return { status: "literal", value: literal.value };
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(context.state, node, node.name);
|
||||
return binding === undefined
|
||||
? { status: "unknown", reason: `Unbound identifier ${node.name}.` }
|
||||
: evaluateBinding(binding, nestedContext(context));
|
||||
}
|
||||
if (t.isTemplateLiteral(node)) return evaluateTemplate(node, context);
|
||||
if (t.isConditionalExpression(node))
|
||||
return mergeValues(
|
||||
[
|
||||
evaluateExpression(node.consequent, nestedContext(context)),
|
||||
evaluateExpression(node.alternate, nestedContext(context)),
|
||||
],
|
||||
context.state,
|
||||
);
|
||||
if (t.isLogicalExpression(node))
|
||||
return mergeValues(
|
||||
[
|
||||
evaluateExpression(node.left, nestedContext(context)),
|
||||
evaluateExpression(node.right, nestedContext(context)),
|
||||
],
|
||||
context.state,
|
||||
);
|
||||
if (t.isObjectExpression(node)) return evaluateObject(node, context);
|
||||
if (t.isArrayExpression(node)) return evaluateArray(node, context);
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node))
|
||||
return evaluateMember(node, context);
|
||||
if (t.isBinaryExpression(node, { operator: "+" }))
|
||||
return evaluateAddition(node, context);
|
||||
if (t.isUnaryExpression(node)) return evaluateUnary(node, context);
|
||||
if (
|
||||
(t.isTSAsExpression(node) ||
|
||||
t.isTSTypeAssertion(node) ||
|
||||
t.isTSNonNullExpression(node)) &&
|
||||
t.isExpression(node.expression)
|
||||
)
|
||||
return evaluateExpression(node.expression, nestedContext(context));
|
||||
return { status: "unknown", reason: `Unsupported ${node.type} value.` };
|
||||
};
|
||||
|
||||
const evaluateTemplate = (
|
||||
node: t.TemplateLiteral,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
let candidates = [""];
|
||||
for (let index = 0; index < node.quasis.length; index += 1) {
|
||||
const quasi = node.quasis[index];
|
||||
const text = quasi?.value.cooked ?? quasi?.value.raw ?? "";
|
||||
candidates = candidates.map((prefix) => `${prefix}${text}`);
|
||||
const expression = node.expressions[index];
|
||||
if (expression === undefined) continue;
|
||||
const values = primitiveCandidates(
|
||||
evaluateExpression(expression, nestedContext(context)),
|
||||
);
|
||||
if (values === null)
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: "Template expression is not a bounded primitive.",
|
||||
};
|
||||
candidates = candidates.flatMap((prefix) =>
|
||||
values.map((value) => `${prefix}${String(value)}`),
|
||||
);
|
||||
if (candidates.length > context.state.limits.maxUnionValues)
|
||||
return limitValue(context.state, "maxUnionValues");
|
||||
}
|
||||
return primitiveSet(candidates, context.state);
|
||||
};
|
||||
|
||||
const evaluateObject = (
|
||||
node: t.ObjectExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
const properties: JavaScriptSemanticProperty[] = [];
|
||||
let unknownProperties = false;
|
||||
for (const property of node.properties) {
|
||||
if (t.isSpreadElement(property) || property.computed) {
|
||||
unknownProperties = true;
|
||||
continue;
|
||||
}
|
||||
const name = propertyName(property.key);
|
||||
if (name === "" || !t.isObjectProperty(property)) {
|
||||
unknownProperties = true;
|
||||
continue;
|
||||
}
|
||||
if (properties.length >= context.state.limits.maxObjectProperties) {
|
||||
markLimit(context.state, "maxObjectProperties");
|
||||
unknownProperties = true;
|
||||
continue;
|
||||
}
|
||||
properties.push({
|
||||
name,
|
||||
value: evaluateExpression(property.value, nestedContext(context)),
|
||||
});
|
||||
}
|
||||
properties.sort((left, right) => compareCodePoints(left.name, right.name));
|
||||
return { status: "object", properties, unknownProperties };
|
||||
};
|
||||
|
||||
const evaluateArray = (
|
||||
node: t.ArrayExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
const items: JavaScriptSemanticValue[] = [];
|
||||
let unknownItems = false;
|
||||
for (const element of node.elements) {
|
||||
if (element === null || t.isSpreadElement(element)) {
|
||||
unknownItems = true;
|
||||
continue;
|
||||
}
|
||||
if (items.length >= context.state.limits.maxObjectProperties) {
|
||||
markLimit(context.state, "maxObjectProperties");
|
||||
unknownItems = true;
|
||||
continue;
|
||||
}
|
||||
items.push(evaluateExpression(element, nestedContext(context)));
|
||||
}
|
||||
return { status: "array", items, unknownItems };
|
||||
};
|
||||
|
||||
const evaluateMember = (
|
||||
node: t.MemberExpression | t.OptionalMemberExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
if (!t.isNode(node.object))
|
||||
return { status: "unknown", reason: "Unsupported member base." };
|
||||
const key = memberKey(node);
|
||||
if (key === undefined)
|
||||
return { status: "unknown", reason: "Dynamic member key." };
|
||||
return projectValue(evaluateExpression(node.object, nestedContext(context)), [
|
||||
key,
|
||||
]);
|
||||
};
|
||||
|
||||
const evaluateAddition = (
|
||||
node: t.BinaryExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
const left = primitiveCandidates(
|
||||
evaluateExpression(node.left, nestedContext(context)),
|
||||
);
|
||||
const right = primitiveCandidates(
|
||||
evaluateExpression(node.right, nestedContext(context)),
|
||||
);
|
||||
if (left === null || right === null)
|
||||
return { status: "unknown", reason: "Non-primitive addition." };
|
||||
const values = left.flatMap((leftValue) =>
|
||||
right.map((rightValue) =>
|
||||
typeof leftValue === "number" && typeof rightValue === "number"
|
||||
? leftValue + rightValue
|
||||
: `${String(leftValue)}${String(rightValue)}`,
|
||||
),
|
||||
);
|
||||
return primitiveSet(values, context.state);
|
||||
};
|
||||
|
||||
const evaluateUnary = (
|
||||
node: t.UnaryExpression,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptSemanticValue => {
|
||||
const argument = primitiveCandidates(
|
||||
evaluateExpression(node.argument, nestedContext(context)),
|
||||
);
|
||||
if (argument === null)
|
||||
return { status: "unknown", reason: "Non-primitive unary operand." };
|
||||
if (node.operator === "!")
|
||||
return primitiveSet(
|
||||
argument.map((value) => !value),
|
||||
context.state,
|
||||
);
|
||||
if (node.operator === "+")
|
||||
return primitiveSet(
|
||||
argument.map((value) => Number(value)),
|
||||
context.state,
|
||||
);
|
||||
if (node.operator === "-")
|
||||
return primitiveSet(
|
||||
argument.map((value) => -Number(value)),
|
||||
context.state,
|
||||
);
|
||||
return { status: "unknown", reason: `Unsupported unary ${node.operator}.` };
|
||||
};
|
||||
|
||||
const projectValue = (
|
||||
value: JavaScriptSemanticValue,
|
||||
projection: readonly (string | number | null)[],
|
||||
): JavaScriptSemanticValue => {
|
||||
let current = value;
|
||||
for (const key of projection) {
|
||||
if (key === null)
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: "Cannot project a dynamic property.",
|
||||
};
|
||||
if (current.status === "object" && typeof key === "string") {
|
||||
const property = current.properties.find(({ name }) => name === key);
|
||||
if (property === undefined)
|
||||
return {
|
||||
status: current.unknownProperties ? "unknown" : "unknown",
|
||||
reason: `Object property ${key} was not observed.`,
|
||||
};
|
||||
current = property.value;
|
||||
} else if (current.status === "array" && typeof key === "number") {
|
||||
const item = current.items[key];
|
||||
if (item === undefined)
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: `Array item ${String(key)} missing.`,
|
||||
};
|
||||
current = item;
|
||||
} else
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: `Cannot project ${String(key)} from ${current.status}.`,
|
||||
};
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
const provenanceForBinding = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptBindingProvenance => {
|
||||
if (context.bindings.has(binding.bindingId))
|
||||
return provenance("cycle", [], `Alias cycle at ${binding.name}.`);
|
||||
if (context.depth >= context.state.limits.maxValueDepth)
|
||||
return limitProvenance(context.state, "maxValueDepth");
|
||||
if (binding.directOrigins.length > 0)
|
||||
return originsProvenance(binding.directOrigins, context.state);
|
||||
if (binding.initializers.length === 0) return provenance("local", [], null);
|
||||
if (binding.initializers.length > 1)
|
||||
return provenance(
|
||||
"ambiguous",
|
||||
[],
|
||||
`Binding ${binding.name} has multiple possible assignments.`,
|
||||
);
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined)
|
||||
return provenance("unknown", [], "Missing binding initializer.");
|
||||
if (initializer.projection.includes(null))
|
||||
return provenance("unknown", [], "Dynamic provenance projection.");
|
||||
const resolved = provenanceForExpression(
|
||||
initializer.node,
|
||||
nestedContext(context, binding.bindingId),
|
||||
);
|
||||
if (resolved.status !== "module" || initializer.projection.length === 0)
|
||||
return resolved;
|
||||
return originsProvenance(
|
||||
resolved.origins.map((origin) => ({
|
||||
...origin,
|
||||
importedPath: [
|
||||
...origin.importedPath,
|
||||
...initializer.projection.map((segment) => String(segment)),
|
||||
],
|
||||
})),
|
||||
context.state,
|
||||
);
|
||||
};
|
||||
|
||||
const provenanceForExpression = (
|
||||
node: t.Node,
|
||||
context: EvaluationContext,
|
||||
): JavaScriptBindingProvenance => {
|
||||
const required = requireOrigin(node);
|
||||
if (required !== undefined)
|
||||
return originsProvenance([required], context.state);
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(context.state, node, node.name);
|
||||
return binding === undefined
|
||||
? provenance("unknown", [], `Unbound identifier ${node.name}.`)
|
||||
: provenanceForBinding(binding, nestedContext(context));
|
||||
}
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object))
|
||||
return provenance("unknown", [], "Unsupported member base.");
|
||||
const member = memberKey(node);
|
||||
if (typeof member !== "string")
|
||||
return provenance("unknown", [], "Dynamic provenance member.");
|
||||
const base = provenanceForExpression(node.object, nestedContext(context));
|
||||
return base.status !== "module"
|
||||
? base
|
||||
: originsProvenance(
|
||||
base.origins.map((origin) => ({
|
||||
...origin,
|
||||
importedPath: [...origin.importedPath, member],
|
||||
})),
|
||||
context.state,
|
||||
);
|
||||
}
|
||||
if (t.isConditionalExpression(node) || t.isLogicalExpression(node)) {
|
||||
const left = t.isConditionalExpression(node) ? node.consequent : node.left;
|
||||
const right = t.isConditionalExpression(node) ? node.alternate : node.right;
|
||||
const candidates = [
|
||||
provenanceForExpression(left, nestedContext(context)),
|
||||
provenanceForExpression(right, nestedContext(context)),
|
||||
];
|
||||
const origins = candidates.flatMap((candidate) => candidate.origins);
|
||||
return origins.length > 0
|
||||
? provenance(
|
||||
"ambiguous",
|
||||
uniqueOrigins(origins),
|
||||
"Multiple module origins.",
|
||||
)
|
||||
: provenance("unknown", [], "Conditional provenance is unresolved.");
|
||||
}
|
||||
return provenance("local", [], null);
|
||||
};
|
||||
|
||||
const requireOrigin = (node: t.Node): JavaScriptModuleOrigin | undefined => {
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object)) return undefined;
|
||||
const nested = requireOrigin(node.object);
|
||||
const member = memberKey(node);
|
||||
return nested === undefined || typeof member !== "string"
|
||||
? undefined
|
||||
: { ...nested, importedPath: [...nested.importedPath, member] };
|
||||
}
|
||||
if (
|
||||
!t.isCallExpression(node) ||
|
||||
!t.isIdentifier(node.callee, { name: "require" })
|
||||
)
|
||||
return undefined;
|
||||
const specifier = stringValue(node.arguments[0]);
|
||||
return specifier === undefined ? undefined : { specifier, importedPath: [] };
|
||||
};
|
||||
|
||||
const mergeValues = (
|
||||
values: readonly JavaScriptSemanticValue[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticValue => {
|
||||
const primitives = values.flatMap(
|
||||
(value) => primitiveCandidates(value) ?? [],
|
||||
);
|
||||
return primitives.length === values.length ||
|
||||
values.every(
|
||||
(value) => value.status === "union" || value.status === "literal",
|
||||
)
|
||||
? primitiveSet(primitives, state)
|
||||
: { status: "ambiguous", reason: "Branches have incompatible values." };
|
||||
};
|
||||
|
||||
const primitiveSet = (
|
||||
values: readonly JavaScriptSemanticPrimitive[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticValue => {
|
||||
const unique = [
|
||||
...new Map(values.map((value) => [primitiveKey(value), value])).values(),
|
||||
].sort((left, right) =>
|
||||
compareCodePoints(primitiveKey(left), primitiveKey(right)),
|
||||
);
|
||||
if (unique.length > state.limits.maxUnionValues)
|
||||
return limitValue(state, "maxUnionValues");
|
||||
const only = unique[0];
|
||||
return unique.length === 1 && only !== undefined
|
||||
? { status: "literal", value: only }
|
||||
: { status: "union", values: unique };
|
||||
};
|
||||
|
||||
const primitiveCandidates = (
|
||||
value: JavaScriptSemanticValue,
|
||||
): readonly JavaScriptSemanticPrimitive[] | null =>
|
||||
value.status === "literal"
|
||||
? [value.value]
|
||||
: value.status === "union"
|
||||
? value.values
|
||||
: null;
|
||||
|
||||
const primitiveValue = (
|
||||
node: t.Node,
|
||||
):
|
||||
| { readonly found: true; readonly value: JavaScriptSemanticPrimitive }
|
||||
| { readonly found: false } => {
|
||||
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
|
||||
return { found: true, value: node.value };
|
||||
if (t.isBooleanLiteral(node)) return { found: true, value: node.value };
|
||||
if (t.isNullLiteral(node)) return { found: true, value: null };
|
||||
return { found: false };
|
||||
};
|
||||
|
||||
const memberKey = (
|
||||
node: t.MemberExpression | t.OptionalMemberExpression,
|
||||
): string | number | undefined => {
|
||||
if (!node.computed) return propertyName(node.property) || undefined;
|
||||
if (t.isStringLiteral(node.property) || t.isNumericLiteral(node.property))
|
||||
return node.property.value;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const originsProvenance = (
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptBindingProvenance => {
|
||||
const unique = uniqueOrigins(origins);
|
||||
if (unique.length > state.limits.maxUnionValues)
|
||||
return limitProvenance(state, "maxUnionValues");
|
||||
return unique.length === 1
|
||||
? provenance("module", unique, null)
|
||||
: provenance("ambiguous", unique, "Multiple module origins.");
|
||||
};
|
||||
|
||||
const uniqueOrigins = (
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
): JavaScriptModuleOrigin[] =>
|
||||
[
|
||||
...new Map(origins.map((origin) => [originKey(origin), origin])).values(),
|
||||
].sort((left, right) => compareCodePoints(originKey(left), originKey(right)));
|
||||
|
||||
const provenance = (
|
||||
status: JavaScriptBindingProvenance["status"],
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
reason: string | null,
|
||||
): JavaScriptBindingProvenance => ({ status, origins, reason });
|
||||
|
||||
const limitValue = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: "maxValueDepth" | "maxUnionValues",
|
||||
): JavaScriptSemanticValue => {
|
||||
markLimit(state, limit);
|
||||
return { status: "limit-reached", reason: `${limit} reached.` };
|
||||
};
|
||||
|
||||
const limitProvenance = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: "maxValueDepth" | "maxUnionValues",
|
||||
): JavaScriptBindingProvenance => {
|
||||
markLimit(state, limit);
|
||||
return provenance("limit-reached", [], `${limit} reached.`);
|
||||
};
|
||||
|
||||
const markLimit = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: keyof JavaScriptSemanticAnalysisState["limits"],
|
||||
): void => {
|
||||
state.limitsReached.add(limit);
|
||||
state.omittedCount += 1;
|
||||
};
|
||||
|
||||
const nestedContext = (
|
||||
context: EvaluationContext,
|
||||
bindingId?: string,
|
||||
): EvaluationContext => ({
|
||||
state: context.state,
|
||||
depth: context.depth + 1,
|
||||
bindings:
|
||||
bindingId === undefined
|
||||
? context.bindings
|
||||
: new Set([...context.bindings, bindingId]),
|
||||
});
|
||||
|
||||
const primitiveKey = (value: JavaScriptSemanticPrimitive): string =>
|
||||
`${value === null ? "null" : typeof value}:${JSON.stringify(value)}`;
|
||||
|
||||
const originKey = (origin: JavaScriptModuleOrigin): string =>
|
||||
`${origin.specifier}\0${origin.importedPath.join("\0")}`;
|
||||
Reference in New Issue
Block a user