feat: complete REA remediation program
This commit is contained in:
@@ -304,7 +304,13 @@ const providerErrorDetails = (
|
||||
if (error instanceof HopperRemoteError)
|
||||
return { provider_code: error.code, diagnostic_type: error.diagnosticType };
|
||||
if (error instanceof HopperProcessError && error.failureCode !== undefined)
|
||||
return { failure_code: error.failureCode, exit_code: error.exitCode };
|
||||
return {
|
||||
failure_code: error.failureCode,
|
||||
exit_code: error.exitCode,
|
||||
...(error.diagnostic === undefined
|
||||
? {}
|
||||
: { diagnostics: { ...error.diagnostic } }),
|
||||
};
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
+10
-2
@@ -6,9 +6,14 @@ import type {
|
||||
} from "./permissionPolicy.js";
|
||||
import {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupDiagnostic,
|
||||
type HopperStartupFailureCode,
|
||||
} from "./hopperStartupFailure.js";
|
||||
export { hopperStartupFailure, type HopperStartupFailureCode };
|
||||
export {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupDiagnostic,
|
||||
type HopperStartupFailureCode,
|
||||
};
|
||||
export { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
|
||||
/** Stable tags exposed by safe analysis-error projections. */
|
||||
@@ -457,7 +462,10 @@ export class HopperProcessError extends HopperError {
|
||||
readonly failureCode: HopperStartupFailureCode | undefined;
|
||||
override readonly userMessage: string | undefined;
|
||||
|
||||
constructor(readonly exitCode: number | null) {
|
||||
constructor(
|
||||
readonly exitCode: number | null,
|
||||
readonly diagnostic?: HopperStartupDiagnostic,
|
||||
) {
|
||||
super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`);
|
||||
const failure = hopperStartupFailure(exitCode);
|
||||
this.failureCode = failure?.code;
|
||||
|
||||
@@ -8,7 +8,33 @@ export type HopperStartupFailureCode =
|
||||
| "unsupported_demo_dialog"
|
||||
| "unexpected_display_geometry"
|
||||
| "x11_input_failed"
|
||||
| "runtime_dependency_unavailable";
|
||||
| "runtime_dependency_unavailable"
|
||||
| "x11_socket_directory_unusable";
|
||||
|
||||
export type HopperPrivateDisplayStrategy =
|
||||
| "direct"
|
||||
| "user-mount-namespace"
|
||||
| "unavailable";
|
||||
|
||||
/** Bounded, non-secret facts emitted by the Linux private-display adapter. */
|
||||
export interface HopperStartupDiagnostic {
|
||||
readonly schema_version: 1;
|
||||
readonly component: "hopper_private_display";
|
||||
readonly operation: "probe" | "launch";
|
||||
readonly status: "ready" | "error";
|
||||
readonly failure_code: HopperStartupFailureCode | null;
|
||||
readonly reason: string;
|
||||
readonly socket_directory: "/tmp/.X11-unix";
|
||||
readonly socket_directory_mode: string | null;
|
||||
readonly mount_read_only: boolean | null;
|
||||
readonly effective_socket_directory_mode: string | null;
|
||||
readonly effective_mount_read_only: boolean | null;
|
||||
readonly wsl: boolean;
|
||||
readonly strategy: HopperPrivateDisplayStrategy;
|
||||
readonly fallback_reason: string | null;
|
||||
readonly xvfb_stderr_bytes: number;
|
||||
readonly xvfb_stderr_truncated: boolean;
|
||||
}
|
||||
|
||||
const failures = [
|
||||
[
|
||||
@@ -61,6 +87,11 @@ const failures = [
|
||||
"runtime_dependency_unavailable",
|
||||
"A Linux demo-session dependency is unavailable. Rerun rea setup --yes --install-hopper, then rea doctor.",
|
||||
],
|
||||
[
|
||||
80,
|
||||
"x11_socket_directory_unusable",
|
||||
"REA cannot use the host X11 socket directory for a private display. Run rea doctor --provider hopper for exact mount and namespace diagnostics.",
|
||||
],
|
||||
] as const;
|
||||
|
||||
const HOPPER_STARTUP_FAILURES = new Map<
|
||||
@@ -71,3 +102,15 @@ const HOPPER_STARTUP_FAILURES = new Map<
|
||||
/** Return the stable public failure associated with a Linux demo adapter exit. */
|
||||
export const hopperStartupFailure = (exitCode: number | null) =>
|
||||
exitCode === null ? undefined : HOPPER_STARTUP_FAILURES.get(exitCode);
|
||||
|
||||
/** Return the adapter exit associated with one stable startup failure code. */
|
||||
export const hopperStartupExitCode = (
|
||||
code: HopperStartupFailureCode,
|
||||
): number | undefined =>
|
||||
failures.find(([, candidate]) => candidate === code)?.[0];
|
||||
|
||||
/** Narrow an untrusted diagnostic field to the public startup code union. */
|
||||
export const isHopperStartupFailureCode = (
|
||||
value: string,
|
||||
): value is HopperStartupFailureCode =>
|
||||
failures.some(([, candidate]) => candidate === value);
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { compareCodePoints } from "./javascriptApplicationGraph.js";
|
||||
import { digestExportShapeValue } from "./javascriptExportShapeComparisonIdentity.js";
|
||||
import {
|
||||
javaScriptExportShapeComparisonResultSchema,
|
||||
type CompareJavaScriptExportShapesInput,
|
||||
type JavaScriptExportShapeComparisonChange,
|
||||
type JavaScriptExportShapeComparisonResult,
|
||||
} from "./javascriptExportShapeComparisonSchemas.js";
|
||||
import {
|
||||
retainJavaScriptExportShapes,
|
||||
selectJavaScriptExport,
|
||||
type JavaScriptExportShapeSideInput,
|
||||
type RetainedJavaScriptExportShapes,
|
||||
type SelectedJavaScriptExport,
|
||||
} from "./javascriptExportShapeSelection.js";
|
||||
import {
|
||||
buildJavaScriptExportShapeChanges,
|
||||
compareJavaScriptExportShapeChanges,
|
||||
hasPartialJavaScriptExportPropertyCoverage,
|
||||
pairJavaScriptExportShapeVariants,
|
||||
type JavaScriptExportShapePairing,
|
||||
} from "./javascriptExportShapeVariants.js";
|
||||
|
||||
/** Pure comparison input after application-layer Evidence authentication. */
|
||||
export interface JavaScriptExportShapeComparisonProjectionInput {
|
||||
readonly left: JavaScriptExportShapeSideInput;
|
||||
readonly right: JavaScriptExportShapeSideInput;
|
||||
readonly limits: CompareJavaScriptExportShapesInput["limits"];
|
||||
}
|
||||
|
||||
/** Compare exact selected export return shapes without executing JavaScript. */
|
||||
export const compareJavaScriptExportShapes = (
|
||||
input: JavaScriptExportShapeComparisonProjectionInput,
|
||||
): JavaScriptExportShapeComparisonResult => {
|
||||
const left = selectJavaScriptExport(
|
||||
input.left,
|
||||
input.limits.max_candidate_exports,
|
||||
);
|
||||
const right = selectJavaScriptExport(
|
||||
input.right,
|
||||
input.limits.max_candidate_exports,
|
||||
);
|
||||
const leftRetained = retainJavaScriptExportShapes(
|
||||
left,
|
||||
input.limits.max_return_variants,
|
||||
);
|
||||
const rightRetained = retainJavaScriptExportShapes(
|
||||
right,
|
||||
input.limits.max_return_variants,
|
||||
);
|
||||
const pairing = pairJavaScriptExportShapeVariants(
|
||||
leftRetained.shapes,
|
||||
rightRetained.shapes,
|
||||
);
|
||||
const evidenceLinks = evidencePair(
|
||||
input.left.evidenceId,
|
||||
input.right.evidenceId,
|
||||
);
|
||||
const allChanges = buildJavaScriptExportShapeChanges({
|
||||
leftSelection: left,
|
||||
rightSelection: right,
|
||||
pairing,
|
||||
leftShapes: leftRetained.shapes,
|
||||
rightShapes: rightRetained.shapes,
|
||||
evidenceLinks,
|
||||
}).sort(compareJavaScriptExportShapeChanges);
|
||||
const changes = allChanges.slice(0, input.limits.max_changes);
|
||||
const omittedChanges = allChanges.length - changes.length;
|
||||
const coverage = comparisonCoverage({
|
||||
input,
|
||||
left,
|
||||
right,
|
||||
leftRetained,
|
||||
rightRetained,
|
||||
pairing,
|
||||
allChanges,
|
||||
omittedChanges,
|
||||
});
|
||||
const limitations = comparisonLimitations(left, right, coverage.status);
|
||||
const semantic = {
|
||||
schema_version: 1 as const,
|
||||
left: left.selection,
|
||||
right: right.selection,
|
||||
summary: summarize(allChanges),
|
||||
changes,
|
||||
coverage,
|
||||
evidence_links: evidenceLinks,
|
||||
limitations,
|
||||
runtime_validation: {
|
||||
recommended_tool: "run_controlled_replay" as const,
|
||||
automatically_started: false as const,
|
||||
required_for: "runtime-semantics" as const,
|
||||
},
|
||||
};
|
||||
return javaScriptExportShapeComparisonResultSchema.parse({
|
||||
...semantic,
|
||||
comparison_id: `jesc_${digestExportShapeValue(semantic)}`,
|
||||
});
|
||||
};
|
||||
|
||||
interface CoverageInput {
|
||||
readonly input: JavaScriptExportShapeComparisonProjectionInput;
|
||||
readonly left: SelectedJavaScriptExport;
|
||||
readonly right: SelectedJavaScriptExport;
|
||||
readonly leftRetained: RetainedJavaScriptExportShapes;
|
||||
readonly rightRetained: RetainedJavaScriptExportShapes;
|
||||
readonly pairing: JavaScriptExportShapePairing;
|
||||
readonly allChanges: readonly JavaScriptExportShapeComparisonChange[];
|
||||
readonly omittedChanges: number;
|
||||
}
|
||||
|
||||
const comparisonCoverage = (context: CoverageInput) => {
|
||||
const leftSource = context.left.projection?.return_shape_coverage;
|
||||
const rightSource = context.right.projection?.return_shape_coverage;
|
||||
const omittedCandidates =
|
||||
context.left.selection.omitted_candidates +
|
||||
context.right.selection.omitted_candidates;
|
||||
const truncated = comparisonTruncated(context, omittedCandidates);
|
||||
const partial = comparisonPartial(context);
|
||||
return {
|
||||
status: truncated
|
||||
? ("truncated" as const)
|
||||
: partial
|
||||
? ("partial" as const)
|
||||
: ("complete-within-inputs" as const),
|
||||
left_graph_status: context.input.left.graph.coverage.status,
|
||||
right_graph_status: context.input.right.graph.coverage.status,
|
||||
paired_variants: context.pairing.pairs.length,
|
||||
unpaired_left_variants: context.pairing.unpairedLeft.length,
|
||||
unpaired_right_variants: context.pairing.unpairedRight.length,
|
||||
omitted_left_variants: context.leftRetained.omitted,
|
||||
omitted_right_variants: context.rightRetained.omitted,
|
||||
left_source_omitted_variants: leftSource?.omitted_return_sites ?? null,
|
||||
right_source_omitted_variants: rightSource?.omitted_return_sites ?? null,
|
||||
left_omitted_fields: leftSource?.omitted_fields ?? 0,
|
||||
right_omitted_fields: rightSource?.omitted_fields ?? 0,
|
||||
left_omitted_property_coverage: leftSource?.omitted_property_coverage ?? 0,
|
||||
right_omitted_property_coverage:
|
||||
rightSource?.omitted_property_coverage ?? 0,
|
||||
omitted_candidates: omittedCandidates,
|
||||
omitted_changes: context.omittedChanges,
|
||||
};
|
||||
};
|
||||
|
||||
const comparisonTruncated = (
|
||||
context: CoverageInput,
|
||||
omittedCandidates: number,
|
||||
): boolean =>
|
||||
context.leftRetained.omitted > 0 ||
|
||||
context.rightRetained.omitted > 0 ||
|
||||
omittedCandidates > 0 ||
|
||||
context.omittedChanges > 0 ||
|
||||
sourceProjectionTruncated(context.left) ||
|
||||
sourceProjectionTruncated(context.right);
|
||||
|
||||
const sourceProjectionTruncated = (
|
||||
selection: SelectedJavaScriptExport,
|
||||
): boolean => {
|
||||
const coverage = selection.projection?.return_shape_coverage;
|
||||
if (coverage === undefined) return false;
|
||||
return (
|
||||
coverage.status === "truncated" ||
|
||||
coverage.omitted_fields > 0 ||
|
||||
coverage.omitted_property_coverage > 0 ||
|
||||
coverage.projection_complete === false
|
||||
);
|
||||
};
|
||||
|
||||
const comparisonPartial = (context: CoverageInput): boolean =>
|
||||
selectionPartial(context.left) ||
|
||||
selectionPartial(context.right) ||
|
||||
context.input.left.graph.coverage.status !== "complete" ||
|
||||
context.input.right.graph.coverage.status !== "complete" ||
|
||||
hasPartialJavaScriptExportPropertyCoverage(context.leftRetained.shapes) ||
|
||||
hasPartialJavaScriptExportPropertyCoverage(context.rightRetained.shapes) ||
|
||||
context.pairing.unpairedLeft.length > 0 ||
|
||||
context.pairing.unpairedRight.length > 0 ||
|
||||
context.allChanges.some(({ status }) => status === "unknown");
|
||||
|
||||
const selectionPartial = (selection: SelectedJavaScriptExport): boolean => {
|
||||
const coverage = selection.projection?.return_shape_coverage;
|
||||
return (
|
||||
selection.selection.status !== "selected" ||
|
||||
!selection.observationComplete ||
|
||||
coverage?.status !== "complete" ||
|
||||
coverage.projection_complete !== true
|
||||
);
|
||||
};
|
||||
|
||||
const comparisonLimitations = (
|
||||
left: SelectedJavaScriptExport,
|
||||
right: SelectedJavaScriptExport,
|
||||
status: "complete-within-inputs" | "partial" | "truncated",
|
||||
): string[] =>
|
||||
uniqueSorted([
|
||||
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
|
||||
"Return variants are paired only by unique exact literal discriminants, never by source order.",
|
||||
"Dynamic values, incomplete object coverage, and ambiguous variants remain unknown.",
|
||||
"Controlled replay is recommended separately for runtime semantics and was not started.",
|
||||
...left.limitations,
|
||||
...right.limitations,
|
||||
...(status === "truncated"
|
||||
? [
|
||||
"Comparison output or source return-shape recovery reached an explicit limit.",
|
||||
]
|
||||
: []),
|
||||
...(status === "partial"
|
||||
? [
|
||||
"At least one selector, graph, return shape, or property boundary is incomplete.",
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
|
||||
const summarize = (
|
||||
changes: readonly JavaScriptExportShapeComparisonChange[],
|
||||
): JavaScriptExportShapeComparisonResult["summary"] => ({
|
||||
added: countStatus(changes, "added"),
|
||||
removed: countStatus(changes, "removed"),
|
||||
changed: countStatus(changes, "changed"),
|
||||
unknown: countStatus(changes, "unknown"),
|
||||
});
|
||||
|
||||
const countStatus = (
|
||||
changes: readonly JavaScriptExportShapeComparisonChange[],
|
||||
status: JavaScriptExportShapeComparisonChange["status"],
|
||||
): number => changes.filter((change) => change.status === status).length;
|
||||
|
||||
const evidencePair = (left: string, right: string): [string, string] => [
|
||||
left,
|
||||
right,
|
||||
];
|
||||
|
||||
const uniqueSorted = <Value extends string>(
|
||||
values: readonly Value[],
|
||||
): Value[] => [...new Set(values)].sort(compareCodePoints);
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
/** Canonically encode one export-shape comparison value. */
|
||||
export const canonicalExportShapeValue = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError(
|
||||
"JavaScript export shape comparison could not canonicalize data",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/** Derive one deterministic SHA-256 comparison identifier component. */
|
||||
export const digestExportShapeValue = (value: unknown): string =>
|
||||
createHash("sha256").update(canonicalExportShapeValue(value)).digest("hex");
|
||||
@@ -0,0 +1,308 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceSchema } from "./evidence.js";
|
||||
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const graphIdSchema = z.string().regex(/^jag_[a-f0-9]{64}$/u);
|
||||
const nodeIdSchema = z.string().regex(/^jag_node_[a-f0-9]{64}$/u);
|
||||
const boundedTextSchema = z.string().min(1).max(4_096);
|
||||
const selectorTextSchema = z.string().min(1).max(4_096);
|
||||
const semanticPrimitiveSchema = z.union([
|
||||
z.string().max(4_096),
|
||||
z.number().finite(),
|
||||
z.boolean(),
|
||||
z.null(),
|
||||
]);
|
||||
|
||||
function isJsonPointer(value: string): boolean {
|
||||
if (value === "") return true;
|
||||
if (!value.startsWith("/")) return false;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
if (value[index] !== "~") continue;
|
||||
const escaped = value[index + 1];
|
||||
if (escaped !== "0" && escaped !== "1") return false;
|
||||
index += 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const jsonPointerSchema = z
|
||||
.string()
|
||||
.max(4_096)
|
||||
.refine(isJsonPointer, "Expected an RFC 6901 JSON Pointer");
|
||||
|
||||
const sourcePointSchema = z.strictObject({
|
||||
line: z.number().int().min(1),
|
||||
column: z.number().int().min(0),
|
||||
});
|
||||
|
||||
const sourceRangeSchema = z
|
||||
.strictObject({
|
||||
start: sourcePointSchema,
|
||||
end: sourcePointSchema,
|
||||
})
|
||||
.superRefine((range, context) => {
|
||||
if (
|
||||
range.end.line < range.start.line ||
|
||||
(range.end.line === range.start.line &&
|
||||
range.end.column < range.start.column)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["end"],
|
||||
message: "Source range end must not precede its start",
|
||||
});
|
||||
});
|
||||
|
||||
const comparisonLimitsSchema = z.strictObject({
|
||||
max_candidate_exports: z.number().int().min(1).max(1_000).default(100),
|
||||
max_return_variants: z.number().int().min(1).max(1_000).default(128),
|
||||
max_changes: z.number().int().min(1).max(10_000).default(1_000),
|
||||
});
|
||||
|
||||
/** Two authenticated application graphs, exact export selectors, and bounds. */
|
||||
export const compareJavaScriptExportShapesInputSchema = z
|
||||
.strictObject({
|
||||
left: evidenceSchema,
|
||||
right: evidenceSchema,
|
||||
left_module_path: selectorTextSchema,
|
||||
left_export_name: selectorTextSchema,
|
||||
right_module_path: selectorTextSchema,
|
||||
right_export_name: selectorTextSchema,
|
||||
limits: comparisonLimitsSchema.default({
|
||||
max_candidate_exports: 100,
|
||||
max_return_variants: 128,
|
||||
max_changes: 1_000,
|
||||
}),
|
||||
unknown_registry_approved: z.literal(true).optional(),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (input.left.evidence_id === input.right.evidence_id)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["right"],
|
||||
message: "JavaScript export shape Evidence must be distinct",
|
||||
});
|
||||
});
|
||||
|
||||
const projectedReturnFieldSchema = z
|
||||
.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
state: z.enum(["literal", "union", "unknown"]),
|
||||
value: z.union([
|
||||
semanticPrimitiveSchema,
|
||||
z.array(semanticPrimitiveSchema).min(1).max(32),
|
||||
]),
|
||||
reason: boundedTextSchema.nullable(),
|
||||
})
|
||||
.superRefine((field, context) => {
|
||||
if (field.state === "union" && !Array.isArray(field.value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["value"],
|
||||
message: "Union return fields require a primitive value array",
|
||||
});
|
||||
if (field.state !== "union" && Array.isArray(field.value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["value"],
|
||||
message: "Only union return fields may contain a value array",
|
||||
});
|
||||
if (field.state === "unknown" && field.reason === null)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["reason"],
|
||||
message: "Unknown return fields require a reason",
|
||||
});
|
||||
if (field.state !== "unknown" && field.reason !== null)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["reason"],
|
||||
message: "Known return fields cannot carry an unknown reason",
|
||||
});
|
||||
});
|
||||
|
||||
const projectedPropertyCoverageSchema = z.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
status: z.enum(["complete", "partial"]),
|
||||
omitted: z.number().int().min(0).nullable(),
|
||||
});
|
||||
|
||||
const projectedReturnShapeSchema = z
|
||||
.strictObject({
|
||||
source_range: sourceRangeSchema,
|
||||
value_status: z.enum([
|
||||
"literal",
|
||||
"union",
|
||||
"object",
|
||||
"array",
|
||||
"unknown",
|
||||
"ambiguous",
|
||||
"cycle",
|
||||
"limit-reached",
|
||||
]),
|
||||
fields: z.array(projectedReturnFieldSchema).max(64),
|
||||
property_coverage: z.array(projectedPropertyCoverageSchema).max(64),
|
||||
})
|
||||
.superRefine((shape, context) => {
|
||||
const fieldPaths = shape.fields.map(({ path }) => path);
|
||||
if (new Set(fieldPaths).size !== fieldPaths.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["fields"],
|
||||
message: "Projected return field paths must be unique",
|
||||
});
|
||||
const coveragePaths = shape.property_coverage.map(({ path }) => path);
|
||||
if (new Set(coveragePaths).size !== coveragePaths.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["property_coverage"],
|
||||
message: "Projected property coverage paths must be unique",
|
||||
});
|
||||
});
|
||||
|
||||
/** Strict graph-observation payload produced by static return-shape recovery. */
|
||||
export const projectedExportReturnShapesSchema = z
|
||||
.strictObject({
|
||||
semantic_role: z.literal("export-return-shapes"),
|
||||
module_path: selectorTextSchema,
|
||||
exported_name: selectorTextSchema,
|
||||
callable_id: boundedTextSchema,
|
||||
callable_kind: z.enum(["function", "class", "method"]),
|
||||
static_return_shapes: z.array(projectedReturnShapeSchema).max(32),
|
||||
return_shape_coverage: z.strictObject({
|
||||
status: z.enum(["complete", "partial", "truncated"]),
|
||||
retained_return_sites: z.number().int().min(0).max(32),
|
||||
omitted_return_sites: z.number().int().min(0).nullable(),
|
||||
omitted_fields: z.number().int().min(0),
|
||||
omitted_property_coverage: z.number().int().min(0),
|
||||
projection_complete: z.boolean(),
|
||||
}),
|
||||
})
|
||||
.superRefine((projection, context) => {
|
||||
if (
|
||||
projection.return_shape_coverage.retained_return_sites !==
|
||||
projection.static_return_shapes.length
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["return_shape_coverage", "retained_return_sites"],
|
||||
message: "Retained return-site count must match projected shapes",
|
||||
});
|
||||
});
|
||||
|
||||
const exportCandidateSchema = z.strictObject({
|
||||
node_id: nodeIdSchema,
|
||||
module_path: selectorTextSchema,
|
||||
export_name: selectorTextSchema,
|
||||
matches_requested_module: z.boolean(),
|
||||
matches_requested_export: z.boolean(),
|
||||
});
|
||||
|
||||
const selectorResultSchema = z.strictObject({
|
||||
evidence_id: evidenceIdSchema,
|
||||
graph_id: graphIdSchema,
|
||||
requested_module_path: selectorTextSchema,
|
||||
requested_export_name: selectorTextSchema,
|
||||
status: z.enum(["selected", "missing", "ambiguous", "unavailable"]),
|
||||
selected_node_id: nodeIdSchema.nullable(),
|
||||
candidates: z.array(exportCandidateSchema).max(1_000),
|
||||
omitted_candidates: z.number().int().min(0),
|
||||
});
|
||||
|
||||
const valueAvailabilitySchema = z.discriminatedUnion("availability", [
|
||||
z.strictObject({ availability: z.literal("absent") }),
|
||||
z.strictObject({
|
||||
availability: z.literal("literal"),
|
||||
value: semanticPrimitiveSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
availability: z.literal("union"),
|
||||
values: z.array(semanticPrimitiveSchema).min(1).max(32),
|
||||
}),
|
||||
z.strictObject({
|
||||
availability: z.literal("unknown"),
|
||||
reason: boundedTextSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
const discriminantSchema = z.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
value: semanticPrimitiveSchema,
|
||||
});
|
||||
|
||||
const comparisonChangeSchema = z.strictObject({
|
||||
change_id: z.string().regex(/^jesc_change_[a-f0-9]{64}$/u),
|
||||
status: z.enum(["added", "removed", "changed", "unknown"]),
|
||||
path: jsonPointerSchema,
|
||||
discriminant: discriminantSchema.nullable(),
|
||||
left: valueAvailabilitySchema,
|
||||
right: valueAvailabilitySchema,
|
||||
left_source_range: sourceRangeSchema.nullable(),
|
||||
right_source_range: sourceRangeSchema.nullable(),
|
||||
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
|
||||
limitations: z.array(boundedTextSchema).max(20),
|
||||
});
|
||||
|
||||
/** Bounded static export-return comparison with explicit unknown semantics. */
|
||||
export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
comparison_id: z.string().regex(/^jesc_[a-f0-9]{64}$/u),
|
||||
left: selectorResultSchema,
|
||||
right: selectorResultSchema,
|
||||
summary: z.strictObject({
|
||||
added: z.number().int().min(0),
|
||||
removed: z.number().int().min(0),
|
||||
changed: z.number().int().min(0),
|
||||
unknown: z.number().int().min(0),
|
||||
}),
|
||||
changes: z.array(comparisonChangeSchema).max(10_000),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
|
||||
left_graph_status: z.enum([
|
||||
"complete",
|
||||
"partial",
|
||||
"unknown",
|
||||
"unavailable",
|
||||
]),
|
||||
right_graph_status: z.enum([
|
||||
"complete",
|
||||
"partial",
|
||||
"unknown",
|
||||
"unavailable",
|
||||
]),
|
||||
paired_variants: z.number().int().min(0),
|
||||
unpaired_left_variants: z.number().int().min(0),
|
||||
unpaired_right_variants: z.number().int().min(0),
|
||||
omitted_left_variants: z.number().int().min(0),
|
||||
omitted_right_variants: z.number().int().min(0),
|
||||
left_source_omitted_variants: z.number().int().min(0).nullable(),
|
||||
right_source_omitted_variants: z.number().int().min(0).nullable(),
|
||||
left_omitted_fields: z.number().int().min(0),
|
||||
right_omitted_fields: z.number().int().min(0),
|
||||
left_omitted_property_coverage: z.number().int().min(0),
|
||||
right_omitted_property_coverage: z.number().int().min(0),
|
||||
omitted_candidates: z.number().int().min(0),
|
||||
omitted_changes: z.number().int().min(0),
|
||||
}),
|
||||
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
|
||||
limitations: z.array(boundedTextSchema).max(1_000),
|
||||
runtime_validation: z.strictObject({
|
||||
recommended_tool: z.literal("run_controlled_replay"),
|
||||
automatically_started: z.literal(false),
|
||||
required_for: z.literal("runtime-semantics"),
|
||||
}),
|
||||
});
|
||||
|
||||
export type CompareJavaScriptExportShapesInput = z.output<
|
||||
typeof compareJavaScriptExportShapesInputSchema
|
||||
>;
|
||||
export type ProjectedExportReturnShapes = z.output<
|
||||
typeof projectedExportReturnShapesSchema
|
||||
>;
|
||||
export type JavaScriptExportShapeComparisonResult = z.output<
|
||||
typeof javaScriptExportShapeComparisonResultSchema
|
||||
>;
|
||||
export type JavaScriptExportShapeComparisonChange = z.output<
|
||||
typeof comparisonChangeSchema
|
||||
>;
|
||||
@@ -0,0 +1,234 @@
|
||||
import type {
|
||||
ApplicationNode,
|
||||
JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import { compareCodePoints } from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
projectedExportReturnShapesSchema,
|
||||
type JavaScriptExportShapeComparisonResult,
|
||||
type ProjectedExportReturnShapes,
|
||||
} from "./javascriptExportShapeComparisonSchemas.js";
|
||||
|
||||
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
|
||||
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
|
||||
|
||||
/** One authenticated graph and exact export selector. */
|
||||
export interface JavaScriptExportShapeSideInput {
|
||||
readonly evidenceId: string;
|
||||
readonly graph: JavaScriptApplicationGraph;
|
||||
readonly modulePath: string;
|
||||
readonly exportName: string;
|
||||
}
|
||||
|
||||
interface ExportCandidate {
|
||||
readonly node: ApplicationNode;
|
||||
readonly modulePath: string;
|
||||
readonly exportName: string;
|
||||
readonly trusted: boolean;
|
||||
}
|
||||
|
||||
/** Exact selector result plus any admitted static return-shape projection. */
|
||||
export interface SelectedJavaScriptExport {
|
||||
readonly selection: SelectorResult;
|
||||
readonly projection: ProjectedExportReturnShapes | null;
|
||||
readonly observationComplete: boolean;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Caller-retained return shapes and their exact caller-limit omission count. */
|
||||
export interface RetainedJavaScriptExportShapes {
|
||||
readonly shapes: readonly Shape[];
|
||||
readonly omitted: number;
|
||||
}
|
||||
|
||||
/** Select one exact trusted export and its exact static return-shape observation. */
|
||||
export const selectJavaScriptExport = (
|
||||
side: JavaScriptExportShapeSideInput,
|
||||
maxCandidates: number,
|
||||
): SelectedJavaScriptExport => {
|
||||
const candidates = exportCandidates(side.graph);
|
||||
const exact = candidates.filter(
|
||||
({ modulePath, exportName }) =>
|
||||
modulePath === side.modulePath && exportName === side.exportName,
|
||||
);
|
||||
const matchingOneSelector = candidates.filter(
|
||||
({ modulePath, exportName }) =>
|
||||
modulePath === side.modulePath || exportName === side.exportName,
|
||||
);
|
||||
const diagnosticPool =
|
||||
exact.length > 0
|
||||
? exact
|
||||
: matchingOneSelector.length > 0
|
||||
? matchingOneSelector
|
||||
: candidates;
|
||||
const retainedCandidates = diagnosticPool.slice(0, maxCandidates);
|
||||
const base = selectorBase(side, diagnosticPool, retainedCandidates);
|
||||
if (exact.length === 0)
|
||||
return unresolvedSelection(base, "missing", null, [
|
||||
`No exact export binding matched ${side.modulePath}:${side.exportName}.`,
|
||||
]);
|
||||
if (exact.length > 1)
|
||||
return unresolvedSelection(base, "ambiguous", null, [
|
||||
`Multiple exact export bindings matched ${side.modulePath}:${side.exportName}; none was selected.`,
|
||||
]);
|
||||
const selected = exact[0];
|
||||
if (selected === undefined || !selected.trusted)
|
||||
return unresolvedSelection(
|
||||
base,
|
||||
"unavailable",
|
||||
selected?.node.node_id ?? null,
|
||||
[
|
||||
"The exact export binding lacks the expected static-analysis authority.",
|
||||
],
|
||||
);
|
||||
const returnShape = returnShapeFor(selected.node, side);
|
||||
if (returnShape.projection === null)
|
||||
return unresolvedSelection(base, "unavailable", selected.node.node_id, [
|
||||
returnShape.reason,
|
||||
]);
|
||||
return {
|
||||
selection: {
|
||||
...base,
|
||||
status: "selected",
|
||||
selected_node_id: selected.node.node_id,
|
||||
},
|
||||
projection: returnShape.projection,
|
||||
observationComplete: returnShape.observationComplete,
|
||||
limitations: [],
|
||||
};
|
||||
};
|
||||
|
||||
/** Apply the caller's explicit return-variant limit. */
|
||||
export const retainJavaScriptExportShapes = (
|
||||
selection: SelectedJavaScriptExport,
|
||||
maximum: number,
|
||||
): RetainedJavaScriptExportShapes => {
|
||||
const shapes = selection.projection?.static_return_shapes ?? [];
|
||||
const retained = shapes.slice(0, maximum);
|
||||
return { shapes: retained, omitted: shapes.length - retained.length };
|
||||
};
|
||||
|
||||
const selectorBase = (
|
||||
side: JavaScriptExportShapeSideInput,
|
||||
candidates: readonly ExportCandidate[],
|
||||
retained: readonly ExportCandidate[],
|
||||
): Omit<SelectorResult, "status" | "selected_node_id"> => ({
|
||||
evidence_id: side.evidenceId,
|
||||
graph_id: side.graph.graph_id,
|
||||
requested_module_path: side.modulePath,
|
||||
requested_export_name: side.exportName,
|
||||
candidates: retained.map((candidate) => ({
|
||||
node_id: candidate.node.node_id,
|
||||
module_path: candidate.modulePath,
|
||||
export_name: candidate.exportName,
|
||||
matches_requested_module: candidate.modulePath === side.modulePath,
|
||||
matches_requested_export: candidate.exportName === side.exportName,
|
||||
})),
|
||||
omitted_candidates: candidates.length - retained.length,
|
||||
});
|
||||
|
||||
const unresolvedSelection = (
|
||||
base: Omit<SelectorResult, "status" | "selected_node_id">,
|
||||
status: "missing" | "ambiguous" | "unavailable",
|
||||
nodeId: string | null,
|
||||
limitations: readonly string[],
|
||||
): SelectedJavaScriptExport => ({
|
||||
selection: { ...base, status, selected_node_id: nodeId },
|
||||
projection: null,
|
||||
observationComplete: false,
|
||||
limitations,
|
||||
});
|
||||
|
||||
const exportCandidates = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
): ExportCandidate[] => {
|
||||
const candidates = new Map<string, ExportCandidate>();
|
||||
for (const node of graph.nodes) {
|
||||
for (const observation of node.observations) {
|
||||
const properties = observation.properties;
|
||||
if (properties.semantic_role !== "export-binding") continue;
|
||||
const modulePath = properties.module_path;
|
||||
const exportName = properties.exported_name;
|
||||
if (typeof modulePath !== "string" || typeof exportName !== "string")
|
||||
continue;
|
||||
const key = `${node.node_id}\0${modulePath}\0${exportName}`;
|
||||
const trusted =
|
||||
observation.evidence.authority === "ast-static-analysis" &&
|
||||
observation.evidence.state === "observed" &&
|
||||
observation.evidence.extractor.operation === "recover-module-export";
|
||||
const existing = candidates.get(key);
|
||||
candidates.set(key, {
|
||||
node,
|
||||
modulePath,
|
||||
exportName,
|
||||
trusted: trusted || existing?.trusted === true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return [...candidates.values()].sort((left, right) =>
|
||||
compareCodePoints(candidateKey(left), candidateKey(right)),
|
||||
);
|
||||
};
|
||||
|
||||
const candidateKey = (candidate: ExportCandidate): string =>
|
||||
`${candidate.modulePath}\0${candidate.exportName}\0${candidate.node.node_id}`;
|
||||
|
||||
const returnShapeFor = (
|
||||
node: ApplicationNode,
|
||||
side: JavaScriptExportShapeSideInput,
|
||||
): {
|
||||
readonly projection: ProjectedExportReturnShapes | null;
|
||||
readonly observationComplete: boolean;
|
||||
readonly reason: string;
|
||||
} => {
|
||||
const roleObservations = node.observations.filter(
|
||||
({ properties }) => properties.semantic_role === "export-return-shapes",
|
||||
);
|
||||
const parsed = roleObservations.map((observation) => ({
|
||||
observation,
|
||||
result: projectedExportReturnShapesSchema.safeParse(observation.properties),
|
||||
}));
|
||||
if (parsed.some(({ result }) => !result.success))
|
||||
return unavailableReturnShape(
|
||||
"The export return-shape observation is malformed.",
|
||||
);
|
||||
const matching = parsed.filter(
|
||||
({ result }) =>
|
||||
result.success &&
|
||||
result.data.module_path === side.modulePath &&
|
||||
result.data.exported_name === side.exportName,
|
||||
);
|
||||
if (matching.length !== 1)
|
||||
return unavailableReturnShape(
|
||||
matching.length === 0
|
||||
? "No exact static return-shape observation is available for the selected export."
|
||||
: "Multiple static return-shape observations matched the selected export.",
|
||||
);
|
||||
const selected = matching[0];
|
||||
if (selected === undefined || !selected.result.success)
|
||||
return unavailableReturnShape(
|
||||
"The selected return-shape observation could not be parsed.",
|
||||
);
|
||||
const { observation } = selected;
|
||||
const trusted =
|
||||
observation.evidence.authority === "static-relationship-inference" &&
|
||||
observation.evidence.state === "inferred" &&
|
||||
observation.evidence.extractor.operation === "recover-export-return-shapes";
|
||||
if (!trusted)
|
||||
return unavailableReturnShape(
|
||||
"The return-shape observation lacks the expected static-inference authority.",
|
||||
);
|
||||
return {
|
||||
projection: selected.result.data,
|
||||
observationComplete:
|
||||
observation.evidence.coverage.status === "complete" &&
|
||||
!observation.evidence.coverage.truncated,
|
||||
reason: "",
|
||||
};
|
||||
};
|
||||
|
||||
const unavailableReturnShape = (reason: string) => ({
|
||||
projection: null,
|
||||
observationComplete: false,
|
||||
reason,
|
||||
});
|
||||
@@ -0,0 +1,441 @@
|
||||
import { compareCodePoints } from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
canonicalExportShapeValue,
|
||||
digestExportShapeValue,
|
||||
} from "./javascriptExportShapeComparisonIdentity.js";
|
||||
import type {
|
||||
JavaScriptExportShapeComparisonChange,
|
||||
JavaScriptExportShapeComparisonResult,
|
||||
ProjectedExportReturnShapes,
|
||||
} from "./javascriptExportShapeComparisonSchemas.js";
|
||||
import type { SelectedJavaScriptExport } from "./javascriptExportShapeSelection.js";
|
||||
|
||||
type Primitive = string | number | boolean | null;
|
||||
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
|
||||
type Field = Shape["fields"][number];
|
||||
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
|
||||
type ValueAvailability = JavaScriptExportShapeComparisonChange["left"];
|
||||
type Discriminant = NonNullable<
|
||||
JavaScriptExportShapeComparisonChange["discriminant"]
|
||||
>;
|
||||
|
||||
interface VariantPair {
|
||||
readonly leftIndex: number;
|
||||
readonly rightIndex: number;
|
||||
readonly discriminant: Discriminant;
|
||||
}
|
||||
|
||||
/** Unique-only return-variant pairings plus every unpaired retained variant. */
|
||||
export interface JavaScriptExportShapePairing {
|
||||
readonly pairs: readonly VariantPair[];
|
||||
readonly unpairedLeft: readonly number[];
|
||||
readonly unpairedRight: readonly number[];
|
||||
}
|
||||
|
||||
/** Pair variants only through reciprocal unique exact literal discriminants. */
|
||||
export const pairJavaScriptExportShapeVariants = (
|
||||
left: readonly Shape[],
|
||||
right: readonly Shape[],
|
||||
): JavaScriptExportShapePairing => {
|
||||
const leftKeys = discriminantOccurrences(left);
|
||||
const rightKeys = discriminantOccurrences(right);
|
||||
const edges = new Map<string, Discriminant[]>();
|
||||
const leftTargets = new Map<number, Set<number>>();
|
||||
const rightTargets = new Map<number, Set<number>>();
|
||||
for (const [key, leftOccurrence] of leftKeys) {
|
||||
const rightOccurrence = rightKeys.get(key);
|
||||
if (
|
||||
leftOccurrence.indexes.length !== 1 ||
|
||||
rightOccurrence?.indexes.length !== 1
|
||||
)
|
||||
continue;
|
||||
const leftIndex = leftOccurrence.indexes[0];
|
||||
const rightIndex = rightOccurrence.indexes[0];
|
||||
if (leftIndex === undefined || rightIndex === undefined) continue;
|
||||
const edgeKey = `${String(leftIndex)}:${String(rightIndex)}`;
|
||||
edges.set(edgeKey, [
|
||||
...(edges.get(edgeKey) ?? []),
|
||||
leftOccurrence.discriminant,
|
||||
]);
|
||||
addTarget(leftTargets, leftIndex, rightIndex);
|
||||
addTarget(rightTargets, rightIndex, leftIndex);
|
||||
}
|
||||
const pairs = reciprocalPairs(leftTargets, rightTargets, edges);
|
||||
const pairedLeft = new Set(pairs.map(({ leftIndex }) => leftIndex));
|
||||
const pairedRight = new Set(pairs.map(({ rightIndex }) => rightIndex));
|
||||
return {
|
||||
pairs,
|
||||
unpairedLeft: indexesNotIn(left, pairedLeft),
|
||||
unpairedRight: indexesNotIn(right, pairedRight),
|
||||
};
|
||||
};
|
||||
|
||||
interface ChangeBuildInput {
|
||||
readonly leftSelection: SelectedJavaScriptExport;
|
||||
readonly rightSelection: SelectedJavaScriptExport;
|
||||
readonly pairing: JavaScriptExportShapePairing;
|
||||
readonly leftShapes: readonly Shape[];
|
||||
readonly rightShapes: readonly Shape[];
|
||||
readonly evidenceLinks: [string, string];
|
||||
}
|
||||
|
||||
/** Build bounded-ready field and unpaired-variant changes before caller slicing. */
|
||||
export const buildJavaScriptExportShapeChanges = (
|
||||
input: ChangeBuildInput,
|
||||
): JavaScriptExportShapeComparisonChange[] => {
|
||||
if (
|
||||
input.leftSelection.selection.status !== "selected" ||
|
||||
input.rightSelection.selection.status !== "selected"
|
||||
)
|
||||
return [selectionUnknownChange(input)];
|
||||
if (input.leftShapes.length === 0 || input.rightShapes.length === 0)
|
||||
return [emptyShapeUnknownChange(input)];
|
||||
const paired = input.pairing.pairs.flatMap((pair) => {
|
||||
const left = input.leftShapes[pair.leftIndex];
|
||||
const right = input.rightShapes[pair.rightIndex];
|
||||
return left === undefined || right === undefined
|
||||
? []
|
||||
: diffPair(left, right, pair.discriminant, input.evidenceLinks);
|
||||
});
|
||||
const unpairedLeft = input.pairing.unpairedLeft.flatMap((index) => {
|
||||
const shape = input.leftShapes[index];
|
||||
return shape === undefined
|
||||
? []
|
||||
: [unpairedChange("left", shape, input.evidenceLinks)];
|
||||
});
|
||||
const unpairedRight = input.pairing.unpairedRight.flatMap((index) => {
|
||||
const shape = input.rightShapes[index];
|
||||
return shape === undefined
|
||||
? []
|
||||
: [unpairedChange("right", shape, input.evidenceLinks)];
|
||||
});
|
||||
return [...paired, ...unpairedLeft, ...unpairedRight];
|
||||
};
|
||||
|
||||
/** Sort changes by semantic content rather than traversal order. */
|
||||
export const compareJavaScriptExportShapeChanges = (
|
||||
left: JavaScriptExportShapeComparisonChange,
|
||||
right: JavaScriptExportShapeComparisonChange,
|
||||
): number =>
|
||||
compareCodePoints(
|
||||
canonicalExportShapeValue(changeSortKey(left)),
|
||||
canonicalExportShapeValue(changeSortKey(right)),
|
||||
);
|
||||
|
||||
/** Report whether any retained shape lacks complete property coverage. */
|
||||
export const hasPartialJavaScriptExportPropertyCoverage = (
|
||||
shapes: readonly Shape[],
|
||||
): boolean =>
|
||||
shapes.some((shape) =>
|
||||
shape.property_coverage.some(({ status }) => status === "partial"),
|
||||
);
|
||||
|
||||
interface DiscriminantOccurrence {
|
||||
readonly discriminant: Discriminant;
|
||||
readonly indexes: number[];
|
||||
}
|
||||
|
||||
const discriminantOccurrences = (
|
||||
shapes: readonly Shape[],
|
||||
): Map<string, DiscriminantOccurrence> => {
|
||||
const output = new Map<string, DiscriminantOccurrence>();
|
||||
shapes.forEach((shape, index) => {
|
||||
for (const field of shape.fields) {
|
||||
const value = literalValue(field);
|
||||
if (!value.found) continue;
|
||||
const discriminant = { path: field.path, value: value.value };
|
||||
const key = canonicalExportShapeValue(discriminant);
|
||||
const current = output.get(key);
|
||||
output.set(key, {
|
||||
discriminant,
|
||||
indexes: [...(current?.indexes ?? []), index],
|
||||
});
|
||||
}
|
||||
});
|
||||
return output;
|
||||
};
|
||||
|
||||
const reciprocalPairs = (
|
||||
leftTargets: ReadonlyMap<number, ReadonlySet<number>>,
|
||||
rightTargets: ReadonlyMap<number, ReadonlySet<number>>,
|
||||
edges: ReadonlyMap<string, readonly Discriminant[]>,
|
||||
): VariantPair[] => {
|
||||
const pairs: VariantPair[] = [];
|
||||
for (const [leftIndex, targets] of leftTargets) {
|
||||
if (targets.size !== 1) continue;
|
||||
const rightIndex = [...targets][0];
|
||||
if (
|
||||
rightIndex === undefined ||
|
||||
rightTargets.get(rightIndex)?.size !== 1 ||
|
||||
!rightTargets.get(rightIndex)?.has(leftIndex)
|
||||
)
|
||||
continue;
|
||||
const discriminants = edges
|
||||
.get(`${String(leftIndex)}:${String(rightIndex)}`)
|
||||
?.toSorted(compareDiscriminants);
|
||||
const discriminant = discriminants?.[0];
|
||||
if (discriminant !== undefined)
|
||||
pairs.push({ leftIndex, rightIndex, discriminant });
|
||||
}
|
||||
return pairs.sort((first, second) =>
|
||||
compareDiscriminants(first.discriminant, second.discriminant),
|
||||
);
|
||||
};
|
||||
|
||||
const addTarget = (
|
||||
map: Map<number, Set<number>>,
|
||||
source: number,
|
||||
target: number,
|
||||
): void => {
|
||||
const values = map.get(source) ?? new Set<number>();
|
||||
values.add(target);
|
||||
map.set(source, values);
|
||||
};
|
||||
|
||||
const indexesNotIn = (
|
||||
shapes: readonly Shape[],
|
||||
paired: ReadonlySet<number>,
|
||||
): number[] =>
|
||||
shapes.map((_, index) => index).filter((index) => !paired.has(index));
|
||||
|
||||
const compareDiscriminants = (
|
||||
left: Discriminant,
|
||||
right: Discriminant,
|
||||
): number =>
|
||||
compareCodePoints(
|
||||
canonicalExportShapeValue(left),
|
||||
canonicalExportShapeValue(right),
|
||||
);
|
||||
|
||||
const selectionUnknownChange = (
|
||||
input: ChangeBuildInput,
|
||||
): JavaScriptExportShapeComparisonChange =>
|
||||
changeWithId({
|
||||
status: "unknown",
|
||||
path: "",
|
||||
discriminant: null,
|
||||
left: selectionAvailability(input.leftSelection.selection, "left"),
|
||||
right: selectionAvailability(input.rightSelection.selection, "right"),
|
||||
left_source_range: null,
|
||||
right_source_range: null,
|
||||
evidence_links: input.evidenceLinks,
|
||||
limitations: [
|
||||
"Both selectors must resolve one exact export with trusted static return shapes before comparison.",
|
||||
],
|
||||
});
|
||||
|
||||
const emptyShapeUnknownChange = (
|
||||
input: ChangeBuildInput,
|
||||
): JavaScriptExportShapeComparisonChange =>
|
||||
changeWithId({
|
||||
status: "unknown",
|
||||
path: "",
|
||||
discriminant: null,
|
||||
left: emptyShapeAvailability(input.leftShapes, "left"),
|
||||
right: emptyShapeAvailability(input.rightShapes, "right"),
|
||||
left_source_range: null,
|
||||
right_source_range: null,
|
||||
evidence_links: input.evidenceLinks,
|
||||
limitations: [
|
||||
"At least one selected export has no retained direct return shape.",
|
||||
],
|
||||
});
|
||||
|
||||
const diffPair = (
|
||||
left: Shape,
|
||||
right: Shape,
|
||||
discriminant: Discriminant,
|
||||
evidenceLinks: [string, string],
|
||||
): JavaScriptExportShapeComparisonChange[] => {
|
||||
const leftFields = new Map(left.fields.map((field) => [field.path, field]));
|
||||
const rightFields = new Map(right.fields.map((field) => [field.path, field]));
|
||||
const paths = uniqueSorted([...leftFields.keys(), ...rightFields.keys()]);
|
||||
return paths.flatMap((path) => {
|
||||
const leftField = leftFields.get(path);
|
||||
const rightField = rightFields.get(path);
|
||||
const status = fieldChangeStatus({
|
||||
leftShape: left,
|
||||
rightShape: right,
|
||||
path,
|
||||
leftField,
|
||||
rightField,
|
||||
});
|
||||
if (status === null) return [];
|
||||
return [
|
||||
changeWithId({
|
||||
status,
|
||||
path,
|
||||
discriminant,
|
||||
left: fieldAvailability(leftField),
|
||||
right: fieldAvailability(rightField),
|
||||
left_source_range: left.source_range,
|
||||
right_source_range: right.source_range,
|
||||
evidence_links: evidenceLinks,
|
||||
limitations:
|
||||
status === "unknown"
|
||||
? [
|
||||
"The static value or relevant parent-property coverage is incomplete.",
|
||||
]
|
||||
: [],
|
||||
}),
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
interface FieldChangeInput {
|
||||
readonly leftShape: Shape;
|
||||
readonly rightShape: Shape;
|
||||
readonly path: string;
|
||||
readonly leftField: Field | undefined;
|
||||
readonly rightField: Field | undefined;
|
||||
}
|
||||
|
||||
const fieldChangeStatus = ({
|
||||
leftShape,
|
||||
rightShape,
|
||||
path,
|
||||
leftField,
|
||||
rightField,
|
||||
}: FieldChangeInput):
|
||||
| JavaScriptExportShapeComparisonChange["status"]
|
||||
| null => {
|
||||
if (leftField !== undefined && rightField !== undefined) {
|
||||
if (
|
||||
canonicalExportShapeValue(leftField) ===
|
||||
canonicalExportShapeValue(rightField)
|
||||
)
|
||||
return null;
|
||||
return leftField.state === "unknown" || rightField.state === "unknown"
|
||||
? "unknown"
|
||||
: "changed";
|
||||
}
|
||||
const present = leftField ?? rightField;
|
||||
if (present === undefined) return null;
|
||||
const parent = parentPointer(path);
|
||||
const parentsComplete =
|
||||
propertyCoverageComplete(leftShape, parent) &&
|
||||
propertyCoverageComplete(rightShape, parent);
|
||||
if (present.state === "unknown" || !parentsComplete) return "unknown";
|
||||
return leftField === undefined ? "added" : "removed";
|
||||
};
|
||||
|
||||
const propertyCoverageComplete = (shape: Shape, path: string | null): boolean =>
|
||||
path !== null &&
|
||||
shape.property_coverage.some(
|
||||
(coverage) => coverage.path === path && coverage.status === "complete",
|
||||
);
|
||||
|
||||
const parentPointer = (path: string): string | null => {
|
||||
if (path === "") return null;
|
||||
const separator = path.lastIndexOf("/");
|
||||
return separator < 0 ? null : path.slice(0, separator);
|
||||
};
|
||||
|
||||
const fieldAvailability = (field: Field | undefined): ValueAvailability => {
|
||||
if (field === undefined) return { availability: "absent" };
|
||||
if (field.state === "unknown")
|
||||
return {
|
||||
availability: "unknown",
|
||||
reason: field.reason ?? "Static field value is unknown.",
|
||||
};
|
||||
if (field.state === "union")
|
||||
return { availability: "union", values: primitiveArray(field.value) };
|
||||
const literal = literalValue(field);
|
||||
return literal.found
|
||||
? { availability: "literal", value: literal.value }
|
||||
: {
|
||||
availability: "unknown",
|
||||
reason: "Static literal field failed its projection boundary.",
|
||||
};
|
||||
};
|
||||
|
||||
const selectionAvailability = (
|
||||
selection: SelectorResult,
|
||||
side: "left" | "right",
|
||||
): ValueAvailability => ({
|
||||
availability: "unknown",
|
||||
reason: `${capitalize(side)} export selection is ${selection.status}.`,
|
||||
});
|
||||
|
||||
const emptyShapeAvailability = (
|
||||
shapes: readonly Shape[],
|
||||
side: "left" | "right",
|
||||
): ValueAvailability => ({
|
||||
availability: "unknown",
|
||||
reason:
|
||||
shapes.length === 0
|
||||
? `${capitalize(side)} export has no retained direct return shape.`
|
||||
: `${capitalize(side)} export return shape cannot be paired without an opposite variant.`,
|
||||
});
|
||||
|
||||
const unpairedChange = (
|
||||
side: "left" | "right",
|
||||
shape: Shape,
|
||||
evidenceLinks: [string, string],
|
||||
): JavaScriptExportShapeComparisonChange =>
|
||||
changeWithId({
|
||||
status: "unknown",
|
||||
path: "",
|
||||
discriminant: null,
|
||||
left: {
|
||||
availability: "unknown",
|
||||
reason:
|
||||
side === "left"
|
||||
? "Left return variant has no unique exact cross-version pairing."
|
||||
: "No left return variant was uniquely paired with this right variant.",
|
||||
},
|
||||
right: {
|
||||
availability: "unknown",
|
||||
reason:
|
||||
side === "right"
|
||||
? "Right return variant has no unique exact cross-version pairing."
|
||||
: "No right return variant was uniquely paired with this left variant.",
|
||||
},
|
||||
left_source_range: side === "left" ? shape.source_range : null,
|
||||
right_source_range: side === "right" ? shape.source_range : null,
|
||||
evidence_links: evidenceLinks,
|
||||
limitations: [
|
||||
"The return variant was not paired because no reciprocal unique literal discriminant exists.",
|
||||
],
|
||||
});
|
||||
|
||||
const changeWithId = (
|
||||
semantic: Omit<JavaScriptExportShapeComparisonChange, "change_id">,
|
||||
): JavaScriptExportShapeComparisonChange => ({
|
||||
...semantic,
|
||||
change_id: `jesc_change_${digestExportShapeValue(semantic)}`,
|
||||
});
|
||||
|
||||
const changeSortKey = (change: JavaScriptExportShapeComparisonChange) => ({
|
||||
discriminant: change.discriminant,
|
||||
path: change.path,
|
||||
status: change.status,
|
||||
left_source_range: change.left_source_range,
|
||||
right_source_range: change.right_source_range,
|
||||
change_id: change.change_id,
|
||||
});
|
||||
|
||||
const literalValue = (
|
||||
field: Field,
|
||||
):
|
||||
| { readonly found: true; readonly value: Primitive }
|
||||
| { readonly found: false } =>
|
||||
field.state === "literal" && isPrimitive(field.value)
|
||||
? { found: true, value: field.value }
|
||||
: { found: false };
|
||||
|
||||
const primitiveArray = (value: unknown): Primitive[] =>
|
||||
Array.isArray(value) ? value.filter(isPrimitive) : [];
|
||||
|
||||
const isPrimitive = (value: unknown): value is Primitive =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean";
|
||||
|
||||
const capitalize = (value: string): string =>
|
||||
`${value.slice(0, 1).toUpperCase()}${value.slice(1)}`;
|
||||
|
||||
const uniqueSorted = <Value extends string>(
|
||||
values: readonly Value[],
|
||||
): Value[] => [...new Set(values)].sort(compareCodePoints);
|
||||
@@ -26,9 +26,15 @@ import type {
|
||||
} from "./javascriptSemanticState.js";
|
||||
import {
|
||||
currentSemanticScope,
|
||||
resolveSemanticBindingFromScope,
|
||||
semanticScopeId,
|
||||
semanticVariableScope,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
import {
|
||||
collectSemanticReturns,
|
||||
resolveSemanticModuleCallables,
|
||||
} from "./javascriptSemanticReturns.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
@@ -77,14 +83,17 @@ export const analyzeJavaScriptSemantics = (
|
||||
collectDefinitions(file.program, state);
|
||||
const references = collectSemanticReferences(file.program, state);
|
||||
const parserPartial = file.errors.length > 0;
|
||||
const bindings = immutableSemanticBindings(state);
|
||||
const callables = collectSemanticReturns(file.program, state, parserPartial);
|
||||
const moduleLinks = resolveSemanticModuleCallables(state, callables);
|
||||
return {
|
||||
schema: "JavaScriptSemanticIR",
|
||||
schemaVersion: 1,
|
||||
schemaVersion: 2,
|
||||
scopes: immutableSemanticScopes(state),
|
||||
bindings: immutableSemanticBindings(state),
|
||||
callables: [...state.callables],
|
||||
bindings,
|
||||
callables,
|
||||
references,
|
||||
moduleLinks: [...state.moduleLinks],
|
||||
moduleLinks,
|
||||
coverage: {
|
||||
status:
|
||||
state.limitsReached.size > 0
|
||||
@@ -105,6 +114,7 @@ export const analyzeJavaScriptSemantics = (
|
||||
? []
|
||||
: ["Semantic recovery stopped retaining facts at explicit limits."]),
|
||||
"Values and aliases were recovered from inert syntax only; no JavaScript was executed.",
|
||||
"Return sites include only direct callable returns; nested callable returns remain separate.",
|
||||
"Cross-function mutation and dynamic property resolution remain unknown.",
|
||||
],
|
||||
};
|
||||
@@ -208,7 +218,7 @@ const bindInnerDeclaration = (
|
||||
bindPattern({
|
||||
pattern: node.id,
|
||||
initializer: node.init ?? null,
|
||||
scope: variableScope(scope, parent, state),
|
||||
scope: semanticVariableScope(scope, parent, state),
|
||||
state,
|
||||
mutable:
|
||||
parent !== null && t.isVariableDeclaration(parent)
|
||||
@@ -473,46 +483,13 @@ const addAssignment = (
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): void => {
|
||||
const binding = resolveFromScope(scope, identifier.name, state);
|
||||
const binding = resolveSemanticBindingFromScope(
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface JavaScriptSemanticLimits {
|
||||
readonly maxCallables: number;
|
||||
readonly maxReferences: number;
|
||||
readonly maxModuleLinks: number;
|
||||
readonly maxReturnSites: number;
|
||||
readonly maxValueDepth: number;
|
||||
readonly maxUnionValues: number;
|
||||
readonly maxObjectProperties: number;
|
||||
@@ -19,6 +20,7 @@ export const DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS: JavaScriptSemanticLimits = {
|
||||
maxCallables: 20_000,
|
||||
maxReferences: 100_000,
|
||||
maxModuleLinks: 20_000,
|
||||
maxReturnSites: 20_000,
|
||||
maxValueDepth: 16,
|
||||
maxUnionValues: 32,
|
||||
maxObjectProperties: 256,
|
||||
@@ -41,11 +43,13 @@ export type JavaScriptSemanticValue =
|
||||
readonly status: "object";
|
||||
readonly properties: readonly JavaScriptSemanticProperty[];
|
||||
readonly unknownProperties: boolean;
|
||||
readonly omittedProperties: number | null;
|
||||
}
|
||||
| {
|
||||
readonly status: "array";
|
||||
readonly items: readonly JavaScriptSemanticValue[];
|
||||
readonly unknownItems: boolean;
|
||||
readonly omittedItems: number | null;
|
||||
}
|
||||
| {
|
||||
readonly status: "unknown" | "ambiguous" | "cycle" | "limit-reached";
|
||||
@@ -129,6 +133,22 @@ export interface JavaScriptSemanticCallable {
|
||||
readonly containerScopeId: string;
|
||||
readonly bodyScopeId: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
readonly returnSites: readonly JavaScriptSemanticReturnSite[];
|
||||
readonly returnCoverage: JavaScriptSemanticReturnCoverage;
|
||||
}
|
||||
|
||||
/** One direct return expression belonging to exactly one callable. */
|
||||
export interface JavaScriptSemanticReturnSite {
|
||||
readonly location: JavaScriptSourceRange;
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
}
|
||||
|
||||
/** Exact retention state for one callable's direct returns. */
|
||||
interface JavaScriptSemanticReturnCoverage {
|
||||
readonly status: "complete" | "partial" | "truncated";
|
||||
readonly retainedCount: number;
|
||||
readonly omittedCount: number | null;
|
||||
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
|
||||
}
|
||||
|
||||
/** Static import/export relationship retained for cross-file composition. */
|
||||
@@ -143,6 +163,7 @@ export interface JavaScriptSemanticModuleLink {
|
||||
readonly importedName: string | null;
|
||||
readonly localName: string | null;
|
||||
readonly exportedName: string | null;
|
||||
readonly callableId: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -153,10 +174,10 @@ interface JavaScriptSemanticCoverage {
|
||||
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
|
||||
}
|
||||
|
||||
/** Provider-neutral JavaScript semantic IR v1. */
|
||||
/** Provider-neutral JavaScript semantic IR v2. */
|
||||
export interface JavaScriptSemanticIr {
|
||||
readonly schema: "JavaScriptSemanticIR";
|
||||
readonly schemaVersion: 1;
|
||||
readonly schemaVersion: 2;
|
||||
readonly scopes: readonly JavaScriptSemanticScope[];
|
||||
readonly bindings: readonly JavaScriptSemanticBinding[];
|
||||
readonly callables: readonly JavaScriptSemanticCallable[];
|
||||
@@ -187,7 +208,7 @@ export const semanticBinding = (
|
||||
/** Fail-closed result when Babel cannot produce an inert syntax tree. */
|
||||
export const failedJavaScriptSemanticIr = (): JavaScriptSemanticIr => ({
|
||||
schema: "JavaScriptSemanticIR",
|
||||
schemaVersion: 1,
|
||||
schemaVersion: 2,
|
||||
scopes: [],
|
||||
bindings: [],
|
||||
callables: [],
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptSemanticPrimitive,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
|
||||
import {
|
||||
reachSemanticValueLimit,
|
||||
semanticPrimitiveKey,
|
||||
} from "./javascriptSemanticProvenance.js";
|
||||
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
/** Normalize one bounded collection of possible primitive values. */
|
||||
export const semanticPrimitiveSet = (
|
||||
values: readonly JavaScriptSemanticPrimitive[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticValue => {
|
||||
const unique = [
|
||||
...new Map(
|
||||
values.map((value) => [semanticPrimitiveKey(value), value]),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
compareCodePoints(semanticPrimitiveKey(left), semanticPrimitiveKey(right)),
|
||||
);
|
||||
if (unique.length > state.limits.maxUnionValues) {
|
||||
reachSemanticValueLimit(state, "maxUnionValues");
|
||||
return {
|
||||
status: "limit-reached",
|
||||
reason: "maxUnionValues reached.",
|
||||
};
|
||||
}
|
||||
const only = unique[0];
|
||||
return unique.length === 1 && only !== undefined
|
||||
? { status: "literal", value: only }
|
||||
: { status: "union", values: unique };
|
||||
};
|
||||
|
||||
/** Read the primitive candidates retained in one lattice value. */
|
||||
export const semanticPrimitiveCandidates = (
|
||||
value: JavaScriptSemanticValue,
|
||||
): readonly JavaScriptSemanticPrimitive[] | null =>
|
||||
value.status === "literal"
|
||||
? [value.value]
|
||||
: value.status === "union"
|
||||
? value.values
|
||||
: null;
|
||||
|
||||
/** Parse one Babel primitive literal without evaluating code. */
|
||||
export const semanticPrimitiveValue = (
|
||||
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 };
|
||||
};
|
||||
@@ -43,7 +43,7 @@ export const collectSemanticCallable = (input: CollectCallableInput): void => {
|
||||
return;
|
||||
}
|
||||
state.callables.push({
|
||||
callableId: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
|
||||
callableId: semanticCallableIdForNode(node) ?? "callable:unknown:-1:-1",
|
||||
kind,
|
||||
name: callableName(node, parent),
|
||||
containerScopeId: containerScope.scopeId,
|
||||
@@ -52,6 +52,13 @@ export const collectSemanticCallable = (input: CollectCallableInput): void => {
|
||||
? null
|
||||
: bodyScope.scopeId,
|
||||
location: range(node),
|
||||
returnSites: [],
|
||||
returnCoverage: {
|
||||
status: "partial",
|
||||
retainedCount: 0,
|
||||
omittedCount: null,
|
||||
limitsReached: [],
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -78,6 +85,7 @@ export const collectSemanticModuleLink = (
|
||||
importedName: null,
|
||||
localName: defaultDeclarationName(node.declaration),
|
||||
exportedName: "default",
|
||||
callableId: semanticCallableIdForNode(node.declaration),
|
||||
location: range(node),
|
||||
});
|
||||
else if (t.isVariableDeclarator(node)) collectRequireLink(node, state);
|
||||
@@ -278,6 +286,7 @@ const collectNamedExports = (
|
||||
importedName: null,
|
||||
localName,
|
||||
exportedName: localName,
|
||||
callableId: declarationCallableId(node.declaration, localName),
|
||||
location: range(node.declaration),
|
||||
});
|
||||
for (const specifier of node.specifiers)
|
||||
@@ -349,19 +358,49 @@ const collectCommonJsExport = (
|
||||
importedName: origin?.importedPath.at(-1) ?? null,
|
||||
localName: t.isIdentifier(node.right) ? node.right.name : null,
|
||||
exportedName,
|
||||
callableId: semanticCallableIdForNode(node.right),
|
||||
location: range(node),
|
||||
});
|
||||
};
|
||||
|
||||
const addModuleLink = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
link: JavaScriptSemanticModuleLink,
|
||||
link: Omit<JavaScriptSemanticModuleLink, "callableId"> & {
|
||||
readonly callableId?: string | null;
|
||||
},
|
||||
): void => {
|
||||
if (state.moduleLinks.length >= state.limits.maxModuleLinks) {
|
||||
reachSemanticLimit(state, "maxModuleLinks");
|
||||
return;
|
||||
}
|
||||
state.moduleLinks.push(link);
|
||||
state.moduleLinks.push({ ...link, callableId: link.callableId ?? null });
|
||||
};
|
||||
|
||||
/** Deterministic callable identity shared by collection and return recovery. */
|
||||
export const semanticCallableIdForNode = (node: t.Node): string | null => {
|
||||
const kind = callableKind(node);
|
||||
return kind === undefined
|
||||
? null
|
||||
: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
|
||||
};
|
||||
|
||||
const declarationCallableId = (
|
||||
declaration: t.Declaration,
|
||||
localName: string,
|
||||
): string | null => {
|
||||
if (
|
||||
(t.isFunctionDeclaration(declaration) ||
|
||||
t.isClassDeclaration(declaration)) &&
|
||||
declaration.id?.name === localName
|
||||
)
|
||||
return semanticCallableIdForNode(declaration);
|
||||
if (!t.isVariableDeclaration(declaration)) return null;
|
||||
const declarator = declaration.declarations.find(({ id }) =>
|
||||
t.isIdentifier(id, { name: localName }),
|
||||
);
|
||||
return declarator?.init === null || declarator?.init === undefined
|
||||
? null
|
||||
: semanticCallableIdForNode(declarator.init);
|
||||
};
|
||||
|
||||
const referenceRole = (
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type {
|
||||
JavaScriptBindingProvenance,
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticPrimitive,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
|
||||
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
/** Construct one immutable semantic provenance value. */
|
||||
export const semanticProvenance = (
|
||||
status: JavaScriptBindingProvenance["status"],
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
reason: string | null,
|
||||
): JavaScriptBindingProvenance => ({ status, origins, reason });
|
||||
|
||||
/** Normalize bounded exact module origins into one provenance classification. */
|
||||
export const semanticOriginsProvenance = (
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptBindingProvenance => {
|
||||
const unique = uniqueSemanticOrigins(origins);
|
||||
if (unique.length > state.limits.maxUnionValues)
|
||||
return semanticLimitProvenance(state, "maxUnionValues");
|
||||
return unique.length === 1
|
||||
? semanticProvenance("module", unique, null)
|
||||
: semanticProvenance("ambiguous", unique, "Multiple module origins.");
|
||||
};
|
||||
|
||||
/** Deduplicate and canonically order module origins. */
|
||||
export const uniqueSemanticOrigins = (
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
): JavaScriptModuleOrigin[] =>
|
||||
[
|
||||
...new Map(
|
||||
origins.map((origin) => [semanticOriginKey(origin), origin]),
|
||||
).values(),
|
||||
].sort((left, right) =>
|
||||
compareCodePoints(semanticOriginKey(left), semanticOriginKey(right)),
|
||||
);
|
||||
|
||||
/** Mark and return an explicit provenance-limit value. */
|
||||
export const semanticLimitProvenance = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: "maxValueDepth" | "maxUnionValues",
|
||||
): JavaScriptBindingProvenance => {
|
||||
reachSemanticValueLimit(state, limit);
|
||||
return semanticProvenance("limit-reached", [], `${limit} reached.`);
|
||||
};
|
||||
|
||||
/** Record one value-lattice limit against the shared semantic analysis state. */
|
||||
export const reachSemanticValueLimit = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
limit: keyof JavaScriptSemanticAnalysisState["limits"],
|
||||
): void => {
|
||||
state.limitsReached.add(limit);
|
||||
state.omittedCount += 1;
|
||||
};
|
||||
|
||||
const semanticOriginKey = (origin: JavaScriptModuleOrigin): string =>
|
||||
`${origin.specifier}\0${origin.importedPath.join("\0")}`;
|
||||
|
||||
/** Canonically distinguish primitive values across type boundaries. */
|
||||
export const semanticPrimitiveKey = (
|
||||
value: JavaScriptSemanticPrimitive,
|
||||
): string =>
|
||||
`${value === null ? "null" : typeof value}:${JSON.stringify(value)}`;
|
||||
@@ -0,0 +1,283 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptSemanticCallable,
|
||||
JavaScriptSemanticModuleLink,
|
||||
JavaScriptSemanticReturnSite,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
reachSemanticLimit,
|
||||
semanticCallableIdForNode,
|
||||
} from "./javascriptSemanticProjection.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
type JavaScriptSemanticAnalysisState,
|
||||
type JavaScriptSemanticBindingState,
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
|
||||
import { compareCodePoints, range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
|
||||
interface ReturnExpression {
|
||||
readonly node: t.Node | null;
|
||||
readonly location: JavaScriptSemanticReturnSite["location"];
|
||||
}
|
||||
|
||||
/** Evaluate bounded direct returns while excluding every nested callable. */
|
||||
export const collectSemanticReturns = (
|
||||
program: t.Program,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
parserPartial: boolean,
|
||||
): JavaScriptSemanticCallable[] => {
|
||||
const nodes = callableNodes(program);
|
||||
let retained = 0;
|
||||
return state.callables.map((callable) => {
|
||||
const node = nodes.get(callable.callableId);
|
||||
if (node === undefined)
|
||||
return {
|
||||
...callable,
|
||||
returnCoverage: {
|
||||
status: "partial" as const,
|
||||
retainedCount: 0,
|
||||
omittedCount: null,
|
||||
limitsReached: [],
|
||||
},
|
||||
};
|
||||
const expressions = directReturnExpressions(node);
|
||||
const sites: JavaScriptSemanticReturnSite[] = [];
|
||||
let omitted = 0;
|
||||
for (const expression of expressions) {
|
||||
if (retained >= state.limits.maxReturnSites) {
|
||||
omitted += 1;
|
||||
reachSemanticLimit(state, "maxReturnSites");
|
||||
continue;
|
||||
}
|
||||
retained += 1;
|
||||
sites.push({
|
||||
location: expression.location,
|
||||
value:
|
||||
expression.node === null
|
||||
? { status: "unknown", reason: "Return has no value." }
|
||||
: evaluateSemanticExpression(expression.node, state),
|
||||
});
|
||||
}
|
||||
return {
|
||||
...callable,
|
||||
returnSites: sites,
|
||||
returnCoverage: {
|
||||
status:
|
||||
omitted > 0 ? "truncated" : parserPartial ? "partial" : "complete",
|
||||
retainedCount: sites.length,
|
||||
omittedCount: omitted,
|
||||
limitsReached: omitted > 0 ? ["maxReturnSites"] : [],
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
/** Link exports to callables only when lexical resolution is unique and exact. */
|
||||
export const resolveSemanticModuleCallables = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
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);
|
||||
const resolved =
|
||||
binding === undefined
|
||||
? []
|
||||
: callableIdsForBinding(binding, state, callableIds, new Set());
|
||||
return {
|
||||
...link,
|
||||
callableId: resolved.length === 1 ? (resolved[0] ?? null) : null,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const callableNodes = (program: t.Program): Map<string, t.Node> => {
|
||||
const output = new Map<string, t.Node>();
|
||||
traverseJavaScriptAst(program, {
|
||||
enter: (node) => {
|
||||
const id = semanticCallableIdForNode(node);
|
||||
if (id !== null) output.set(id, node);
|
||||
},
|
||||
});
|
||||
return output;
|
||||
};
|
||||
|
||||
const directReturnExpressions = (callable: t.Node): ReturnExpression[] => {
|
||||
if (
|
||||
t.isArrowFunctionExpression(callable) &&
|
||||
!t.isBlockStatement(callable.body)
|
||||
)
|
||||
return [{ node: callable.body, location: range(callable.body) }];
|
||||
if (!t.isFunction(callable)) return [];
|
||||
const output: ReturnExpression[] = [];
|
||||
const visit = (node: t.Node): void => {
|
||||
if (t.isFunction(node) || t.isClass(node)) return;
|
||||
if (t.isReturnStatement(node)) {
|
||||
output.push({ node: node.argument ?? null, location: range(node) });
|
||||
return;
|
||||
}
|
||||
for (const child of childNodes(node)) visit(child);
|
||||
};
|
||||
for (const child of childNodes(callable.body)) visit(child);
|
||||
return output;
|
||||
};
|
||||
|
||||
const childNodes = (node: t.Node): t.Node[] =>
|
||||
(t.VISITOR_KEYS[node.type] ?? []).flatMap((key) => {
|
||||
const value: unknown = Reflect.get(node, key);
|
||||
if (t.isNode(value)) return [value];
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is t.Node => t.isNode(item))
|
||||
: [];
|
||||
});
|
||||
|
||||
const callableIdsForBinding = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
admitted: ReadonlySet<string>,
|
||||
seen: ReadonlySet<string>,
|
||||
): string[] => {
|
||||
if (seen.has(binding.bindingId) || binding.initializers.length !== 1)
|
||||
return [];
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined || initializer.projection.length > 0) return [];
|
||||
return callableIdsForNode(
|
||||
initializer.node,
|
||||
state,
|
||||
admitted,
|
||||
new Set([...seen, binding.bindingId]),
|
||||
);
|
||||
};
|
||||
|
||||
const callableIdsForNode = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
admitted: ReadonlySet<string>,
|
||||
seen: ReadonlySet<string>,
|
||||
): string[] => {
|
||||
const direct = semanticCallableIdForNode(node);
|
||||
if (direct !== null && admitted.has(direct)) return [direct];
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(state, node, node.name);
|
||||
return binding === undefined
|
||||
? []
|
||||
: callableIdsForBinding(binding, state, admitted, seen);
|
||||
}
|
||||
if (
|
||||
t.isTSAsExpression(node) ||
|
||||
t.isTSTypeAssertion(node) ||
|
||||
t.isTSNonNullExpression(node)
|
||||
)
|
||||
return callableIdsForNode(node.expression, state, admitted, seen);
|
||||
return [];
|
||||
};
|
||||
|
||||
/** Flatten a semantic value to bounded JSON-pointer leaves for graph projection. */
|
||||
export const flattenSemanticReturnValue = (
|
||||
value: JavaScriptSemanticValue,
|
||||
): {
|
||||
readonly fields: readonly {
|
||||
readonly path: string;
|
||||
readonly state: "literal" | "union" | "unknown";
|
||||
readonly value: unknown;
|
||||
readonly reason: string | null;
|
||||
}[];
|
||||
readonly propertyCoverage: readonly {
|
||||
readonly path: string;
|
||||
readonly status: "complete" | "partial";
|
||||
readonly omitted: number | null;
|
||||
}[];
|
||||
} => {
|
||||
const fields: {
|
||||
path: string;
|
||||
state: "literal" | "union" | "unknown";
|
||||
value: unknown;
|
||||
reason: string | null;
|
||||
}[] = [];
|
||||
const propertyCoverage: {
|
||||
path: string;
|
||||
status: "complete" | "partial";
|
||||
omitted: number | null;
|
||||
}[] = [];
|
||||
flattenValue(value, "", fields, propertyCoverage);
|
||||
fields.sort((left, right) => compareCodePoints(left.path, right.path));
|
||||
propertyCoverage.sort((left, right) =>
|
||||
compareCodePoints(left.path, right.path),
|
||||
);
|
||||
return { fields, propertyCoverage };
|
||||
};
|
||||
|
||||
const flattenValue = (
|
||||
value: JavaScriptSemanticValue,
|
||||
path: string,
|
||||
fields: {
|
||||
path: string;
|
||||
state: "literal" | "union" | "unknown";
|
||||
value: unknown;
|
||||
reason: string | null;
|
||||
}[],
|
||||
coverage: {
|
||||
path: string;
|
||||
status: "complete" | "partial";
|
||||
omitted: number | null;
|
||||
}[],
|
||||
): void => {
|
||||
if (value.status === "literal") {
|
||||
fields.push({ path, state: "literal", value: value.value, reason: null });
|
||||
return;
|
||||
}
|
||||
if (value.status === "union") {
|
||||
fields.push({
|
||||
path,
|
||||
state: "union",
|
||||
value: [...value.values],
|
||||
reason: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (value.status === "object") {
|
||||
coverage.push({
|
||||
path,
|
||||
status: value.unknownProperties ? "partial" : "complete",
|
||||
omitted: value.omittedProperties,
|
||||
});
|
||||
for (const property of value.properties)
|
||||
flattenValue(
|
||||
property.value,
|
||||
`${path}/${escapePointer(property.name)}`,
|
||||
fields,
|
||||
coverage,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (value.status === "array") {
|
||||
coverage.push({
|
||||
path,
|
||||
status: value.unknownItems ? "partial" : "complete",
|
||||
omitted: value.omittedItems,
|
||||
});
|
||||
value.items.forEach((item, index) =>
|
||||
flattenValue(item, `${path}/${String(index)}`, fields, coverage),
|
||||
);
|
||||
return;
|
||||
}
|
||||
fields.push({ path, state: "unknown", value: null, reason: value.reason });
|
||||
};
|
||||
|
||||
const escapePointer = (value: string): string =>
|
||||
value.replaceAll("~", "~0").replaceAll("/", "~1");
|
||||
@@ -1,4 +1,4 @@
|
||||
import type * as t from "@babel/types";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
JavaScriptModuleOrigin,
|
||||
@@ -102,3 +102,42 @@ export const semanticResolutionBlocked = (
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Resolve one name starting from an explicitly selected lexical scope. */
|
||||
export const resolveSemanticBindingFromScope = (
|
||||
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;
|
||||
};
|
||||
|
||||
/** Select the function/program owner for a var declaration. */
|
||||
export const semanticVariableScope = (
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as t from "@babel/types";
|
||||
import type {
|
||||
JavaScriptBindingProvenance,
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticPrimitive,
|
||||
JavaScriptSemanticProperty,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
@@ -17,6 +16,18 @@ import {
|
||||
propertyName,
|
||||
stringValue,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import {
|
||||
reachSemanticValueLimit,
|
||||
semanticLimitProvenance,
|
||||
semanticOriginsProvenance,
|
||||
semanticProvenance,
|
||||
uniqueSemanticOrigins,
|
||||
} from "./javascriptSemanticProvenance.js";
|
||||
import {
|
||||
semanticPrimitiveCandidates as primitiveCandidates,
|
||||
semanticPrimitiveSet as primitiveSet,
|
||||
semanticPrimitiveValue as primitiveValue,
|
||||
} from "./javascriptSemanticPrimitives.js";
|
||||
|
||||
interface EvaluationContext {
|
||||
readonly state: JavaScriptSemanticAnalysisState;
|
||||
@@ -31,6 +42,13 @@ export const evaluateSemanticBinding = (
|
||||
): JavaScriptSemanticValue =>
|
||||
evaluateBinding(binding, { state, bindings: new Set(), depth: 0 });
|
||||
|
||||
/** Evaluate one arbitrary inert expression in the established lexical state. */
|
||||
export const evaluateSemanticExpression = (
|
||||
node: t.Node,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticValue =>
|
||||
evaluateExpression(node, { state, bindings: new Set(), depth: 0 });
|
||||
|
||||
/** Follow module provenance through destructuring, members, and aliases. */
|
||||
export const evaluateSemanticProvenance = (
|
||||
binding: JavaScriptSemanticBindingState,
|
||||
@@ -148,19 +166,28 @@ const evaluateObject = (
|
||||
): JavaScriptSemanticValue => {
|
||||
const properties: JavaScriptSemanticProperty[] = [];
|
||||
let unknownProperties = false;
|
||||
let omittedProperties: number | null = 0;
|
||||
for (const property of node.properties) {
|
||||
if (t.isSpreadElement(property) || property.computed) {
|
||||
if (t.isSpreadElement(property)) {
|
||||
unknownProperties = true;
|
||||
omittedProperties = null;
|
||||
continue;
|
||||
}
|
||||
if (property.computed) {
|
||||
unknownProperties = true;
|
||||
if (omittedProperties !== null) omittedProperties += 1;
|
||||
continue;
|
||||
}
|
||||
const name = propertyName(property.key);
|
||||
if (name === "" || !t.isObjectProperty(property)) {
|
||||
unknownProperties = true;
|
||||
if (omittedProperties !== null) omittedProperties += 1;
|
||||
continue;
|
||||
}
|
||||
if (properties.length >= context.state.limits.maxObjectProperties) {
|
||||
markLimit(context.state, "maxObjectProperties");
|
||||
reachSemanticValueLimit(context.state, "maxObjectProperties");
|
||||
unknownProperties = true;
|
||||
if (omittedProperties !== null) omittedProperties += 1;
|
||||
continue;
|
||||
}
|
||||
properties.push({
|
||||
@@ -169,7 +196,12 @@ const evaluateObject = (
|
||||
});
|
||||
}
|
||||
properties.sort((left, right) => compareCodePoints(left.name, right.name));
|
||||
return { status: "object", properties, unknownProperties };
|
||||
return {
|
||||
status: "object",
|
||||
properties,
|
||||
unknownProperties,
|
||||
omittedProperties,
|
||||
};
|
||||
};
|
||||
|
||||
const evaluateArray = (
|
||||
@@ -178,19 +210,27 @@ const evaluateArray = (
|
||||
): JavaScriptSemanticValue => {
|
||||
const items: JavaScriptSemanticValue[] = [];
|
||||
let unknownItems = false;
|
||||
let omittedItems: number | null = 0;
|
||||
for (const element of node.elements) {
|
||||
if (element === null || t.isSpreadElement(element)) {
|
||||
if (t.isSpreadElement(element)) {
|
||||
unknownItems = true;
|
||||
omittedItems = null;
|
||||
continue;
|
||||
}
|
||||
if (element === null) {
|
||||
unknownItems = true;
|
||||
if (omittedItems !== null) omittedItems += 1;
|
||||
continue;
|
||||
}
|
||||
if (items.length >= context.state.limits.maxObjectProperties) {
|
||||
markLimit(context.state, "maxObjectProperties");
|
||||
reachSemanticValueLimit(context.state, "maxObjectProperties");
|
||||
unknownItems = true;
|
||||
if (omittedItems !== null) omittedItems += 1;
|
||||
continue;
|
||||
}
|
||||
items.push(evaluateExpression(element, nestedContext(context)));
|
||||
}
|
||||
return { status: "array", items, unknownItems };
|
||||
return { status: "array", items, unknownItems, omittedItems };
|
||||
};
|
||||
|
||||
const evaluateMember = (
|
||||
@@ -297,30 +337,31 @@ const provenanceForBinding = (
|
||||
context: EvaluationContext,
|
||||
): JavaScriptBindingProvenance => {
|
||||
if (context.bindings.has(binding.bindingId))
|
||||
return provenance("cycle", [], `Alias cycle at ${binding.name}.`);
|
||||
return semanticProvenance("cycle", [], `Alias cycle at ${binding.name}.`);
|
||||
if (context.depth >= context.state.limits.maxValueDepth)
|
||||
return limitProvenance(context.state, "maxValueDepth");
|
||||
return semanticLimitProvenance(context.state, "maxValueDepth");
|
||||
if (binding.directOrigins.length > 0)
|
||||
return originsProvenance(binding.directOrigins, context.state);
|
||||
if (binding.initializers.length === 0) return provenance("local", [], null);
|
||||
return semanticOriginsProvenance(binding.directOrigins, context.state);
|
||||
if (binding.initializers.length === 0)
|
||||
return semanticProvenance("local", [], null);
|
||||
if (binding.initializers.length > 1)
|
||||
return provenance(
|
||||
return semanticProvenance(
|
||||
"ambiguous",
|
||||
[],
|
||||
`Binding ${binding.name} has multiple possible assignments.`,
|
||||
);
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined)
|
||||
return provenance("unknown", [], "Missing binding initializer.");
|
||||
return semanticProvenance("unknown", [], "Missing binding initializer.");
|
||||
if (initializer.projection.includes(null))
|
||||
return provenance("unknown", [], "Dynamic provenance projection.");
|
||||
return semanticProvenance("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(
|
||||
return semanticOriginsProvenance(
|
||||
resolved.origins.map((origin) => ({
|
||||
...origin,
|
||||
importedPath: [
|
||||
@@ -338,23 +379,23 @@ const provenanceForExpression = (
|
||||
): JavaScriptBindingProvenance => {
|
||||
const required = requireOrigin(node);
|
||||
if (required !== undefined)
|
||||
return originsProvenance([required], context.state);
|
||||
return semanticOriginsProvenance([required], context.state);
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(context.state, node, node.name);
|
||||
return binding === undefined
|
||||
? provenance("unknown", [], `Unbound identifier ${node.name}.`)
|
||||
? semanticProvenance("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.");
|
||||
return semanticProvenance("unknown", [], "Unsupported member base.");
|
||||
const member = memberKey(node);
|
||||
if (typeof member !== "string")
|
||||
return provenance("unknown", [], "Dynamic provenance member.");
|
||||
return semanticProvenance("unknown", [], "Dynamic provenance member.");
|
||||
const base = provenanceForExpression(node.object, nestedContext(context));
|
||||
return base.status !== "module"
|
||||
? base
|
||||
: originsProvenance(
|
||||
: semanticOriginsProvenance(
|
||||
base.origins.map((origin) => ({
|
||||
...origin,
|
||||
importedPath: [...origin.importedPath, member],
|
||||
@@ -371,14 +412,18 @@ const provenanceForExpression = (
|
||||
];
|
||||
const origins = candidates.flatMap((candidate) => candidate.origins);
|
||||
return origins.length > 0
|
||||
? provenance(
|
||||
? semanticProvenance(
|
||||
"ambiguous",
|
||||
uniqueOrigins(origins),
|
||||
uniqueSemanticOrigins(origins),
|
||||
"Multiple module origins.",
|
||||
)
|
||||
: provenance("unknown", [], "Conditional provenance is unresolved.");
|
||||
: semanticProvenance(
|
||||
"unknown",
|
||||
[],
|
||||
"Conditional provenance is unresolved.",
|
||||
);
|
||||
}
|
||||
return provenance("local", [], null);
|
||||
return semanticProvenance("local", [], null);
|
||||
};
|
||||
|
||||
const requireOrigin = (node: t.Node): JavaScriptModuleOrigin | undefined => {
|
||||
@@ -414,44 +459,6 @@ const mergeValues = (
|
||||
: { 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 => {
|
||||
@@ -461,55 +468,14 @@ const memberKey = (
|
||||
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);
|
||||
reachSemanticValueLimit(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,
|
||||
@@ -521,9 +487,3 @@ const nestedContext = (
|
||||
? 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