(source, "Top");
+ try {
+ const clk = sim.event("clk");
+ sim.negedge(clk);
+ reset(sim);
+ const observed = enables.map((enable) => {
+ sim.dut.en_in = enable;
+ sim.cycle(clk);
+ return [sim.dut.a_out, sim.dut.b_out, sim.dut.d_out];
+ });
+ expect(observed).toEqual(expected);
+ } finally {
+ sim.dispose();
+ }
+ });
+
+ test("coincident edges sample the state before them", () => {
+ const sim = Simulator.fromSource<{ a: bigint; b: bigint }>(
+ `module Top (a_clk: input '_ clock, b_clk: input '_ clock, rst: input '_ reset_async_low,
+ a: output logic<8>, b: output logic<8>) {
+ var ra: logic<8>;
+ var rb: logic<8>;
+ always_ff (a_clk, rst) { if_reset { ra = 3; } else { ra = rb + 8'd1; } }
+ always_ff (b_clk, rst) { if_reset { rb = 5; } else { rb = ra + 8'd2; } }
+ assign a = ra;
+ assign b = rb;
+}`,
+ "Top",
+ );
+ try {
+ const [aClk, bClk] = [sim.event("a_clk"), sim.event("b_clk")];
+ sim.edges([
+ [aClk, "negedge"],
+ [bClk, "negedge"],
+ ]);
+ reset(sim);
+ sim.edges([
+ [aClk, "posedge"],
+ [bClk, "posedge"],
+ ]);
+ expect([sim.dut.a, sim.dut.b]).toEqual([6n, 5n]);
+ expect(() => sim.edges([[aClk, "sideways" as "posedge"]])).toThrow(
+ RangeError,
+ );
+ } finally {
+ sim.dispose();
+ }
+ });
+});
diff --git a/packages/celox/src/simulator.ts b/packages/celox/src/simulator.ts
index 5d34faeb0a6..d174b5f54df 100644
--- a/packages/celox/src/simulator.ts
+++ b/packages/celox/src/simulator.ts
@@ -19,6 +19,7 @@ import {
wrapDirectSimulatorHandle,
} from "./napi-helpers.js";
import type {
+ ClockEdge,
CreateResult,
EventHandle,
FourStateValue,
@@ -519,6 +520,98 @@ export class Simulator> {
}
}
+ /**
+ * Move a clock's signal to 1 and run every domain sensitive to that
+ * rising edge: its own domain when the edge is its active edge, clocks
+ * computed combinationally from it (sampling the state before the edge),
+ * and the domains the commit clocks in turn. The signal stays high; an
+ * edge to the level the signal already has does nothing.
+ *
+ * @param event Event handle or known raw event ID. Defaults to the first
+ * event.
+ */
+ posedge(event?: EventHandle | number): void {
+ this.edges([[this.resolveEventId(event), "posedge"]]);
+ }
+
+ /** Move a clock's signal to 0; see `posedge()`. */
+ negedge(event?: EventHandle | number): void {
+ this.edges([[this.resolveEventId(event), "negedge"]]);
+ }
+
+ /**
+ * The event's active edge: rising for a positive-edge clock or an
+ * active-high reset (including Veryl's `clock` under a `posedge` clock
+ * type), falling otherwise. See `posedge()`.
+ */
+ activeEdge(event?: EventHandle | number): void {
+ const id = this.resolveEventId(event);
+ this.edges([[id, this.activeIsRising(id) ? "posedge" : "negedge"]]);
+ }
+
+ /** The edge opposite to the event's active edge. See `posedge()`. */
+ inactiveEdge(event?: EventHandle | number): void {
+ const id = this.resolveEventId(event);
+ this.edges([[id, this.activeIsRising(id) ? "negedge" : "posedge"]]);
+ }
+
+ /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */
+ cycle(event?: EventHandle | number): void {
+ this.activeEdge(event);
+ this.inactiveEdge(event);
+ }
+
+ /**
+ * Move several event signals at one instant. Every domain sensitive to
+ * one of the edges evaluates against the state before them, then all of
+ * them commit, as coincident edges in hardware.
+ */
+ edges(
+ moves: ReadonlyArray,
+ ): void {
+ this.ensureAlive();
+ const handle = this._handle;
+ if (!handle.edges) {
+ throw new Error("This simulator backend does not support explicit edges");
+ }
+ const ids: number[] = [];
+ const rising: boolean[] = [];
+ for (const [event, edge] of moves) {
+ const id = typeof event === "number" ? event : event.id;
+ this.assertKnownEventId(id);
+ if (edge !== "posedge" && edge !== "negedge") {
+ throw new RangeError(`Unknown clock edge '${String(edge)}'`);
+ }
+ ids.push(id);
+ rising.push(edge === "posedge");
+ }
+ // The handle settles first only when needed, and leaves
+ // combinational logic as it was when no domain ran and nothing
+ // combinational reads the moved signals.
+ this._state.dirty = !handle.edges(ids, rising, this._state.dirty);
+ }
+
+ private resolveEventId(event: EventHandle | number | undefined): number {
+ this.ensureAlive();
+ if (event === undefined) {
+ if (this._eventIds.size === 0) {
+ throw new Error("Simulator has no events");
+ }
+ return this._defaultEventId;
+ }
+ const id = typeof event === "number" ? event : event.id;
+ this.assertKnownEventId(id);
+ return id;
+ }
+
+ private activeIsRising(eventId: number): boolean {
+ const handle = this._handle;
+ if (!handle.activeEdgeIsRising) {
+ throw new Error("This simulator backend does not support explicit edges");
+ }
+ return handle.activeEdgeIsRising(eventId);
+ }
+
/** Resolve an event name to a handle for use with `tick()`. */
event(name: string): EventHandle {
const id = this._events[name];
diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts
index 278c5291b36..c5f3c9e58ad 100644
--- a/packages/celox/src/types.ts
+++ b/packages/celox/src/types.ts
@@ -117,6 +117,16 @@ export interface NativeFrontendSimulatorHandle
extends FrontendSimulatorHandleMetadata {
tick(eventId: number): void;
tickN(eventId: number, count: number): void;
+ /**
+ * Move event signals through coincident edges and run every domain
+ * sensitive to them: `rising[i]` gives the direction of `eventIds[i]`.
+ * `dirty` says whether combinational logic has pending changes (default
+ * `true`: it settles first). Returns whether combinational logic is
+ * settled afterwards. Absent on addons without explicit edges.
+ */
+ edges?(eventIds: number[], rising: boolean[], dirty?: boolean): boolean;
+ /** Whether the event's active edge is rising. */
+ activeEdgeIsRising?(eventId: number): boolean;
evalComb(): void;
dump(timestamp: number): void;
sharedMemory(): Uint8Array;
@@ -141,6 +151,16 @@ export interface WasmFrontendSimulatorHandle
initialMemoryBytes(): Uint8Array | number[];
combWasmBytes(): Uint8Array | number[];
eventWasmBytes(name: string): Uint8Array | number[];
+ /**
+ * Per event name, the derived domains its ticks and edges run, as JSON.
+ * Absent on addons that predate explicit edges.
+ */
+ edgePlansJson?(): string;
+ /** The `"evalOnly"` or `"apply"` phase module of an event's kernels. */
+ eventPhaseWasmBytes?(
+ name: string,
+ phase: "evalOnly" | "apply",
+ ): Uint8Array | number[];
/**
* Offset where the checkpointable design state starts (it ends at
* `stableSize`). Absent on addons without checkpoint support.
@@ -170,6 +190,16 @@ export type FrontendSimulatorHandle =
export interface NativeSimulatorHandle {
tick(eventId: number): void;
tickN(eventId: number, count: number): void;
+ /**
+ * Move event signals through coincident edges and run every domain
+ * sensitive to them: `rising[i]` gives the direction of `eventIds[i]`.
+ * `dirty` says whether combinational logic has pending changes (default
+ * `true`: it settles first). Returns whether combinational logic is
+ * settled afterwards. Absent on addons without explicit edges.
+ */
+ edges?(eventIds: number[], rising: boolean[], dirty?: boolean): boolean;
+ /** Whether the event's active edge is rising. */
+ activeEdgeIsRising?(eventId: number): boolean;
evalComb(): void;
dump(timestamp: number): void;
dispose(): void;
@@ -396,6 +426,9 @@ export interface EventHandle {
readonly id: number;
}
+/** A transition of a clock or reset signal. */
+export type ClockEdge = "posedge" | "negedge";
+
// ---------------------------------------------------------------------------
// 4-state helpers
// ---------------------------------------------------------------------------
diff --git a/packages/celox/src/wasm-bridge.ts b/packages/celox/src/wasm-bridge.ts
index e94437517ed..38dd368825b 100644
--- a/packages/celox/src/wasm-bridge.ts
+++ b/packages/celox/src/wasm-bridge.ts
@@ -16,6 +16,11 @@ import type {
NativeSimulatorHandle,
WasmFrontendSimulatorHandle,
} from "./types.js";
+import {
+ cachedEdgeKernels,
+ type EdgePlans,
+ WasmEdgeRunner,
+} from "./wasm-edges.js";
// ---------------------------------------------------------------------------
// Minimal WebAssembly type declarations for environments without DOM lib.
@@ -123,6 +128,64 @@ function wasmCheckpointMethods(
};
}
+/**
+ * The module of an event's own domain, or `undefined` for an event without
+ * one (a clock that only drives a gated clock).
+ */
+function eventBytes(
+ raw: RawWasmSimulatorHandle,
+ name: string,
+): Uint8Array | undefined {
+ try {
+ return new Uint8Array(raw.eventWasmBytes(name));
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * The edge runner of a bridge, when the raw handle provides edge plans.
+ * Phase modules of split kernels are compiled on first use.
+ */
+function wasmEdgeRunner(
+ raw: RawWasmSimulatorHandle,
+ memory: WebAssembly.Memory,
+ events: Record,
+ eventInstances: Map,
+ evalComb: () => void,
+): WasmEdgeRunner | undefined {
+ if (!raw.edgePlansJson) return undefined;
+ const plans = JSON.parse(raw.edgePlansJson()) as EdgePlans;
+ const run = (instance: WebAssembly.Instance) => () =>
+ (instance.exports.run as CallableFunction)();
+ const phase = (name: string, kind: "evalOnly" | "apply") => {
+ if (!raw.eventPhaseWasmBytes) return undefined;
+ try {
+ const bytes = new Uint8Array(raw.eventPhaseWasmBytes(name, kind));
+ const module = new WebAssembly.Module(bytes);
+ return run(new WebAssembly.Instance(module, { env: { memory } }));
+ } catch {
+ return undefined;
+ }
+ };
+ const kernels = cachedEdgeKernels((name) => {
+ const id = events[name];
+ const instance = id === undefined ? undefined : eventInstances.get(id);
+ return instance ? run(instance) : undefined;
+ }, phase);
+ return new WasmEdgeRunner(memory, plans, events, kernels, evalComb);
+}
+
+function edgeMethods(
+ edges: WasmEdgeRunner | undefined,
+): Pick {
+ if (!edges) return {};
+ return {
+ edges: (eventIds, rising, dirty) => edges.edges(eventIds, rising, dirty),
+ activeEdgeIsRising: (eventId) => edges.activeEdgeIsRising(eventId),
+ };
+}
+
/** Result of creating a WASM simulator bridge. */
export interface WasmBridgeResult {
/** Handle compatible with the existing Simulator code. */
@@ -168,7 +231,8 @@ export function createWasmSimulatorBridge(
const eventInstances = new Map();
for (const [name, id] of Object.entries(events)) {
- const bytes = new Uint8Array(raw.eventWasmBytes(name));
+ const bytes = eventBytes(raw, name);
+ if (!bytes) continue;
const mod = new WebAssembly.Module(bytes);
const inst = new WebAssembly.Instance(mod, { env: { memory } });
eventInstances.set(id, inst);
@@ -176,14 +240,22 @@ export function createWasmSimulatorBridge(
const sharedMemory = new Uint8Array(memory.buffer, 0, stableSize);
+ const edges = wasmEdgeRunner(raw, memory, events, eventInstances, () =>
+ (combInstance.exports.run as CallableFunction)(),
+ );
const handle: NativeSimulatorHandle = {
tick(eventId: number): void {
+ if (edges?.hasDerived(eventId)) {
+ edges.tick(eventId);
+ return;
+ }
// eval_comb → eval_apply_ff → eval_comb
(combInstance.exports.run as CallableFunction)();
const evInst = eventInstances.get(eventId);
if (evInst) (evInst.exports.run as CallableFunction)();
(combInstance.exports.run as CallableFunction)();
},
+ ...edgeMethods(edges),
tickN(eventId: number, count: number): void {
for (let i = 0; i < count; i++) {
this.tick(eventId);
@@ -239,7 +311,8 @@ export async function createWasmSimulatorBridgeAsync(
const eventEntries = Object.entries(events);
await Promise.all(
eventEntries.map(async ([name, id]) => {
- const bytes = new Uint8Array(raw.eventWasmBytes(name));
+ const bytes = eventBytes(raw, name);
+ if (!bytes) return;
const mod = await WebAssembly.compile(bytes);
const inst = await WebAssembly.instantiate(mod, { env: { memory } });
eventInstances.set(id, inst);
@@ -248,13 +321,21 @@ export async function createWasmSimulatorBridgeAsync(
const sharedMemory = new Uint8Array(memory.buffer, 0, stableSize);
+ const edges = wasmEdgeRunner(raw, memory, events, eventInstances, () =>
+ (combInstance.exports.run as CallableFunction)(),
+ );
const handle: NativeSimulatorHandle = {
tick(eventId: number): void {
+ if (edges?.hasDerived(eventId)) {
+ edges.tick(eventId);
+ return;
+ }
(combInstance.exports.run as CallableFunction)();
const evInst = eventInstances.get(eventId);
if (evInst) (evInst.exports.run as CallableFunction)();
(combInstance.exports.run as CallableFunction)();
},
+ ...edgeMethods(edges),
tickN(eventId: number, count: number): void {
for (let i = 0; i < count; i++) {
this.tick(eventId);
diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts
new file mode 100644
index 00000000000..3a1d25270a2
--- /dev/null
+++ b/packages/celox/src/wasm-edges.test.ts
@@ -0,0 +1,189 @@
+import { expect, test, vi } from "vitest";
+import {
+ createWasmSimulatorBridge,
+ type RawWasmSimulatorHandle,
+} from "./wasm-bridge.js";
+import type { EdgePlans } from "./wasm-edges.js";
+
+// Memory map of a small design driven by hand-written WASM modules:
+// `gated = clk & en`, `inverted = ~clk`, and one counter per domain.
+const CLK = 0;
+const EN = 1;
+const GATED = 2;
+const INVERTED = 3;
+const RISING = 8;
+const GATED_COUNT = 9;
+const FALLING = 10;
+
+const I32_CONST = 0x41;
+const LOAD8 = [0x2d, 0x00, 0x00];
+const STORE8 = [0x3a, 0x00, 0x00];
+
+/** A module exporting `run`, which executes `body` over the shared memory. */
+function module(body: number[]): Uint8Array {
+ const code = [0x00, ...body, 0x0b];
+ return new Uint8Array([
+ ...[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
+ ...[0x01, 0x04, 0x01, 0x60, 0x00, 0x00],
+ ...[0x02, 0x0f, 0x01, 0x03, 0x65, 0x6e, 0x76],
+ ...[0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x01],
+ ...[0x03, 0x02, 0x01, 0x00],
+ ...[0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x00],
+ ...[0x0a, code.length + 2, 0x01, code.length, ...code],
+ ]);
+}
+
+/** `mem[target] = mem[target] + 1`. */
+const increment = (target: number) => [
+ I32_CONST,
+ target,
+ I32_CONST,
+ target,
+ ...LOAD8,
+ I32_CONST,
+ 1,
+ 0x6a,
+ ...STORE8,
+];
+
+// gated = clk & en; inverted = (clk ^ 1) & 1
+const comb = module([
+ I32_CONST,
+ GATED,
+ I32_CONST,
+ CLK,
+ ...LOAD8,
+ I32_CONST,
+ EN,
+ ...LOAD8,
+ 0x71,
+ ...STORE8,
+ I32_CONST,
+ INVERTED,
+ I32_CONST,
+ CLK,
+ ...LOAD8,
+ I32_CONST,
+ 1,
+ 0x73,
+ I32_CONST,
+ 1,
+ 0x71,
+ ...STORE8,
+]);
+
+const PLANS: EdgePlans = {
+ fourState: false,
+ events: {
+ clk: {
+ signal: { offset: CLK, width: 1 },
+ edge: "posedge",
+ combRead: true,
+ domains: [],
+ gated: [
+ {
+ event: "gated",
+ signal: { offset: GATED, width: 1 },
+ edge: "posedge",
+ },
+ {
+ event: "inverted",
+ signal: { offset: INVERTED, width: 1 },
+ edge: "posedge",
+ },
+ ],
+ },
+ gated: {
+ signal: { offset: GATED, width: 1 },
+ edge: "posedge",
+ combRead: false,
+ domains: [],
+ gated: [],
+ },
+ inverted: {
+ signal: { offset: INVERTED, width: 1 },
+ edge: "posedge",
+ combRead: false,
+ domains: [],
+ gated: [],
+ },
+ },
+};
+
+function raw(plans: EdgePlans | undefined): RawWasmSimulatorHandle {
+ const kernels: Record = {
+ clk: module(increment(RISING)),
+ gated: module(increment(GATED_COUNT)),
+ inverted: module(increment(FALLING)),
+ };
+ const initial = new Uint8Array(16);
+ initial[INVERTED] = 1;
+ return {
+ layoutJson: "{}",
+ eventsJson: JSON.stringify({ clk: 0, gated: 1, inverted: 2 }),
+ hierarchyJson: "{}",
+ warningsJson: "[]",
+ stableSize: 16,
+ totalSize: 16,
+ dispose: vi.fn(),
+ initialMemoryBytes: () => initial,
+ combWasmBytes: () => comb,
+ eventWasmBytes: (name: string) => kernels[name],
+ ...(plans ? { edgePlansJson: () => JSON.stringify(plans) } : {}),
+ };
+}
+
+test("the WASM bridge ticks and moves clocks as the native simulator does", () => {
+ const { handle, sharedMemory } = createWasmSimulatorBridge(raw(PLANS));
+ const counters = () => [
+ sharedMemory[RISING],
+ sharedMemory[GATED_COUNT],
+ sharedMemory[FALLING],
+ ];
+ sharedMemory[EN] = 1;
+ handle.evalComb();
+
+ // A tick is the active edge only: the gate passes it, `~clk` does not
+ // rise, and `clk` stays low.
+ handle.tick(0);
+ expect(counters()).toEqual([1, 1, 0]);
+ expect(sharedMemory[CLK]).toBe(0);
+
+ expect(handle.activeEdgeIsRising?.(0)).toBe(true);
+ expect(handle.edges?.([0], [true])).toBe(true);
+ expect(counters()).toEqual([2, 2, 0]);
+ expect(sharedMemory[CLK]).toBe(1);
+ // Already high: no edge.
+ handle.edges?.([0], [true]);
+ expect(counters()).toEqual([2, 2, 0]);
+ handle.edges?.([0], [false]);
+ expect(counters()).toEqual([2, 2, 1]);
+
+ // A closed gate passes no edge.
+ sharedMemory[EN] = 0;
+ handle.evalComb();
+ handle.edges?.([0], [true]);
+ handle.edges?.([0], [false]);
+ expect(counters()).toEqual([3, 2, 2]);
+});
+
+test("a bridge without edge plans keeps the plain tick", () => {
+ const { handle, sharedMemory } = createWasmSimulatorBridge(raw(undefined));
+ sharedMemory[EN] = 1;
+ handle.tick(0);
+ expect([sharedMemory[RISING], sharedMemory[GATED_COUNT]]).toEqual([1, 0]);
+ expect(handle.edges).toBeUndefined();
+});
+
+test("edges of a clock combinational logic does not read keep it settled", () => {
+ const { handle, sharedMemory } = createWasmSimulatorBridge(raw(PLANS));
+ handle.evalComb();
+ // `gated` only clocks its counter: its falling edge runs nothing and
+ // leaves combinational logic as it was.
+ expect(handle.edges?.([1], [true], false)).toBe(true);
+ expect(sharedMemory[GATED_COUNT]).toBe(1);
+ expect(handle.edges?.([1], [false], false)).toBe(true);
+ expect(handle.edges?.([1], [false], true)).toBe(false);
+ expect(handle.edges?.([1], [true], true)).toBe(true);
+ expect(sharedMemory[GATED_COUNT]).toBe(2);
+});
diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts
new file mode 100644
index 00000000000..ee31deee116
--- /dev/null
+++ b/packages/celox/src/wasm-edges.ts
@@ -0,0 +1,431 @@
+/**
+ * Ticks and clock edges for simulators whose WASM event modules run in
+ * JavaScript (browser and WASI builds).
+ *
+ * These follow the rules of the native `Simulator`, from the same build-time
+ * plans (`edgePlansJson()` of the raw handle):
+ *
+ * - An edge runs the event's own domain when it is the domain's active edge.
+ * - Clocks computed combinationally from the event's signal (such as
+ * `clk & en` or `~clk`) are judged from the state before the edge with the
+ * signal at its new level, and their domains evaluate together with the
+ * event's own, against the same state, before any of them commits.
+ * - After the commit, every domain whose clock then moved to its active edge
+ * runs, in rounds, until no further edge appears: domains clocked from
+ * state, and gates the commit moved.
+ * - `tick` is the event's active edge without moving its signal. An edge
+ * moves the signal and leaves it at its new level.
+ *
+ * Gates are judged by settling the design with the signal at each level.
+ *
+ * @module
+ */
+
+/** The memory the kernels share. */
+export interface EdgeMemory {
+ readonly buffer: ArrayBuffer;
+}
+
+/** A one-bit event signal in the packed memory layout. */
+export interface EdgePlanSignal {
+ readonly offset: number;
+ readonly width: number;
+}
+
+/** The active edge of a domain, or `"any"` for a domain of unknown kind. */
+export type EdgePlanEdge = "posedge" | "negedge" | "any";
+
+/** A derived event domain. */
+export interface EdgePlanDomain {
+ readonly event: string;
+ readonly signal: EdgePlanSignal;
+ readonly edge: EdgePlanEdge;
+}
+
+/** What an edge of one event runs besides the event's own domain. */
+export interface EdgePlanEvent {
+ readonly signal: EdgePlanSignal;
+ readonly edge: EdgePlanEdge;
+ readonly combRead: boolean;
+ readonly domains: readonly EdgePlanDomain[];
+ readonly gated: readonly EdgePlanDomain[];
+}
+
+/** Per event name, its edge plan (`celox::EdgePlans`). */
+export interface EdgePlans {
+ readonly fourState: boolean;
+ readonly events: Readonly>;
+}
+
+/** One compiled kernel: runs a module's `run` export. */
+export type KernelRun = () => void;
+
+/** The kernels of one event domain. */
+export interface EdgeKernels {
+ /** Evaluate and commit the domain. */
+ evalApply(): void;
+ /** Evaluate the domain's next state without committing it. */
+ evalOnly?(): void;
+ /** Commit what `evalOnly()` evaluated. */
+ apply?(): void;
+}
+
+/**
+ * Kernels looked up by event name on first use and cached: `evalApply(name)`
+ * runs the event's domain, `phase(name, kind)` one phase of its split
+ * kernels. An event without a domain of its own (a clock that only drives a
+ * gated clock) has no kernels.
+ */
+export function cachedEdgeKernels(
+ evalApply: (name: string) => KernelRun | undefined,
+ phase: (name: string, kind: "evalOnly" | "apply") => KernelRun | undefined,
+): (name: string) => EdgeKernels | undefined {
+ const cache = new Map();
+ return (name) => {
+ if (cache.has(name)) return cache.get(name);
+ const run = evalApply(name);
+ let kernels: EdgeKernels | undefined;
+ if (run) {
+ const evalOnly = phase(name, "evalOnly");
+ const apply = phase(name, "apply");
+ kernels =
+ evalOnly && apply
+ ? { evalApply: run, evalOnly, apply }
+ : { evalApply: run };
+ }
+ cache.set(name, kernels);
+ return kernels;
+ };
+}
+
+/** One entry of a cascade round: a domain and the level it last had. */
+interface RoundEntry {
+ readonly domain: EdgePlanDomain;
+ was: boolean;
+ fired: boolean;
+}
+
+/** A signal moved by an edge, with its level before and after. */
+interface Lever {
+ readonly signal: EdgePlanSignal;
+ readonly from: number;
+ readonly to: number;
+}
+
+function stableEdge(edge: EdgePlanEdge, was: boolean, is: boolean): boolean {
+ switch (edge) {
+ case "posedge":
+ return !was && is;
+ case "negedge":
+ return was && !is;
+ default:
+ return was !== is;
+ }
+}
+
+/**
+ * Edge execution over a shared memory and per-event kernels.
+ */
+export class WasmEdgeRunner {
+ private readonly memory: EdgeMemory;
+ private readonly plans: EdgePlans;
+ private readonly eventNames: Map;
+ private readonly kernels: (name: string) => EdgeKernels | undefined;
+ private readonly evalComb: () => void;
+
+ constructor(
+ memory: EdgeMemory,
+ plans: EdgePlans,
+ events: Readonly>,
+ kernels: (name: string) => EdgeKernels | undefined,
+ evalComb: () => void,
+ ) {
+ this.memory = memory;
+ this.plans = plans;
+ this.eventNames = new Map(
+ Object.entries(events).map(([name, id]) => [id, name]),
+ );
+ this.kernels = kernels;
+ this.evalComb = evalComb;
+ }
+
+ /** Whether ticks of the event can run derived domains. */
+ hasDerived(eventId: number): boolean {
+ const plan = this.plan(eventId);
+ return !!plan && (plan.domains.length > 0 || plan.gated.length > 0);
+ }
+
+ /** Whether the event's active edge is a rising one. */
+ activeEdgeIsRising(eventId: number): boolean {
+ return this.plan(eventId)?.edge !== "negedge";
+ }
+
+ /** The event's active edge without moving its signal, as `tick`. */
+ tick(eventId: number): void {
+ const name = this.name(eventId);
+ const plan = this.plan(eventId);
+ if (!plan || !this.hasDerived(eventId)) {
+ this.evalComb();
+ this.kernels(name)?.evalApply();
+ this.evalComb();
+ return;
+ }
+ const active = plan.edge === "negedge" ? 0 : 1;
+ const levers: Lever[] =
+ plan.gated.length > 0
+ ? [{ signal: plan.signal, from: active ^ 1, to: active }]
+ : [];
+ this.run(
+ [name],
+ plan.domains,
+ plan.gated.map((g) => [g, 0]),
+ levers,
+ {
+ settle: true,
+ persist: false,
+ },
+ );
+ }
+
+ /**
+ * Move event signals at one instant; `rising[i]` gives the direction of
+ * `eventIds[i]`. `dirty` says whether combinational logic has pending
+ * changes. Returns whether combinational logic is settled afterwards:
+ * moving a signal that combinational logic does not read, without running
+ * a domain, leaves it as it was.
+ */
+ edges(
+ eventIds: readonly number[],
+ rising: readonly boolean[],
+ dirty = true,
+ ): boolean {
+ const sources: string[] = [];
+ const levers: Lever[] = [];
+ const domains: EdgePlanDomain[] = [];
+ const gated: [EdgePlanDomain, number][] = [];
+ let moved = false;
+ let combRead = false;
+ eventIds.forEach((eventId, index) => {
+ const name = this.name(eventId);
+ const plan = this.plan(eventId);
+ if (!plan) {
+ return;
+ }
+ const to = rising[index] ? 1 : 0;
+ const old = this.knownLevel(plan.signal);
+ if (
+ old === to ||
+ levers.some((l) => l.signal.offset === plan.signal.offset)
+ ) {
+ return;
+ }
+ moved = true;
+ combRead ||= plan.combRead;
+ this.setLevel(plan.signal, to);
+ const lever = { signal: plan.signal, from: old ?? to ^ 1, to };
+ if (plan.edge === "any" || (plan.edge === "posedge") === (to === 1)) {
+ sources.push(name);
+ }
+ if (plan.gated.length > 0) {
+ levers.push(lever);
+ for (const domain of plan.gated) {
+ if (!gated.some(([known]) => known.event === domain.event)) {
+ gated.push([domain, levers.length - 1]);
+ }
+ }
+ }
+ for (const domain of plan.domains) {
+ if (!domains.some((known) => known.event === domain.event)) {
+ domains.push(domain);
+ }
+ }
+ });
+ if (!moved) {
+ return !dirty;
+ }
+ const notSource = (domain: EdgePlanDomain) =>
+ !sources.includes(domain.event);
+ const ran = this.run(
+ sources,
+ domains.filter(notSource),
+ gated.filter(([domain]) => notSource(domain)),
+ levers,
+ { settle: dirty || combRead, persist: true },
+ );
+ return ran || (!dirty && !combRead);
+ }
+
+ private run(
+ sources: readonly string[],
+ domains: readonly EdgePlanDomain[],
+ gated: readonly (readonly [EdgePlanDomain, number])[],
+ levers: readonly Lever[],
+ options: { settle: boolean; persist: boolean },
+ ): boolean {
+ const rounds: RoundEntry[] = domains.map((domain) => ({
+ domain,
+ was: this.level(domain.signal),
+ fired: false,
+ }));
+ if (gated.length === 0) {
+ if (sources.length === 0) {
+ return false;
+ }
+ this.fire(sources, options.settle);
+ this.evalComb();
+ this.rounds(rounds);
+ return true;
+ }
+ const saved = options.persist
+ ? []
+ : levers.map((lever) => this.saveLevel(lever.signal));
+ let moved = false;
+ for (const lever of levers) {
+ if (this.level(lever.signal) !== (lever.from === 1)) {
+ this.setLevel(lever.signal, lever.from);
+ moved = true;
+ }
+ }
+ if (moved || options.settle) {
+ this.evalComb();
+ }
+ const before = gated.map(([domain]) => this.level(domain.signal));
+ for (const lever of levers) {
+ this.setLevel(lever.signal, lever.to);
+ }
+ this.evalComb();
+ const gatedEntries: RoundEntry[] = gated.map(([domain], index) => {
+ const now = this.level(domain.signal);
+ return {
+ domain,
+ was: now,
+ fired: stableEdge(domain.edge, before[index] ?? now, now),
+ };
+ });
+ this.fire(
+ [
+ ...sources,
+ ...gatedEntries
+ .filter((entry) => entry.fired)
+ .map((entry) => entry.domain.event),
+ ],
+ false,
+ );
+ this.evalComb();
+ this.rounds([...rounds, ...gatedEntries]);
+ if (!options.persist) {
+ levers.forEach((lever, index) => {
+ this.restoreLevel(lever.signal, saved[index] ?? [0, 0]);
+ });
+ this.evalComb();
+ }
+ return true;
+ }
+
+ /** Cascade rounds: run every domain whose clock moved to its active edge. */
+ private rounds(entries: RoundEntry[]): void {
+ for (;;) {
+ const ready = entries.filter(
+ (entry) =>
+ !entry.fired &&
+ stableEdge(
+ entry.domain.edge,
+ entry.was,
+ this.level(entry.domain.signal),
+ ),
+ );
+ if (ready.length === 0) {
+ return;
+ }
+ this.fire(
+ ready.map((entry) => entry.domain.event),
+ false,
+ );
+ for (const entry of ready) {
+ entry.fired = true;
+ }
+ this.evalComb();
+ }
+ }
+
+ /** Evaluate `events` against one state, then commit all of them. */
+ private fire(events: readonly string[], settle: boolean): void {
+ if (settle) {
+ this.evalComb();
+ }
+ // An event without a domain of its own runs nothing.
+ const kernels = events
+ .map((name) => this.kernels(name))
+ .filter((kernel): kernel is EdgeKernels => kernel !== undefined);
+ const [only] = kernels;
+ if (kernels.length === 1 && only !== undefined) {
+ only.evalApply();
+ return;
+ }
+ for (const kernel of kernels) {
+ if (kernel.evalOnly) {
+ kernel.evalOnly();
+ } else {
+ kernel.evalApply();
+ }
+ }
+ for (const kernel of kernels) {
+ kernel.apply?.();
+ }
+ }
+
+ private bytes(): Uint8Array {
+ return new Uint8Array(this.memory.buffer);
+ }
+
+ private byte(offset: number): number {
+ return this.bytes()[offset] ?? 0;
+ }
+
+ private level(signal: EdgePlanSignal): boolean {
+ return (this.byte(signal.offset) & 1) !== 0;
+ }
+
+ /** The signal's level, or `null` while it is unknown. */
+ private knownLevel(signal: EdgePlanSignal): number | null {
+ if (this.plans.fourState && (this.byte(signal.offset + 1) & 1) !== 0) {
+ return null;
+ }
+ return this.byte(signal.offset) & 1;
+ }
+
+ private setLevel(signal: EdgePlanSignal, level: number): void {
+ const bytes = this.bytes();
+ bytes[signal.offset] = (this.byte(signal.offset) & ~1) | level;
+ if (this.plans.fourState) {
+ bytes[signal.offset + 1] = this.byte(signal.offset + 1) & ~1;
+ }
+ }
+
+ private saveLevel(signal: EdgePlanSignal): [number, number] {
+ return [
+ this.byte(signal.offset),
+ this.plans.fourState ? this.byte(signal.offset + 1) : 0,
+ ];
+ }
+
+ private restoreLevel(signal: EdgePlanSignal, saved: [number, number]): void {
+ const bytes = this.bytes();
+ bytes[signal.offset] = saved[0];
+ if (this.plans.fourState) {
+ bytes[signal.offset + 1] = saved[1];
+ }
+ }
+
+ private name(eventId: number): string {
+ const name = this.eventNames.get(eventId);
+ if (name === undefined) {
+ throw new RangeError(`Unknown event ID ${eventId}`);
+ }
+ return name;
+ }
+
+ private plan(eventId: number): EdgePlanEvent | undefined {
+ return this.plans.events[this.name(eventId)];
+ }
+}
diff --git a/packages/playground/src/celox-compiler-protocol.ts b/packages/playground/src/celox-compiler-protocol.ts
index 91dc832be7e..419508fdc4d 100644
--- a/packages/playground/src/celox-compiler-protocol.ts
+++ b/packages/playground/src/celox-compiler-protocol.ts
@@ -1,3 +1,5 @@
+import type { EdgePlans } from "@celox-sim/celox/wasm-edges";
+
export type CeloxSourceFile = {
content: string;
path: string;
@@ -10,7 +12,15 @@ export type CompiledSimulator = {
events: Record;
totalSize: number;
combModule: WebAssembly.Module;
+ /** Per event, its own domain; absent for an event without one. */
eventModules: Record;
+ /** Per event, the phases of its split kernels, where it has them. */
+ phaseModules: Record<
+ string,
+ { evalOnly: WebAssembly.Module; apply: WebAssembly.Module }
+ >;
+ /** Derived and gated domains of each event's ticks and edges. */
+ edgePlans: EdgePlans;
};
export type CeloxCompilerRequest =
diff --git a/packages/playground/src/celox-compiler-worker.ts b/packages/playground/src/celox-compiler-worker.ts
index 5a440f03230..061b0fe5782 100644
--- a/packages/playground/src/celox-compiler-worker.ts
+++ b/packages/playground/src/celox-compiler-worker.ts
@@ -1,8 +1,8 @@
import type {
CeloxCompilerRequest,
CeloxCompilerResponse,
- CompiledSimulator,
} from "./celox-compiler-protocol.js";
+import { compiledFromHandle } from "./compile-simulator.js";
const workerScope = globalThis as unknown as {
addEventListener(
@@ -30,33 +30,7 @@ try {
{ fourState: request.fourState },
);
try {
- const layout = JSON.parse(handle.layoutJson);
- const events = JSON.parse(handle.eventsJson) as Record;
- const fourStateInitRegions = JSON.parse(
- handle.fourStateInitRegionsJson,
- ) as Array<[number, number]>;
- const combModule = new WebAssembly.Module(
- new Uint8Array(handle.combWasmBytes()),
- );
- const eventModules: Record = {};
- for (const name of Object.keys(events)) {
- try {
- eventModules[name] = new WebAssembly.Module(
- new Uint8Array(handle.eventWasmBytes(name)),
- );
- } catch {
- // An event without generated code is valid and has nothing to run.
- }
- }
- const value: CompiledSimulator = {
- fourState: request.fourState,
- fourStateInitRegions,
- layout,
- events,
- totalSize: handle.totalSize,
- combModule,
- eventModules,
- };
+ const value = compiledFromHandle(handle, request.fourState);
workerScope.postMessage({ type: "result", id: request.id, value });
} finally {
handle.dispose();
diff --git a/packages/playground/src/celox-wasm-loader.d.ts b/packages/playground/src/celox-wasm-loader.d.ts
index 12b272a745a..29d2726e5d8 100644
--- a/packages/playground/src/celox-wasm-loader.d.ts
+++ b/packages/playground/src/celox-wasm-loader.d.ts
@@ -15,5 +15,7 @@ export class NativeSimulatorHandle {
initialMemoryBytes(): Uint8Array;
combWasmBytes(): Uint8Array;
eventWasmBytes(name: string): Uint8Array;
+ edgePlansJson(): string;
+ eventPhaseWasmBytes(name: string, phase: "evalOnly" | "apply"): Uint8Array;
dispose(): void;
}
diff --git a/packages/playground/src/compile-simulator.ts b/packages/playground/src/compile-simulator.ts
new file mode 100644
index 00000000000..ff43d1282bb
--- /dev/null
+++ b/packages/playground/src/compile-simulator.ts
@@ -0,0 +1,61 @@
+import type { EdgePlans } from "@celox-sim/celox/wasm-edges";
+import type { CompiledSimulator } from "./celox-compiler-protocol.js";
+
+/** The parts of the wasm32 Celox handle a compiled simulator is made from. */
+export interface CompilerHandle {
+ readonly layoutJson: string;
+ readonly eventsJson: string;
+ readonly fourStateInitRegionsJson: string;
+ readonly totalSize: number;
+ combWasmBytes(): Uint8Array;
+ eventWasmBytes(name: string): Uint8Array;
+ edgePlansJson(): string;
+ eventPhaseWasmBytes(name: string, phase: "evalOnly" | "apply"): Uint8Array;
+}
+
+function compileModule(
+ bytes: () => Uint8Array,
+): WebAssembly.Module | undefined {
+ try {
+ return new WebAssembly.Module(new Uint8Array(bytes()));
+ } catch {
+ // An event without a domain of its own (a clock that only drives a
+ // gated clock) has no module.
+ return undefined;
+ }
+}
+
+/** Compile every module of `handle` for the playground runtime. */
+export function compiledFromHandle(
+ handle: CompilerHandle,
+ fourState: boolean,
+): CompiledSimulator {
+ const events = JSON.parse(handle.eventsJson) as Record;
+ const eventModules: CompiledSimulator["eventModules"] = {};
+ const phaseModules: CompiledSimulator["phaseModules"] = {};
+ for (const name of Object.keys(events)) {
+ const own = compileModule(() => handle.eventWasmBytes(name));
+ if (!own) continue;
+ eventModules[name] = own;
+ const evalOnly = compileModule(() =>
+ handle.eventPhaseWasmBytes(name, "evalOnly"),
+ );
+ const apply = compileModule(() =>
+ handle.eventPhaseWasmBytes(name, "apply"),
+ );
+ if (evalOnly && apply) phaseModules[name] = { evalOnly, apply };
+ }
+ return {
+ fourState,
+ fourStateInitRegions: JSON.parse(handle.fourStateInitRegionsJson) as Array<
+ [number, number]
+ >,
+ layout: JSON.parse(handle.layoutJson),
+ events,
+ totalSize: handle.totalSize,
+ combModule: new WebAssembly.Module(new Uint8Array(handle.combWasmBytes())),
+ eventModules,
+ phaseModules,
+ edgePlans: JSON.parse(handle.edgePlansJson()) as EdgePlans,
+ };
+}
diff --git a/packages/playground/src/main.ts b/packages/playground/src/main.ts
index befa5ce205b..af064eee6c0 100644
--- a/packages/playground/src/main.ts
+++ b/packages/playground/src/main.ts
@@ -1,25 +1,14 @@
import { chai, JestAsymmetricMatchers, JestChaiExpect } from "@vitest/expect";
import * as monaco from "monaco-editor";
-import celoxDutDts from "../../celox/dist/dut.d.ts?raw";
-import celoxIndexDts from "../../celox/dist/index.d.ts?raw";
-import celoxNapiBridgeDts from "../../celox/dist/napi-bridge.d.ts?raw";
-import celoxNapiHelpersDts from "../../celox/dist/napi-helpers.d.ts?raw";
-import celoxSimulationDts from "../../celox/dist/simulation.d.ts?raw";
-import celoxSimulatorDts from "../../celox/dist/simulator.d.ts?raw";
-// Import real .d.ts files from @celox-sim/celox for Monaco type injection
-import celoxTypesDts from "../../celox/dist/types.d.ts?raw";
-import celoxWasmBridgeDts from "../../celox/dist/wasm-bridge.d.ts?raw";
import { CeloxCompilerClient } from "./celox-compiler-client.js";
import { buildMonacoTestbenchCompilerOptions } from "./monaco-testbench-options.js";
+import { celoxDtsLibs } from "./playground-dts.js";
+import { FourState, X, Z } from "./playground-runtime-helpers.js";
import {
- FourState,
- initializeFourStateMemory,
- type PlaygroundSignalValue,
- runPlaygroundTicks,
- writeSignalValue,
- X,
- Z,
-} from "./playground-runtime-helpers.js";
+ createPlaygroundSimulation,
+ createPlaygroundSimulator,
+ type PlaygroundDumpSink,
+} from "./playground-simulator.js";
import { transpileTestbench } from "./testbench-transpile.js";
import {
buildVirtualModuleDts,
@@ -1099,41 +1088,14 @@ declare module "vitest" {
// ── @celox-sim/celox type registration (from real .d.ts) ──
-// Rewrite relative imports in .d.ts to match Monaco's virtual FS paths
-function fixDtsImports(content: string): string {
- return content.replace(
- /from\s+["']\.\/(\w+)\.js["']/g,
- 'from "@celox-sim/celox/$1"',
- );
-}
-
-// Register all @celox-sim/celox .d.ts files so Monaco resolves imports
-const celoxDtsFiles: Record = {
- types: celoxTypesDts,
- simulator: celoxSimulatorDts,
- simulation: celoxSimulationDts,
- index: celoxIndexDts,
- dut: celoxDutDts,
- "napi-helpers": celoxNapiHelpersDts,
- "wasm-bridge": celoxWasmBridgeDts,
- "napi-bridge": celoxNapiBridgeDts,
-};
-monacoTypeScript.typescriptDefaults.addExtraLib(
- fixDtsImports(celoxIndexDts),
- "file:///node_modules/@celox-sim/celox/index.d.ts",
-);
-for (const [name, content] of Object.entries(celoxDtsFiles)) {
- const fixed = fixDtsImports(content);
- // Register as both the sub-module path and the node_modules-style path
- monacoTypeScript.typescriptDefaults.addExtraLib(
- fixed,
- `file:///node_modules/@celox-sim/celox/dist/${name}.d.ts`,
- );
- // Also register as a bare module specifier for "from '@celox-sim/celox/xxx'" resolution
- monacoTypeScript.typescriptDefaults.addExtraLib(
- fixed,
- `file:///node_modules/@celox-sim/celox/${name}.d.ts`,
- );
+// Every declaration file of the package, so the whole public API resolves.
+const celoxDtsSources = import.meta.glob("../../celox/dist/*.d.ts", {
+ query: "?raw",
+ import: "default",
+ eager: true,
+});
+for (const lib of celoxDtsLibs(celoxDtsSources)) {
+ monacoTypeScript.typescriptDefaults.addExtraLib(lib.content, lib.filePath);
}
// ── DUT type injection (.veryl module declarations) ─────
@@ -1437,156 +1399,13 @@ async function run() {
type PlaygroundSimulatorOptions = { fourState?: boolean };
- // Build simulation factory (creates fresh instance per call)
- function createSim(options?: PlaygroundSimulatorOptions) {
- const fourStateEnabled = options?.fourState === true;
- const {
- layout,
- events,
- totalSize,
- combModule,
- eventModules,
- fourStateInitRegions,
- } = fourStateEnabled ? fourStateCompiled : twoStateCompiled;
- const pages = Math.max(1, Math.ceil(totalSize / 65536));
- const memory = new WebAssembly.Memory({ initial: pages });
- initializeFourStateMemory(memory, fourStateInitRegions);
- const combInst = new WebAssembly.Instance(combModule, {
- env: { memory },
- });
-
- // Build event instances and id→name mapping (mirrors real Simulator)
- const eventNames = Object.keys(events);
- const eventInsts: Record = {};
- for (const name of eventNames) {
- const id: number = events[name];
- const eventModule = eventModules[name];
- if (eventModule) {
- eventInsts[id] = new WebAssembly.Instance(eventModule, {
- env: { memory },
- });
- }
- }
- const defaultEventId = eventNames.length > 0 ? events[eventNames[0]] : -1;
- const knownEventIds = new Set(Object.values(events));
-
- const view = new DataView(memory.buffer);
- let dirty = false;
-
- const dut = new Proxy({} as Record, {
- get(_, prop: string) {
- const sig = layout[prop];
- if (!sig) return undefined;
- // Lazy evalComb on output reads (matches real Simulator DUT behavior)
- if (dirty && sig.direction !== "input") {
- (combInst.exports.run as Function)();
- dirty = false;
- }
- let v = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- v = (v << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n;
- return v;
- },
- set(_, prop: string, value: PlaygroundSignalValue) {
- const sig = layout[prop];
- if (!sig) throw new Error(`Signal '${prop}' not found`);
- writeSignalValue(view, sig, value, fourStateEnabled);
- dirty = true;
- return true;
- },
- });
-
- function evalComb() {
- (combInst.exports.run as Function)();
- dirty = false;
- }
-
- function flushDirty() {
- if (dirty) evalComb();
- }
-
- function tickOne(eventId: number) {
- const inst = eventInsts[eventId];
- if (inst) (inst.exports.run as Function)();
- (combInst.exports.run as Function)();
- dirty = false;
- }
-
- const tickRuntime = {
- defaultEventId,
- knownEventIds,
- flushDirty,
- tickOne,
- };
-
- return {
- dut,
- warnings: [] as readonly string[],
- tick(
- eventOrCount?: { name: string; id: number } | number,
- count?: number,
- ) {
- runPlaygroundTicks(tickRuntime, eventOrCount, count);
- },
- event(name: string): { name: string; id: number } {
- const id = events[name];
- if (id === undefined) {
- throw new Error(
- `Unknown event '${name}'. Available: ${eventNames.join(", ")}`,
- );
- }
- return { name, id };
- },
- fourState(portName: string): {
- __fourState: true;
- value: bigint;
- mask: bigint;
- } {
- const sig = layout[portName];
- if (!sig) {
- throw new Error(
- `Unknown port '${portName}'. Available: ${Object.keys(layout).join(", ")}`,
- );
- }
- if (dirty && sig.direction !== "input") evalComb();
- let value = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- value = (value << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n;
- // 4-state mask lives immediately after value bytes
- let mask = 0n;
- if (sig.is_4state) {
- for (let i = sig.byte_size - 1; i >= 0; i--)
- mask =
- (mask << 8n) |
- BigInt(view.getUint8(sig.offset + sig.byte_size + i));
- if (sig.width < 64) mask &= (1n << BigInt(sig.width)) - 1n;
- }
- return { __fourState: true, value, mask };
- },
- dump(timestamp: number) {
- if (vcdSignals.length === 0) {
- for (const [name, sig] of Object.entries(layout)) {
- vcdSignals.push({ name, width: sig.width });
- }
- }
- if (dirty) {
- evalComb();
- }
- const values: bigint[] = [];
- for (const sig of Object.values(layout)) {
- let v = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- v = (v << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n;
- values.push(v);
- }
- vcdSnapshots.push({ timestamp, values });
- },
- dispose() {},
- };
- }
+ // Every dump() lands in the waveform viewer's current trace.
+ const recordDump: PlaygroundDumpSink = (timestamp, signals, values) => {
+ if (vcdSignals.length === 0) vcdSignals.push(...signals);
+ vcdSnapshots.push({ timestamp, values });
+ };
+ const compiledFor = (options?: PlaygroundSimulatorOptions) =>
+ options?.fourState === true ? fourStateCompiled : twoStateCompiled;
// Build module definitions from genTsFromSource result for .veryl imports
const moduleNames = (genTsResult?.modules || [])
@@ -1595,383 +1414,13 @@ async function run() {
const Simulator = {
create(_module: any, options?: PlaygroundSimulatorOptions) {
- return createSim(options);
+ return createPlaygroundSimulator(compiledFor(options), recordDump);
},
};
- // Time-based Simulation: event queue with signal toggling on top of WASM bridge
- // Mirrors the native Simulation's step() logic:
- // 1. Pop all events at current time
- // 2. Write signal values to memory
- // 3. Detect edges (posedge/negedge) and fire triggered FF handlers
- // 4. Evaluate combinational logic
- // 5. Reschedule recurring clocks with toggled value
- function createSimulation(options?: PlaygroundSimulatorOptions) {
- const fourStateEnabled = options?.fourState === true;
- const {
- layout,
- events,
- totalSize,
- combModule,
- eventModules,
- fourStateInitRegions,
- } = fourStateEnabled ? fourStateCompiled : twoStateCompiled;
- const pages = Math.max(1, Math.ceil(totalSize / 65536));
- const memory = new WebAssembly.Memory({ initial: pages });
- initializeFourStateMemory(memory, fourStateInitRegions);
- const combInst = new WebAssembly.Instance(combModule, {
- env: { memory },
- });
-
- const eventNames = Object.keys(events);
- const eventInsts: Record = {};
- for (const name of eventNames) {
- const id: number = events[name];
- const eventModule = eventModules[name];
- if (eventModule) {
- eventInsts[id] = new WebAssembly.Instance(eventModule, {
- env: { memory },
- });
- }
- }
-
- const view = new DataView(memory.buffer);
-
- // Determine edge type for each event from layout type_kind
- const edgeType: Record = {};
- for (const name of eventNames) {
- const id: number = events[name];
- const sig = layout[name];
- if (!sig) continue;
- const tk: string = sig.type_kind ?? "logic";
- if (tk === "reset_async_low" || tk === "reset_sync_low") {
- edgeType[id] = "negedge";
- } else {
- edgeType[id] = "posedge"; // clock, reset_async_high, etc.
- }
- }
-
- // Event queue entry: carries the signal name, next value, and optional clock reschedule info
- type QueueEntry = {
- time: number;
- eventId: number;
- signalName: string;
- nextVal: number;
- clockHalfPeriod?: number; // if set, reschedule with toggled value
- };
- const queue: QueueEntry[] = [];
- const clocks = new Map();
- let currentTime = 0;
- // Track last signal values for edge detection
- const lastValues: Record = {};
-
- function enqueue(entry: QueueEntry) {
- let lo = 0,
- hi = queue.length;
- while (lo < hi) {
- const mid = (lo + hi) >>> 1;
- if (queue[mid].time <= entry.time) lo = mid + 1;
- else hi = mid;
- }
- queue.splice(lo, 0, entry);
- }
-
- function writeSignal(name: string, val: number) {
- const sig = layout[name];
- if (sig) writeSignalValue(view, sig, val, fourStateEnabled);
- }
-
- function resolveEvent(name: string): number {
- const id = events[name];
- if (id === undefined) {
- throw new Error(
- `Unknown event '${name}'. Available: ${eventNames.join(", ")}`,
- );
- }
- return id;
- }
-
- // Process one time step: pop all events at next time, write values, detect edges, fire FFs
- function processStep(): number | null {
- if (queue.length === 0) return null;
- const t = queue[0].time;
- // Collect all events at this time
- const batch: QueueEntry[] = [];
- while (queue.length > 0 && queue[0].time === t) {
- batch.push(queue.shift()!);
- }
- currentTime = t;
-
- // Phase 1: Write signal values to memory
- for (const ev of batch) {
- writeSignal(ev.signalName, ev.nextVal);
- }
-
- // Phase 2: Edge detection + fire triggered FFs
- for (const ev of batch) {
- const prevVal = lastValues[ev.eventId] ?? 0;
- const curVal = ev.nextVal;
- const edge = edgeType[ev.eventId] ?? "posedge";
- const triggered =
- edge === "posedge"
- ? prevVal === 0 && curVal !== 0
- : prevVal !== 0 && curVal === 0;
- if (triggered) {
- const inst = eventInsts[ev.eventId];
- if (inst) (inst.exports.run as Function)();
- }
- lastValues[ev.eventId] = curVal;
- }
-
- // Phase 3: Evaluate combinational logic
- (combInst.exports.run as Function)();
-
- // Phase 4: Reschedule clocks with toggled value
- for (const ev of batch) {
- if (ev.clockHalfPeriod != null) {
- enqueue({
- time: currentTime + ev.clockHalfPeriod,
- eventId: ev.eventId,
- signalName: ev.signalName,
- nextVal: 1 - ev.nextVal,
- clockHalfPeriod: ev.clockHalfPeriod,
- });
- }
- }
-
- return currentTime;
- }
-
- // DUT proxy with lazy evalComb on output reads
- let simDirty = false;
- const dut = new Proxy({} as Record, {
- get(_, prop: string) {
- const sig = layout[prop];
- if (!sig) return undefined;
- if (simDirty && sig.direction !== "input") {
- (combInst.exports.run as Function)();
- simDirty = false;
- }
- let v = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- v = (v << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n;
- return v;
- },
- set(_, prop: string, value: PlaygroundSignalValue) {
- const sig = layout[prop];
- if (!sig) throw new Error(`Signal '${prop}' not found`);
- writeSignalValue(view, sig, value, fourStateEnabled);
- simDirty = true;
- return true;
- },
- });
-
- const sim = {
- dut,
- warnings: [] as readonly string[],
-
- addClock(
- name: string,
- opts: { period: number; initialDelay?: number },
- ) {
- const eventId = resolveEvent(name);
- clocks.set(name, { period: opts.period, eventId });
- const delay = opts.initialDelay ?? 0;
- const halfPeriod = opts.period / 2;
- // Schedule first edge (0→1) at delay, then toggles every half-period
- enqueue({
- time: currentTime + delay,
- eventId,
- signalName: name,
- nextVal: 1,
- clockHalfPeriod: halfPeriod,
- });
- },
-
- schedule(name: string, opts: { time: number; value: number }) {
- const eventId = resolveEvent(name);
- enqueue({
- time: opts.time,
- eventId,
- signalName: name,
- nextVal: opts.value,
- });
- },
-
- step: processStep,
-
- time(): number {
- return currentTime;
- },
-
- nextEventTime(): number | null {
- return queue.length > 0 ? queue[0].time : null;
- },
-
- runUntil(endTime: number, opts?: { maxSteps?: number }) {
- const max = opts?.maxSteps;
- let steps = 0;
- while (queue.length > 0 && queue[0].time <= endTime) {
- processStep();
- steps++;
- if (max != null && steps >= max) {
- throw new Error(
- `runUntil: exceeded ${max} steps at time ${currentTime} (target ${endTime})`,
- );
- }
- }
- currentTime = endTime;
- },
-
- waitUntil(
- condition: () => boolean,
- opts?: { maxSteps?: number },
- ): number {
- const max = opts?.maxSteps ?? 100_000;
- let steps = 0;
- while (!condition()) {
- if (queue.length === 0) break;
- processStep();
- steps++;
- if (steps >= max) {
- throw new Error(
- `waitUntil: condition not met after ${max} steps at time ${currentTime}`,
- );
- }
- }
- return currentTime;
- },
-
- waitForCycles(
- clock: string,
- count: number,
- opts?: { maxSteps?: number },
- ): number {
- const clkInfo = clocks.get(clock);
- if (!clkInfo)
- throw new Error(
- `No clock registered for '${clock}'. Call addClock() first.`,
- );
- const sig = layout[clock];
- if (!sig) throw new Error(`No layout entry for clock '${clock}'.`);
- const readClk = () => view.getUint8(sig.offset);
- let prev = readClk();
- let remaining = count;
- return sim.waitUntil(() => {
- const curr = readClk();
- if (prev === 0 && curr !== 0) remaining--;
- prev = curr;
- return remaining <= 0;
- }, opts);
- },
-
- reset(
- signal: string,
- opts?: { activeCycles?: number; duration?: number },
- ) {
- const sig = layout[signal];
- if (!sig)
- throw new Error(
- `Unknown port '${signal}'. Available: ${Object.keys(layout).join(", ")}`,
- );
- const typeKind: string = sig.type_kind ?? "";
- if (!typeKind.startsWith("reset")) {
- throw new Error(
- `Port '${signal}' is not a reset signal (type_kind: '${typeKind}').`,
- );
- }
- const isActiveLow =
- typeKind === "reset_async_low" || typeKind === "reset_sync_low";
- const activeValue = isActiveLow ? 0n : 1n;
- const inactiveValue = isActiveLow ? 1n : 0n;
-
- dut[signal] = activeValue;
-
- if (opts?.duration != null) {
- sim.runUntil(currentTime + opts.duration);
- } else {
- const cycles = opts?.activeCycles ?? 2;
- const firstClock = clocks.keys().next().value;
- if (firstClock) {
- sim.waitForCycles(firstClock, cycles);
- } else {
- // No clock registered — fire the reset event directly
- const eventId = events[signal];
- if (eventId !== undefined) {
- writeSignal(signal, Number(activeValue));
- const inst = eventInsts[eventId];
- if (inst) (inst.exports.run as Function)();
- (combInst.exports.run as Function)();
- }
- }
- }
-
- dut[signal] = inactiveValue;
- },
-
- event(name: string): { name: string; id: number } {
- return { name, id: resolveEvent(name) };
- },
-
- fourState(portName: string): {
- __fourState: true;
- value: bigint;
- mask: bigint;
- } {
- const sig = layout[portName];
- if (!sig)
- throw new Error(
- `Unknown port '${portName}'. Available: ${Object.keys(layout).join(", ")}`,
- );
- if (simDirty && sig.direction !== "input") {
- (combInst.exports.run as Function)();
- simDirty = false;
- }
- let value = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- value = (value << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n;
- let mask = 0n;
- if (sig.is_4state) {
- for (let i = sig.byte_size - 1; i >= 0; i--)
- mask =
- (mask << 8n) |
- BigInt(view.getUint8(sig.offset + sig.byte_size + i));
- if (sig.width < 64) mask &= (1n << BigInt(sig.width)) - 1n;
- }
- return { __fourState: true, value, mask };
- },
-
- dump(timestamp: number) {
- if (vcdSignals.length === 0) {
- for (const [name, sig] of Object.entries(layout)) {
- vcdSignals.push({ name, width: sig.width });
- }
- }
- if (simDirty) {
- (combInst.exports.run as Function)();
- simDirty = false;
- }
- const values: bigint[] = [];
- for (const sig of Object.values(layout)) {
- let v = 0n;
- for (let i = sig.byte_size - 1; i >= 0; i--)
- v = (v << 8n) | BigInt(view.getUint8(sig.offset + i));
- if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n;
- values.push(v);
- }
- vcdSnapshots.push({ timestamp, values });
- },
-
- dispose() {},
- };
- return sim;
- }
-
const Simulation = {
create(_module: any, options?: PlaygroundSimulatorOptions) {
- return createSimulation(options);
+ return createPlaygroundSimulation(compiledFor(options), recordDump);
},
};
diff --git a/packages/playground/src/playground-dts.ts b/packages/playground/src/playground-dts.ts
index ca3981ae6e6..d64a2880b91 100644
--- a/packages/playground/src/playground-dts.ts
+++ b/packages/playground/src/playground-dts.ts
@@ -1,3 +1,37 @@
+/** A declaration file for Monaco's TypeScript service. */
+export interface ExtraLib {
+ readonly content: string;
+ readonly filePath: string;
+}
+
+const CELOX_ROOT = "file:///node_modules/@celox-sim/celox";
+
+/** Rewrite the relative imports of a `@celox-sim/celox` declaration file. */
+function fixCeloxDtsImports(content: string): string {
+ return content.replace(
+ /from\s+["']\.\/([\w-]+)\.js["']/g,
+ 'from "@celox-sim/celox/$1"',
+ );
+}
+
+/**
+ * Monaco libraries for every declaration file of `@celox-sim/celox`'s
+ * `dist`, keyed by path (as `import.meta.glob` returns them): each one under
+ * `dist/` and under its bare subpath, and `index.d.ts` as the package root,
+ * so that testbenches see the whole public API, explicit edges included.
+ */
+export function celoxDtsLibs(files: Record): ExtraLib[] {
+ const libs: ExtraLib[] = [];
+ for (const [path, content] of Object.entries(files)) {
+ const name = /([\w-]+)\.d\.ts$/.exec(path)?.[1];
+ if (!name) continue;
+ const fixed = fixCeloxDtsImports(content);
+ libs.push({ content: fixed, filePath: `${CELOX_ROOT}/dist/${name}.d.ts` });
+ libs.push({ content: fixed, filePath: `${CELOX_ROOT}/${name}.d.ts` });
+ }
+ return libs;
+}
+
export type VirtualPortDirection = "input" | "output" | "inout";
export type VirtualPortKind = "logic" | "bit" | "clock" | "reset";
diff --git a/packages/playground/src/playground-simulator.ts b/packages/playground/src/playground-simulator.ts
new file mode 100644
index 00000000000..949185bd18f
--- /dev/null
+++ b/packages/playground/src/playground-simulator.ts
@@ -0,0 +1,487 @@
+/**
+ * The playground's simulators: the compiled WebAssembly modules of a design,
+ * driven as `@celox-sim/celox` drives them in the browser.
+ *
+ * Ticks, explicit edges and timed steps run through the edge runner of
+ * `@celox-sim/celox`, from the build-time edge plans, so derived and gated
+ * clocks fire exactly as in the native simulator.
+ *
+ * @module
+ */
+
+import {
+ cachedEdgeKernels,
+ type KernelRun,
+ WasmEdgeRunner,
+} from "@celox-sim/celox/wasm-edges";
+import type { CompiledSimulator } from "./celox-compiler-protocol.js";
+import {
+ initializeFourStateMemory,
+ type PlaygroundEventHandle,
+ type PlaygroundSignalValue,
+ runPlaygroundTicks,
+ writeSignalValue,
+} from "./playground-runtime-helpers.js";
+
+/** A clock edge, as `Simulator.edges()` of `@celox-sim/celox` names it. */
+export type PlaygroundClockEdge = "posedge" | "negedge";
+
+/** An event, by handle or ID. */
+export type PlaygroundEvent = PlaygroundEventHandle | number;
+
+/** Receives `dump()` snapshots for the waveform viewer. */
+export type PlaygroundDumpSink = (
+ timestamp: number,
+ signals: { name: string; width: number }[],
+ values: bigint[],
+) => void;
+
+export type PlaygroundFourStateValue = {
+ __fourState: true;
+ value: bigint;
+ mask: bigint;
+};
+
+function runExport(instance: WebAssembly.Instance): KernelRun {
+ return () => (instance.exports.run as CallableFunction)();
+}
+
+/** One instantiated design: its memory, kernels and edge runner. */
+class PlaygroundInstance {
+ readonly layout: Record;
+ readonly events: Record;
+ readonly eventNames: string[];
+ readonly knownEventIds: ReadonlySet;
+ readonly view: DataView;
+ readonly runner: WasmEdgeRunner;
+ readonly fourState: boolean;
+ /** Combinational logic has pending input changes. */
+ dirty = false;
+ private readonly comb: KernelRun;
+
+ constructor(compiled: CompiledSimulator) {
+ this.layout = compiled.layout;
+ this.events = compiled.events;
+ this.eventNames = Object.keys(compiled.events);
+ this.knownEventIds = new Set(Object.values(compiled.events));
+ this.fourState = compiled.fourState;
+ const pages = Math.max(1, Math.ceil(compiled.totalSize / 65536));
+ const memory = new WebAssembly.Memory({ initial: pages });
+ initializeFourStateMemory(memory, compiled.fourStateInitRegions);
+ this.view = new DataView(memory.buffer);
+ const instantiate = (module: WebAssembly.Module) =>
+ runExport(new WebAssembly.Instance(module, { env: { memory } }));
+ this.comb = instantiate(compiled.combModule);
+ const evalApply = new Map();
+ for (const [name, module] of Object.entries(compiled.eventModules)) {
+ evalApply.set(name, instantiate(module));
+ }
+ const kernels = cachedEdgeKernels(
+ (name) => evalApply.get(name),
+ (name, kind) => {
+ const phases = compiled.phaseModules[name];
+ return phases ? instantiate(phases[kind]) : undefined;
+ },
+ );
+ this.runner = new WasmEdgeRunner(
+ memory,
+ compiled.edgePlans,
+ compiled.events,
+ kernels,
+ this.comb,
+ );
+ }
+
+ evalComb(): void {
+ this.comb();
+ this.dirty = false;
+ }
+
+ flushDirty(): void {
+ if (this.dirty) this.evalComb();
+ }
+
+ /** The event's active edge without moving its signal, as `tick`. */
+ tickOne(eventId: number): void {
+ this.runner.tick(eventId);
+ this.dirty = false;
+ }
+
+ /** Coincident edges; see `Simulator.edges()` of `@celox-sim/celox`. */
+ edges(eventIds: number[], rising: boolean[]): void {
+ this.dirty = !this.runner.edges(eventIds, rising, this.dirty);
+ }
+
+ activeIsRising(eventId: number): boolean {
+ return this.runner.activeEdgeIsRising(eventId);
+ }
+
+ resolveEvent(name: string): number {
+ const id = this.events[name];
+ if (id === undefined) {
+ throw new Error(
+ `Unknown event '${name}'. Available: ${this.eventNames.join(", ")}`,
+ );
+ }
+ return id;
+ }
+
+ signal(name: string): any {
+ const sig = this.layout[name];
+ if (!sig) {
+ throw new Error(
+ `Unknown port '${name}'. Available: ${Object.keys(this.layout).join(", ")}`,
+ );
+ }
+ return sig;
+ }
+
+ read(sig: any, plane = 0): bigint {
+ let value = 0n;
+ const base = sig.offset + plane * sig.byte_size;
+ for (let i = sig.byte_size - 1; i >= 0; i--)
+ value = (value << 8n) | BigInt(this.view.getUint8(base + i));
+ if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n;
+ return value;
+ }
+
+ write(name: string, value: PlaygroundSignalValue): void {
+ const sig = this.layout[name];
+ if (!sig) throw new Error(`Signal '${name}' not found`);
+ writeSignalValue(this.view, sig, value, this.fourState);
+ this.dirty = true;
+ }
+
+ /** A DUT whose output reads settle combinational logic first. */
+ dut(): Record {
+ return new Proxy({} as Record, {
+ get: (_, prop: string) => {
+ const sig = this.layout[prop];
+ if (!sig) return undefined;
+ if (sig.direction !== "input") this.flushDirty();
+ return this.read(sig);
+ },
+ set: (_, prop: string, value: PlaygroundSignalValue) => {
+ this.write(prop, value);
+ return true;
+ },
+ });
+ }
+
+ fourStateOf(portName: string): PlaygroundFourStateValue {
+ const sig = this.signal(portName);
+ if (sig.direction !== "input") this.flushDirty();
+ const value = this.read(sig);
+ const mask = sig.is_4state ? this.read(sig, 1) : 0n;
+ return { __fourState: true, value, mask };
+ }
+
+ dump(timestamp: number, sink: PlaygroundDumpSink | undefined): void {
+ this.flushDirty();
+ const entries = Object.entries(this.layout);
+ sink?.(
+ timestamp,
+ entries.map(([name, sig]) => ({ name, width: sig.width })),
+ entries.map(([, sig]) => this.read(sig)),
+ );
+ }
+}
+
+/**
+ * A simulator with untimed ticks and explicit edges, as `Simulator` of
+ * `@celox-sim/celox`.
+ */
+export function createPlaygroundSimulator(
+ compiled: CompiledSimulator,
+ sink?: PlaygroundDumpSink,
+) {
+ const design = new PlaygroundInstance(compiled);
+ const defaultEventId =
+ design.eventNames.length > 0
+ ? (design.events[design.eventNames[0] as string] as number)
+ : -1;
+ const tickRuntime = {
+ defaultEventId,
+ knownEventIds: design.knownEventIds,
+ flushDirty: () => design.flushDirty(),
+ tickOne: (eventId: number) => design.tickOne(eventId),
+ };
+
+ const resolveEventId = (event: PlaygroundEvent | undefined): number => {
+ if (event === undefined) {
+ if (design.knownEventIds.size === 0) {
+ throw new Error("Simulator has no events");
+ }
+ return defaultEventId;
+ }
+ const id = typeof event === "number" ? event : event.id;
+ if (!design.knownEventIds.has(id)) {
+ throw new RangeError(`Unknown event ID ${id}`);
+ }
+ return id;
+ };
+
+ const sim = {
+ dut: design.dut(),
+ warnings: [] as readonly string[],
+ tick(eventOrCount?: PlaygroundEvent, count?: number) {
+ runPlaygroundTicks(tickRuntime, eventOrCount, count);
+ },
+ /**
+ * Move event signals at one instant, as coincident edges: every domain
+ * sensitive to one of them evaluates against the state before the
+ * edges, then all of them commit.
+ */
+ edges(
+ moves: ReadonlyArray,
+ ) {
+ const ids: number[] = [];
+ const rising: boolean[] = [];
+ for (const [event, edge] of moves) {
+ if (edge !== "posedge" && edge !== "negedge") {
+ throw new RangeError(`Unknown clock edge '${String(edge)}'`);
+ }
+ ids.push(resolveEventId(event));
+ rising.push(edge === "posedge");
+ }
+ design.edges(ids, rising);
+ },
+ /** Move a clock's signal to 1 and run every domain sensitive to it. */
+ posedge(event?: PlaygroundEvent) {
+ sim.edges([[resolveEventId(event), "posedge"]]);
+ },
+ /** Move a clock's signal to 0; see `posedge()`. */
+ negedge(event?: PlaygroundEvent) {
+ sim.edges([[resolveEventId(event), "negedge"]]);
+ },
+ /** The event's active edge. */
+ activeEdge(event?: PlaygroundEvent) {
+ const id = resolveEventId(event);
+ sim.edges([[id, design.activeIsRising(id) ? "posedge" : "negedge"]]);
+ },
+ /** The edge opposite to the event's active edge. */
+ inactiveEdge(event?: PlaygroundEvent) {
+ const id = resolveEventId(event);
+ sim.edges([[id, design.activeIsRising(id) ? "negedge" : "posedge"]]);
+ },
+ /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */
+ cycle(event?: PlaygroundEvent) {
+ sim.activeEdge(event);
+ sim.inactiveEdge(event);
+ },
+ event(name: string): PlaygroundEventHandle {
+ return { name, id: design.resolveEvent(name) };
+ },
+ fourState(portName: string): PlaygroundFourStateValue {
+ return design.fourStateOf(portName);
+ },
+ dump(timestamp: number) {
+ design.dump(timestamp, sink);
+ },
+ dispose() {},
+ };
+ return sim;
+}
+
+/**
+ * A timed simulation, as `Simulation` of `@celox-sim/celox`: scheduled
+ * signal changes at one time are coincident edges.
+ */
+export function createPlaygroundSimulation(
+ compiled: CompiledSimulator,
+ sink?: PlaygroundDumpSink,
+) {
+ const design = new PlaygroundInstance(compiled);
+ const { layout } = design;
+
+ type QueueEntry = {
+ time: number;
+ eventId: number;
+ nextVal: number;
+ clockHalfPeriod?: number;
+ };
+ const queue: QueueEntry[] = [];
+ const clocks = new Map();
+ let currentTime = 0;
+
+ function enqueue(entry: QueueEntry) {
+ let lo = 0;
+ let hi = queue.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >>> 1;
+ if ((queue[mid] as QueueEntry).time <= entry.time) lo = mid + 1;
+ else hi = mid;
+ }
+ queue.splice(lo, 0, entry);
+ }
+
+ /** Pop every change at the next time and run them as coincident edges. */
+ function processStep(): number | null {
+ const first = queue[0];
+ if (!first) return null;
+ const t = first.time;
+ const batch: QueueEntry[] = [];
+ while (queue.length > 0 && (queue[0] as QueueEntry).time === t) {
+ batch.push(queue.shift() as QueueEntry);
+ }
+ currentTime = t;
+ design.edges(
+ batch.map((entry) => entry.eventId),
+ batch.map((entry) => entry.nextVal !== 0),
+ );
+ design.flushDirty();
+ for (const entry of batch) {
+ if (entry.clockHalfPeriod != null) {
+ enqueue({
+ time: currentTime + entry.clockHalfPeriod,
+ eventId: entry.eventId,
+ nextVal: 1 - entry.nextVal,
+ clockHalfPeriod: entry.clockHalfPeriod,
+ });
+ }
+ }
+ return currentTime;
+ }
+
+ const dut = design.dut();
+ const sim = {
+ dut,
+ warnings: [] as readonly string[],
+
+ addClock(name: string, opts: { period: number; initialDelay?: number }) {
+ const eventId = design.resolveEvent(name);
+ clocks.set(name, { period: opts.period, eventId });
+ // The first edge (0→1) at the delay, then toggles every half period.
+ enqueue({
+ time: currentTime + (opts.initialDelay ?? 0),
+ eventId,
+ nextVal: 1,
+ clockHalfPeriod: opts.period / 2,
+ });
+ },
+
+ schedule(name: string, opts: { time: number; value: number }) {
+ enqueue({
+ time: opts.time,
+ eventId: design.resolveEvent(name),
+ nextVal: opts.value,
+ });
+ },
+
+ step: processStep,
+
+ time(): number {
+ return currentTime;
+ },
+
+ nextEventTime(): number | null {
+ return queue[0]?.time ?? null;
+ },
+
+ runUntil(endTime: number, opts?: { maxSteps?: number }) {
+ const max = opts?.maxSteps;
+ let steps = 0;
+ while (queue.length > 0 && (queue[0] as QueueEntry).time <= endTime) {
+ processStep();
+ steps++;
+ if (max != null && steps >= max) {
+ throw new Error(
+ `runUntil: exceeded ${max} steps at time ${currentTime} (target ${endTime})`,
+ );
+ }
+ }
+ currentTime = endTime;
+ },
+
+ waitUntil(condition: () => boolean, opts?: { maxSteps?: number }): number {
+ const max = opts?.maxSteps ?? 100_000;
+ let steps = 0;
+ while (!condition()) {
+ if (queue.length === 0) break;
+ processStep();
+ steps++;
+ if (steps >= max) {
+ throw new Error(
+ `waitUntil: condition not met after ${max} steps at time ${currentTime}`,
+ );
+ }
+ }
+ return currentTime;
+ },
+
+ waitForCycles(
+ clock: string,
+ count: number,
+ opts?: { maxSteps?: number },
+ ): number {
+ if (!clocks.has(clock)) {
+ throw new Error(
+ `No clock registered for '${clock}'. Call addClock() first.`,
+ );
+ }
+ const sig = layout[clock];
+ if (!sig) throw new Error(`No layout entry for clock '${clock}'.`);
+ const readClk = () => design.view.getUint8(sig.offset) & 1;
+ let prev = readClk();
+ let remaining = count;
+ return sim.waitUntil(() => {
+ const curr = readClk();
+ if (prev === 0 && curr !== 0) remaining--;
+ prev = curr;
+ return remaining <= 0;
+ }, opts);
+ },
+
+ reset(signal: string, opts?: { activeCycles?: number; duration?: number }) {
+ const sig = design.signal(signal);
+ const typeKind: string = sig.type_kind ?? "";
+ if (!typeKind.startsWith("reset")) {
+ throw new Error(
+ `Port '${signal}' is not a reset signal (type_kind: '${typeKind}').`,
+ );
+ }
+ const isActiveLow =
+ typeKind === "reset_async_low" || typeKind === "reset_sync_low";
+ const activeValue = isActiveLow ? 0n : 1n;
+ const inactiveValue = isActiveLow ? 1n : 0n;
+
+ if (opts?.duration != null) {
+ dut[signal] = activeValue;
+ sim.runUntil(currentTime + opts.duration);
+ } else {
+ const firstClock = clocks.keys().next().value;
+ if (firstClock) {
+ dut[signal] = activeValue;
+ sim.waitForCycles(firstClock, opts?.activeCycles ?? 2);
+ } else {
+ // No clock registered: assert the reset as an edge of its own.
+ const eventId = design.events[signal];
+ if (eventId !== undefined) {
+ dut[signal] = inactiveValue;
+ design.edges([eventId], [activeValue === 1n]);
+ design.flushDirty();
+ } else {
+ dut[signal] = activeValue;
+ }
+ }
+ }
+
+ dut[signal] = inactiveValue;
+ },
+
+ event(name: string): PlaygroundEventHandle {
+ return { name, id: design.resolveEvent(name) };
+ },
+
+ fourState(portName: string): PlaygroundFourStateValue {
+ return design.fourStateOf(portName);
+ },
+
+ dump(timestamp: number) {
+ design.dump(timestamp, sink);
+ },
+
+ dispose() {},
+ };
+ return sim;
+}
diff --git a/packages/playground/test/playground-dts.test.ts b/packages/playground/test/playground-dts.test.ts
index 215a5b41ad3..87ea9c8ce94 100644
--- a/packages/playground/test/playground-dts.test.ts
+++ b/packages/playground/test/playground-dts.test.ts
@@ -1,10 +1,59 @@
+import { readdirSync, readFileSync } from "node:fs";
import { describe, expect, test } from "vitest";
import {
buildVirtualModuleDts,
+ celoxDtsLibs,
extractPortsFromSource,
} from "../src/playground-dts";
+const CELOX_DIST = new URL("../../celox/dist/", import.meta.url);
+
+function celoxDistDts(): Record {
+ const files: Record = {};
+ for (const name of readdirSync(CELOX_DIST)) {
+ if (name.endsWith(".d.ts")) {
+ files[`../../celox/dist/${name}`] = readFileSync(
+ new URL(name, CELOX_DIST),
+ "utf8",
+ );
+ }
+ }
+ return files;
+}
+
+describe("celox declarations for Monaco", () => {
+ test("every import between them resolves and explicit edges are typed", () => {
+ const libs = celoxDtsLibs(celoxDistDts());
+ const paths = new Set(libs.map((lib) => lib.filePath));
+ for (const lib of libs) {
+ for (const [, name] of lib.content.matchAll(
+ /from\s+["']@celox-sim\/celox\/([\w-]+)["']/g,
+ )) {
+ expect(paths).toContain(
+ `file:///node_modules/@celox-sim/celox/${name}.d.ts`,
+ );
+ }
+ // Imports of sibling modules all point into the package.
+ expect(lib.content).not.toMatch(/from\s+["']\.\/[\w-]+\.js["']/);
+ }
+ const simulator = libs.find((lib) =>
+ lib.filePath.endsWith("/celox/simulator.d.ts"),
+ );
+ for (const method of [
+ "posedge(",
+ "negedge(",
+ "activeEdge(",
+ "inactiveEdge(",
+ "cycle(",
+ "edges(",
+ ]) {
+ expect(simulator?.content).toContain(method);
+ }
+ expect(paths).toContain("file:///node_modules/@celox-sim/celox/index.d.ts");
+ });
+});
+
describe("playground-dts", () => {
test("4-state inputs accept FourStateSignalValue in virtual module DTS", () => {
const ports = extractPortsFromSource(`module FourStateDemo (
diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts
new file mode 100644
index 00000000000..3e41fb8b612
--- /dev/null
+++ b/packages/playground/test/playground-simulator-wasm.test.ts
@@ -0,0 +1,151 @@
+/**
+ * The playground's own runtime over modules from the WASM addon: ticks,
+ * explicit edges and timed steps fire derived and gated clocks as the
+ * native simulator does. The expected counts are the native simulator's.
+ */
+import { loadNativeAddon, Simulator } from "@celox-sim/celox";
+import { describe, expect, test } from "vitest";
+import {
+ type CompilerHandle,
+ compiledFromHandle,
+} from "../src/compile-simulator";
+import {
+ createPlaygroundSimulation,
+ createPlaygroundSimulator,
+} from "../src/playground-simulator";
+
+const isWasm =
+ !!process.env.NAPI_RS_WASI_FLAVOR ||
+ process.env.NAPI_RS_FORCE_WASI === "true" ||
+ process.env.NAPI_RS_FORCE_WASI === "error";
+
+const CLOCKS = `module Top (
+ clk: input clock,
+ en: input logic,
+ rising: output logic<8>,
+ falling: output logic<8>,
+ gated_count: output logic<8>,
+ divided_count: output logic<8>,
+) {
+ always_ff (clk) { rising += 1; }
+ let inverted: '_ clock = ~clk;
+ always_ff (inverted) { falling += 1; }
+ let gated: '_ clock = clk & en;
+ always_ff (gated) { gated_count += 1; }
+ var half: logic;
+ always_ff (clk) { half = ~half; }
+ let divided: '_ clock = half;
+ always_ff (divided) { divided_count += 1; }
+}`;
+
+// `clk` has no domain of its own: it only drives the gated clock.
+const LEVER = `module Lever (clk: input clock, en: input logic, count: output logic<8>) {
+ let gated: '_ clock = clk & en;
+ always_ff (gated) { count += 1; }
+}`;
+
+type WasmAddon = {
+ NativeSimulatorHandle: new (
+ sources: { content: string; path: string }[],
+ top: string,
+ options?: { fourState?: boolean },
+ ) => CompilerHandle & { dispose(): void };
+};
+
+function compile(source: string, top: string) {
+ const addon = loadNativeAddon() as unknown as WasmAddon;
+ const handle = new addon.NativeSimulatorHandle(
+ [{ content: source, path: "top.veryl" }],
+ top,
+ { fourState: false },
+ );
+ try {
+ return compiledFromHandle(handle, false);
+ } finally {
+ handle.dispose();
+ }
+}
+
+describe.skipIf(!isWasm)("playground runtime (WASM)", () => {
+ test("explicit edges and ticks run derived and gated domains", () => {
+ const sim = createPlaygroundSimulator(compile(CLOCKS, "Top"));
+ const counts = () =>
+ [
+ sim.dut.rising,
+ sim.dut.falling,
+ sim.dut.gated_count,
+ sim.dut.divided_count,
+ ].map(Number);
+ const clk = sim.event("clk");
+ sim.dut.en = 1n;
+
+ sim.posedge(clk);
+ expect(counts()).toEqual([1, 0, 1, 1]);
+ sim.negedge(clk);
+ expect(counts()).toEqual([1, 1, 1, 1]);
+ sim.cycle(clk);
+ expect(counts()).toEqual([2, 2, 2, 1]);
+ // A tick is the active edge without moving the clock.
+ sim.tick(clk);
+ expect(counts()).toEqual([3, 2, 3, 2]);
+ sim.dut.en = 0n;
+ sim.cycle(clk);
+ expect(counts()).toEqual([4, 3, 3, 2]);
+ // The clock is already at its inactive level: no edge.
+ sim.inactiveEdge(clk);
+ expect(counts()).toEqual([4, 3, 3, 2]);
+ sim.activeEdge();
+ sim.edges([[clk, "negedge"]]);
+ expect(counts()).toEqual([5, 4, 3, 3]);
+ expect(() => sim.edges([[clk, "sideways" as "posedge"]])).toThrow(
+ RangeError,
+ );
+ });
+
+ test("a clock that only drives a gated clock is an event", () => {
+ const sim = createPlaygroundSimulator(compile(LEVER, "Lever"));
+ const clk = sim.event("clk");
+ sim.dut.en = 1n;
+ sim.cycle(clk);
+ sim.cycle(clk);
+ expect(sim.dut.count).toBe(2n);
+ sim.tick(clk);
+ expect(sim.dut.count).toBe(3n);
+ });
+
+ test("the package's WASM bridge also drives such a clock", () => {
+ const sim = Simulator.fromSource(LEVER, "Lever");
+ const clk = sim.event("clk");
+ sim.dut.en = 1n;
+ sim.cycle(clk);
+ sim.tick(clk);
+ expect(sim.dut.count).toBe(2n);
+ sim.dispose();
+ });
+
+ test("timed steps fire derived and gated clocks", () => {
+ const sim = createPlaygroundSimulation(compile(CLOCKS, "Top"));
+ sim.dut.en = 1n;
+ sim.addClock("clk", { period: 10 });
+ sim.runUntil(100);
+ expect(
+ [
+ sim.dut.rising,
+ sim.dut.falling,
+ sim.dut.gated_count,
+ sim.dut.divided_count,
+ ].map(Number),
+ ).toEqual([11, 10, 11, 6]);
+ });
+
+ test("dump reports every signal to the sink", () => {
+ const dumps: { timestamp: number; names: string[] }[] = [];
+ const sim = createPlaygroundSimulator(compile(LEVER, "Lever"), (timestamp, signals) =>
+ dumps.push({ timestamp, names: signals.map((s) => s.name) }),
+ );
+ sim.dump(7);
+ expect(dumps).toHaveLength(1);
+ expect(dumps[0]?.timestamp).toBe(7);
+ expect(dumps[0]?.names).toEqual(expect.arrayContaining(["en", "count"]));
+ });
+});