// Testbench for exercise M10.
//
// Runs the generic design (johnson_counter.sv) and the chip-level design
// (johnson_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 runs through the ten states of
// the ring more than twice, resets in the middle, and checks that reset acts
// at once, without waiting for the clock, like RESET A and B of the 4015.

// 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  [4:0] q, q_chips;

    johnson_counter i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .q   ( q   )
    );

    johnson_counter_chips i_chips
    (
        .clk ( clk     ),
        .rst ( rst     ),
        .q   ( q_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 number of the state, 0 to 9, and its Johnson
    // code: k ones from the bottom for k <= 5, then 10 - k ones from the top.
    // rst sets state 0 at once.

    int count;

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

    function automatic logic [4:0] johnson_code (input int k);
        if (k <= 5)
            return 5' ((1 << k) - 1);
        else
            return 5' (5'b11111 << (k - 5));
    endfunction

    wire [4:0] q_expected = johnson_code (count);

    wire ok_generic = q       === q_expected;
    wire ok_chips   = q_chips === q_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    %0d      %s  %s",
                cycle + 1, rst, q, 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 !== 5'b0 || q_chips !== 5'b0)
        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  Q5..Q1  state  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 of ten states

        // 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
