// Testbench for exercise M12.
//
// Runs the generic design (counter_race.sv) and the chip-level design
// (counter_race_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 the two counters through
// 40 clock periods, more than twice the 16 states of the binary counter,
// resets them in the middle, and checks that reset acts at once.

// 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  [3:0] binary,  binary_chips;
    wire  [3:0] johnson, johnson_chips;
    wire        a_gt_b,  a_gt_b_chips;
    wire        a_eq_b,  a_eq_b_chips;
    wire        a_lt_b,  a_lt_b_chips;

    counter_race i_generic
    (
        .clk     ( clk     ),
        .rst     ( rst     ),
        .binary  ( binary  ),
        .johnson ( johnson ),
        .a_gt_b  ( a_gt_b  ),
        .a_eq_b  ( a_eq_b  ),
        .a_lt_b  ( a_lt_b  )
    );

    counter_race_chips i_chips
    (
        .clk     ( clk           ),
        .rst     ( rst           ),
        .binary  ( binary_chips  ),
        .johnson ( johnson_chips ),
        .a_gt_b  ( a_gt_b_chips  ),
        .a_eq_b  ( a_eq_b_chips  ),
        .a_lt_b  ( a_lt_b_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 clock edges since reset.  The binary
    // counter shows it modulo 16; the Johnson counter shows the code of
    // state t mod 8.  rst sets 0 at once.

    int t;

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

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

    wire [3:0] binary_expected  = 4' (t);
    wire [3:0] johnson_expected = johnson_code (t % 8);

    wire [2:0] compare_expected = { binary_expected >  johnson_expected,
                                    binary_expected == johnson_expected,
                                    binary_expected <  johnson_expected };

    wire ok_generic =    binary        === binary_expected
                      && johnson       === johnson_expected
                      && { a_gt_b, a_eq_b, a_lt_b } === compare_expected;

    wire ok_chips   =    binary_chips  === binary_expected
                      && johnson_chips === johnson_expected
                      && { a_gt_b_chips, a_eq_b_chips, a_lt_b_chips } === compare_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 [2:0] lights_seen = '0;  // Which of A>B, A=B, A<B were seen

    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);
            lights_seen <= lights_seen | compare_expected;

            $display ("%5d  %b    %b %2d   %b %2d   %s   %s  %s",
                cycle + 1, rst, binary, binary, johnson, johnson,
                a_gt_b ? "A>B" : a_eq_b ? "A=B" : a_lt_b ? "A<B" : "---",
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both counters must be 0.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ binary, johnson, binary_chips, johnson_chips } !== 16'b0)
        begin
            $display ("WRONG: reset did not act at once");
            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  binary    Johnson   light  generic  chips");

        // Before reset the counters are unknown, as after power-up

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

        repeat (40) @ (posedge clk);

        // Reset in the middle

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

        repeat (10) @ (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 && lights_seen == 3'b111 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, lights seen %b, %0d resets", n_errors, n_checks,
                      lights_seen, n_async);
    end

endmodule
