// Testbench for exercise B6.
//
// Runs the generic design (shift_register.sv) and the chip-level design
// (shift_register_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 shifts in a bit pattern, checks
// that every bit comes out of q [k] k + 1 clock edges after it went in, and
// resets the register in the middle of the run.

// 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;
    logic       d;

    wire  [7:0] q, q_chips;

    shift_register i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .d   ( d   ),
        .q   ( q   )
    );

    shift_register_chips i_chips
    (
        .clk ( clk     ),
        .rst ( rst     ),
        .d   ( d       ),
        .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 last eight values of d, one per clock edge since
    // the last reset, the newest at the bottom.  q [k] must equal the bit
    // that came in k + 1 edges ago.

    logic [7:0] history;
    int          n_in;  // Bits shifted in since the last reset

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            history <= '0;
            n_in    <= 0;
        end
        else
        begin
            history <= { history [6:0], d };
            n_in    <= n_in + 1;
        end

    wire [7:0] q_expected = history [7:0];

    //------------------------------------------------------------------------
    // 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;
    int max_in   = 0;        // The longest run without a 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 + (q === q_expected ? 0 : 1) + (q_chips === q_expected ? 0 : 1);
            max_in   <= n_in > max_in ? n_in : max_in;

            $display ("%5d  %b   %b   %b   %s  %s",
                cycle + 1, rst, d, q,
                q       === q_expected ? "ok     " : "WRONG  ",
                q_chips === q_expected ? "ok   "   : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Driving the inputs: a pattern of bits, one per clock, as if you pressed
    // the D button during some clock periods and not during others

    localparam n_bits = 28;

    wire [n_bits - 1:0] pattern = 28'b1011_0011_1000_0110_1111_0100_1101;  // From the left

    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  d   q [7:0]    generic  chips");

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

        d   <= '0;
        rst <= 'x;
        repeat (3) @ (posedge clk);
        rst <= '1;
        repeat (3) @ (posedge clk);
        rst <= '0;

        for (int i = 0; i < n_bits; i ++)
        begin
            d <= pattern [n_bits - 1 - i];
            @ (posedge clk);

            // Reset in the middle of the run.  Both designs must clear at
            // once, not at the next clock edge, like RESET of the 4015.

            if (i == 19)
            begin
                rst <= '1;
                @ (posedge clk);
                rst <= '0;
            end
        end

        d <= '0;
        repeat (4) @ (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 && max_in >= 16)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, longest run %0d bits", n_errors, n_checks, max_in);
    end

endmodule
