// Testbench for exercise B4.
//
// Runs the generic design (d_flip_flop.sv) and the chip-level design
// (d_flip_flop_chips.sv) side by side and compares both with a reference
// model.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// On the breadboard you can press the D button at any moment, also in the
// middle of a clock period.  To do the same, the testbench has its own,
// faster clock, tick, and treats the clock of the flip-flop as one more
// input: like the testbenches of Basics-Graphics-Music it changes clk, rst
// and d only right after rising edges of tick and checks the outputs only
// at rising edges of tick.  It never changes d at the tick where clk rises.

// 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 tick;
    logic clk, rst, d;

    wire  q,   q_chips;
    wire  q_n, q_n_chips;

    d_flip_flop i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .d   ( d   ),
        .q   ( q   ),
        .q_n ( q_n )
    );

    d_flip_flop_chips i_chips
    (
        .clk ( clk       ),
        .rst ( rst       ),
        .d   ( d         ),
        .q   ( q_chips   ),
        .q_n ( q_n_chips )
    );

    //------------------------------------------------------------------------
    // The testbench clock, period 10 ns.  The flip-flop clock below has a
    // period of 8 ticks; on the breadboard it is about a second.

    initial
    begin
        tick = '0;

        forever
            # 5 tick = ~ tick;
    end

    //------------------------------------------------------------------------
    // The stimulus as three timing charts, one character per tick.
    // Rising edges of clk at ticks 4, 12, 20, 28, 36 and 44.
    //
    //  tick   0   4   8   12  16  20  24  28  32  36  40  44
    //  clk    0000111100001111000011110000111100001111000011110
    //  rst    0110000000000000000000000000000000000000000000100
    //  d      0000001111111100011111000000001111000011111111111
    //
    // D is 1 at the edge at tick 12, so Q becomes 1.  The short 0 at ticks
    // 14-16 and the short 1 at ticks 30-33 come and go between edges: Q does
    // not see them.  The reset at tick 46 clears Q at once, without an edge.

    localparam n_ticks = 49;

    // The leftmost character is tick 0, the highest bit of each vector

    wire [n_ticks - 1:0] clk_wave = 49'b0000111100001111000011110000111100001111000011110;
    wire [n_ticks - 1:0] rst_wave = 49'b0110000000000000000000000000000000000000000000100;
    wire [n_ticks - 1:0] d_wave   = 49'b0000001111111100011111000000001111000011111111111;

    //------------------------------------------------------------------------
    // Reference model.  Like RESET of the 4013, rst clears Q at once.

    logic q_expected;

    always @ (posedge clk or posedge rst)
        if (rst)
            q_expected <= 1'b0;
        else
            q_expected <= d;

    wire ok_generic = q       === q_expected && q_n       === ~ q_expected;
    wire ok_chips   = q_chips === q_expected && q_n_chips === ~ q_expected;

    //------------------------------------------------------------------------
    // Checking at every rising edge of tick, from the first reset on

    // Initial values are fine in a testbench, and the checker samples rst at
    // the tick 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 n_ticks_seen = 0;
    int n_checks     = 0;
    int n_errors     = 0;
    int n_ones       = 0;    // Ticks with Q = 1, to see that Q did change

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

        if (~ done)
            n_ticks_seen <= n_ticks_seen + 1;

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

        if (~ done)
            $display ("%4d   %b   %b   %b   %b  %b    %s  %s",
                n_ticks_seen, clk, rst, d, q, q_n,
                ~ (rst | was_reset) ? "-      " : ok_generic ? "ok     " : "WRONG  ",
                ~ (rst | was_reset) ? "-    "   : ok_chips   ? "ok   "   : "WRONG");
    end

    //------------------------------------------------------------------------
    // Driving clk, rst and d from the timing charts

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

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

        $display ("tick  clk rst  d   Q ~Q    generic  chips");

        for (int i = 0; i < n_ticks; i ++)
        begin
            clk <= clk_wave [n_ticks - 1 - i];
            rst <= rst_wave [n_ticks - 1 - i];
            d   <= d_wave   [n_ticks - 1 - i];

            @ (posedge tick);
        end

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

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

        $finish;
    end

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

    final
    begin
        if (n_errors == 0 && n_checks > 0 && n_ones == 18)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, Q = 1 for %0d ticks", n_errors, n_checks, n_ones);
    end

endmodule
