// Testbench for exercise BB7.
//
// Runs the generic design (decade_counter.sv) and the chip-level design
// (decade_counter_chips.sv) side by side and compares both with a reference
// model.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  It counts through the ten states
// more than twice, resets in the middle of the count, and checks that reset
// acts at once, without waiting for the clock, like RESET of the 4017.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

    logic       clk;
    logic       rst;

    wire  [9:0] q,         q_chips;
    wire        carry_out, carry_out_chips;

    decade_counter i_generic
    (
        .clk       ( clk       ),
        .rst       ( rst       ),
        .q         ( q         ),
        .carry_out ( carry_out )
    );

    decade_counter_chips i_chips
    (
        .clk       ( clk             ),
        .rst       ( rst             ),
        .q         ( q_chips         ),
        .carry_out ( carry_out_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the count as an integer.  rst sets 0 at once.

    int count;

    always @ (posedge clk or posedge rst)
        if (rst)
            count <= 0;
        else
            count <= (count + 1) % 10;

    wire [9:0] q_expected     = 10'b1 << count;
    wire       carry_expected = count < 5;

    wire ok_generic = q       === q_expected && carry_out       === carry_expected;
    wire ok_chips   = q_chips === q_expected && carry_out_chips === carry_expected;

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

    logic was_reset = 1'b0;
    logic done      = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    logic [9:0] seen = '0;   // Which counts were checked outside reset

    always @ (posedge clk)
    begin
        if (rst)
            was_reset <= 1'b1;

        if ((rst | was_reset) & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1);

            if (~ rst)
                seen [count] <= 1'b1;

            $display ("%5d  %b    %b  %b    %0d     %s  %s",
                cycle + 1, rst, q, carry_out, count,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: in the middle of a clock period, the outputs must
    // show count 0 at once.  The stimulus sets rst right after an edge; one
    // time unit later the reset has acted.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if (q !== 10'b1 || q_chips !== 10'b1)
        begin
            $display ("WRONG: reset did not act at once, q = %b, q_chips = %b", q, q_chips);
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs

    initial
    begin
        $dumpfile ("tb.vcd");

        `ifdef __ICARUS__
            $dumpvars (0, tb);  // Without a scope Icarus also tries to dump $unit
        `else
            $dumpvars;
        `endif

        $display ("cycle  rst  Q9...Q0     CO  count  generic  chips");

        // Before reset the count is unknown, as after power-up

        rst <= 1'bx;
        repeat (2) @ (posedge clk);
        rst <= 1'b1;
        repeat (2) @ (posedge clk);
        rst <= 1'b0;

        repeat (23) @ (posedge clk);   // More than twice round the ring

        // Reset in the middle of the count

        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;

        repeat (12) @ (posedge clk);

        // Stop checking one clock edge before $finish, so that every
        // simulator reports the same number of checks

        done <= '1;
        @ (posedge clk);

        $finish;
    end

    //------------------------------------------------------------------------

    final
    begin
        if (n_errors == 0 && seen == 10'h3ff && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, counts seen %b, %0d resets", n_errors, n_checks, seen,
                      n_async);
    end

endmodule
