Writing Tests
Celox provides two simulation modes: event-based (Simulator) for manual clock control, and time-based (Simulation) for automatic clock generation.
Event-Based Simulation
Simulator gives you direct control over clock ticks. Use it when you want to drive clock edges explicitly, step by step.
import { describe, test, expect } from "vitest";
import { Simulator } from "@celox-sim/celox";
import { Reg } from "../src/Reg.veryl";
describe("Reg", () => {
test("captures input on clock edge", () => {
const sim = Simulator.create(Reg);
// Load a value and clock it in
sim.dut.d = 0xABn;
sim.tick();
expect(sim.dut.q).toBe(0xABn);
// Change input — output should not change until next tick
sim.dut.d = 0xCDn;
expect(sim.dut.q).toBe(0xABn);
sim.tick();
expect(sim.dut.q).toBe(0xCDn);
sim.dispose();
});
});Where src/Reg.veryl is:
module Reg (
clk: input clock,
rst: input reset,
d: input logic<8>,
q: output logic<8>,
) {
always_ff (clk, rst) {
if_reset {
q = 0;
} else {
q = d;
}
}
}Simulator.create(Module)creates a simulator instance from a Veryl module definition.- Signal values are read and written via
sim.dut.<port>. sim.tick()advances the simulation by one clock period: the clock's active edge, then its inactive edge. Every domain sensitive to either edge runs, including clocks derived from it, such as a gatedclk & en, a register-driven divider or~clk. See Execution Semantics for the SystemVerilog a tick is equivalent to.sim.dispose()frees the native resources.
Combinational logic
For purely combinational modules (always_comb only), tick() is not required. Reading an output automatically evaluates the combinational logic with the current inputs.
Clock edges
tick() drives a whole clock period. To stop between the two edges, or to drive a reset, move the signals edge by edge:
const clk = sim.event("clk");
sim.posedge(clk); // clk = 1: domains sensitive to its rising edge run
sim.negedge(clk); // clk = 0: domains sensitive to its falling edge run
sim.activeEdge(clk); // the clock's own edge: rising for a posedge clock
sim.inactiveEdge(clk); // the opposite edge
// Several clocks at one instant: every domain samples the state before them.
sim.edges([
[clk, "posedge"],
[sim.event("clk_b"), "posedge"],
]);An edge moves the clock signal and leaves it at its new level, so it can be read through sim.dut. An edge to the level the signal already has does nothing. Each edge runs the domains a timed simulation would run at that transition: the clock's own domain on its active edge, clocks computed from it (clk & en, ~clk) that see their active edge, sampling the state from before the edge, and the domains that the resulting updates clock in turn. For Veryl's abstract clock type, activeEdge() follows the build's clock type (clockType: "negedge" makes it the falling edge). Reset ports work the same way: negedge(rst) asserts an active-low asynchronous reset.
tick() is activeEdge() followed by inactiveEdge(), and gives the same results as two timed steps of the clock, a rising and a falling one.
Time-Based Simulation
Simulation timestamps and clock periods count global-precision ticks. Veryl uses 1ps per tick. SystemVerilog uses the design's global time precision (default 1ps). VCD headers and VPI time properties queried with a NULL handle use that global precision. VPI queries on a module or its signals return the module's own time unit and precision. Existing Veryl VCD exports now declare 1ps instead of 1ns; their numeric timestamps are unchanged. Native images compiled before this change must be recompiled for the updated container format.
Simulation manages clock generation for you. This is the natural choice for sequential logic with clocked flip-flops.
import { describe, test, expect } from "vitest";
import { Simulation } from "@celox-sim/celox";
import { Counter } from "../src/Counter.veryl";
describe("Counter", () => {
test("counts up when enabled", () => {
const sim = Simulation.create(Counter);
sim.addClock("clk", { period: 10 });
// Assert reset
sim.dut.rst = 1n;
sim.runUntil(20);
// Release reset and enable counting
sim.dut.rst = 0n;
sim.dut.en = 1n;
sim.runUntil(100);
expect(sim.dut.count).toBeGreaterThan(0n);
expect(sim.time()).toBe(100);
sim.dispose();
});
});sim.addClock("clk", { period: 10 })adds a clock with period 10 (toggles every 5 time units).sim.runUntil(t)advances simulation time tot.sim.time()returns the current simulation time.
Testbench Helpers
The Simulation class provides convenience methods for common testbench patterns.
Reset Helper
The active level is determined automatically from the Veryl port type (reset, reset_async_high, reset_async_low, etc.), so you never need to specify the polarity manually.
const sim = Simulation.create(Counter);
sim.addClock("clk", { period: 10 });
// Assert rst for 2 cycles (default), then release
sim.reset("rst");
// Custom: hold reset for 3 clock cycles
sim.reset("rst_n", { activeCycles: 3 });Waiting for Conditions
// Wait until a condition is met (polls via step())
const t = sim.waitUntil(() => sim.dut.done === 1n);
// Wait for a specific number of clock cycles
const t = sim.waitForCycles("clk", 10);Both methods accept an optional { maxSteps } parameter. The default step budget is 100,000, but can be changed project-wide via [simulation] max_steps in celox.toml. A SimulationTimeoutError is thrown if the step budget is exceeded:
import { SimulationTimeoutError } from "@celox-sim/celox";
try {
sim.waitUntil(() => sim.dut.done === 1n, { maxSteps: 1000 });
} catch (e) {
if (e instanceof SimulationTimeoutError) {
console.log(`Timed out at time ${e.time} after ${e.steps} steps`);
}
}Timeout Guard for runUntil
Pass { maxSteps } to runUntil() to bound the number of steps. Both forms run in the Rust scheduler:
// Unbounded
sim.runUntil(10000);
// Guarded: throws SimulationTimeoutError if budget is exceeded
sim.runUntil(10000, { maxSteps: 500 });Runtime Events and Reports
drainRuntimeEvents() returns what the design emitted since the last call, in emission order: $display and $write output, report events of severity tasks and failed assertions, $finish and $stop. A report has its severity ("info", "warning", "error" or "fatal"), its message bytes, and the scope, file and line that issued it.
setFailOn(severity) makes runUntil(), step() and the waits throw after the time step of the first report of at least that severity. While it is set, each report keeps the time it was issued at. Events lost to a full event buffer (a missed event) count as a failure, since they may have held one. A later call continues the simulation.
sim.setFailOn("error");
try {
sim.runUntil(10000);
} catch (error) {
// "failOn: Error: ..." at the time of the first $error
}
for (const event of sim.drainRuntimeEvents()) {
if (event.kind === "report") {
console.log(event.severity, event.time, new TextDecoder().decode(event.message));
}
}Coverage
coverage() returns the covergroup coverage of the simulation (IEEE 1800-2023 clause 19) as of the last completed step: every covergroup type that has an instance, with its coverpoints and crosses, their bins and hits, for the type and for each instance. The report is a CoverageReport object, parsed from the JSON of the Rust Simulation::coverage(). Each call builds it; reading it changes nothing and advances no time. A design without covergroups, any Veryl design included, reports { coverage: 100, covergroups: [] }. Hit and sample counts are JavaScript numbers, exact up to Number.MAX_SAFE_INTEGER.
Covergroups are SystemVerilog: list the .sv source in the module definition. A hit of an illegal_bins bin is an "error" report that drainRuntimeEvents() returns, and its hit is in the report too.
const Top: ModuleDefinition<Record<string, never>> = {
__celox_module: true,
name: "Top",
sources: [{ path: "Top.sv", content: source }], // declares and samples covergroups
ports: {},
events: [],
};
const sim = Simulation.create(Top);
sim.runUntil(1000);
const report = sim.coverage();
console.log(`$get_coverage() = ${report.coverage}%`);
for (const group of report.covergroups) {
for (const item of group.items) {
for (const bin of item.bins) {
console.log(`${group.name}.${item.name} ${bin.name}: ${bin.hits}`);
}
}
}Only Simulation reports coverage; the event-based Simulator has no coverage(). A Simulator runs no process, so a design that constructs a covergroup in a declaration initializer (cg c = new;) or an initial block fails to build as one. The one construction it runs, in a clocked procedure (always @(posedge clk) if (c == null) c = new;), would report its illegal bin hits as runtime events, which the Simulator handle does not drain. Covergroups are not available in the browser (WASI) build.
Simulator Options
Both Simulator and Simulation accept the following options:
const sim = Simulator.fromSource(source, "Top", {
fourState: true, // Enable 4-state (X) simulation
vcd: "./dump.vcd", // Write VCD waveform output (or fst: "./dump.fst")
optLevel: "O1", // "O0" | "O1" | "O2"
passOverrides: ["-sir:reschedule"], // per-pass overrides on top of optLevel
clockType: "posedge", // Clock polarity (default: "posedge")
resetType: "async_low", // Reset type (default: "async_low")
deadStorePolicy: "preserveAllPorts", // Dead store elimination policy
parameters: [ // Top-level parameter overrides
{ name: "WIDTH", value: 16 },
],
// Legacy API remains available for compatibility
optimize: true,
optimizeOptions: {
reschedule: true,
},
craneliftOptLevel: "speed", // "none" | "speed" | "speedAndSize"
regallocAlgorithm: "backtracking", // "backtracking" | "singlePass"
enableAliasAnalysis: true, // alias analysis in egraph pass
enableVerifier: true, // Cranelift IR verifier
});The current recommended entry point is optLevel plus passOverrides.
optLevel: "O0"prioritizes compile time over simulation speed.optLevel: "O1"is the standard default.optLevel: "O2"adds dead store elimination on top ofO1.
optimize and optimizeOptions still exist for backward compatibility, but new code is clearer when it uses optLevel / passOverrides.
Compile-Time Tuning
If compilation is too slow, start with these knobs:
optLevel: "O0"-- reduces Celox-side SIR optimization work.regallocAlgorithm: "singlePass"-- Switches from the backtracking register allocator to a single-pass allocator. Much faster compilation but generates code with more register spills and moves (slower simulation).craneliftOptLevel: "none"-- Disables the egraph optimization pass entirely.enableVerifier: false-- Skips IR verification.enableAliasAnalysis: false-- Disables alias analysis during the egraph pass (only effective whencraneliftOptLevelis not"none").
Type-Safe Imports
The Vite plugin automatically generates TypeScript type definitions for your .veryl files. When you write:
import { Counter } from "../src/Counter.veryl";All ports are fully typed -- you get autocompletion and compile-time checks for port names. All signal port values use bigint.
Running Tests
pnpm testChoosing a Factory Method
All three factory methods produce an equivalent simulator — the difference is where the source comes from.
Simulator.create(Module) / Simulation.create(Module) is the standard choice when using the Vite plugin. The imported Module carries the project path, so create delegates directly to fromProject and picks up all source files and Veryl.toml settings automatically. Port types are fully generated.
import { Adder } from "../src/Adder.veryl"; // generated by Vite plugin
const sim = Simulator.create(Adder);fromProject(path, name) does the same thing as create but takes an explicit path. Use it when you need to point at a project directory without a statically imported module — for example, from a Node.js script that is not part of a Vite build.
const sim = Simulator.fromProject("./my-project", "Adder");fromSource(source, name) compiles a raw Veryl source string with no Veryl.toml. Clock and reset settings must be passed explicitly via options. Useful for self-contained tests or when the design lives entirely in the test file.
const SOURCE = `
module Adder ( ... ) { ... }
`;
const sim = Simulator.fromSource(SOURCE, "Adder", {
clockType: "posedge",
resetType: "async_low",
});Further Reading
- 4-State Simulation -- Using X values in testbenches.
- Parameter Overrides -- Overriding module parameters at simulation time.
- Dead Store Elimination -- Speeding up simulation with DSE.
- Architecture -- The simulation pipeline in detail.
- API Reference -- Full TypeScript API documentation.
HDL output bytes
Rust runtime events (RuntimeEvent::{Display, Write} and the message of RuntimeEvent::Report) and detailed testbench assertion messages return Vec<u8>. JavaScript runTest, runTestFromProject, and runTestWithFrontendArtifact return assertion messages as Uint8Array. %s and %c may contain non-UTF-8 bytes or NUL, so byte payloads are never decoded implicitly. Display/write forwarding also writes the bytes directly.
Decode explicitly when the design emits UTF-8 text:
const text = new TextDecoder("utf-8", { fatal: true }).decode(
result.assertions[0]?.message,
);In Rust, use String::from_utf8(message) to validate UTF-8, or compare the bytes directly. Simulator errors and test failure summaries are human-readable diagnostics: invalid UTF-8 payloads appear as escaped bytes in those summaries, while the original bytes remain in the event or assertion result.
This replaces the earlier string message API; update string comparisons to byte comparisons or explicit decoding.