// Testbench for exercise P3.
//
// Runs the generic design (fifo_adder.sv) and the chip-level design
// (fifo_adder_chips.sv) side by side and compares both with a reference
// model: three queues kept as arrays with the head in place 0, and the
// transfer rule written out.  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 adds one pair, then several
// pairs pushed in a different order, fills C until A and B have to wait,
// pops C so that they move again, makes pseudo-random presses, resets 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;
    logic       push_a = 1'b0;
    logic       push_b = 1'b0;
    logic       pop_c  = 1'b0;
    logic [2:0] data   = '0;

    wire  [2:0] head_a,   head_a_chips;
    wire        dor_a,    dor_a_chips;
    wire  [2:0] head_b,   head_b_chips;
    wire        dor_b,    dor_b_chips;
    wire  [3:0] head_c,   head_c_chips;
    wire        dor_c,    dor_c_chips;
    wire        dir_c,    dir_c_chips;
    wire        transfer, transfer_chips;

    fifo_adder i_generic
    (
        .clk      ( clk      ),
        .rst      ( rst      ),
        .push_a   ( push_a   ),
        .push_b   ( push_b   ),
        .pop_c    ( pop_c    ),
        .data     ( data     ),
        .head_a   ( head_a   ),
        .dor_a    ( dor_a    ),
        .head_b   ( head_b   ),
        .dor_b    ( dor_b    ),
        .head_c   ( head_c   ),
        .dor_c    ( dor_c    ),
        .dir_c    ( dir_c    ),
        .transfer ( transfer )
    );

    fifo_adder_chips i_chips
    (
        .clk      ( clk            ),
        .rst      ( rst            ),
        .push_a   ( push_a         ),
        .push_b   ( push_b         ),
        .pop_c    ( pop_c          ),
        .data     ( data           ),
        .head_a   ( head_a_chips   ),
        .dor_a    ( dor_a_chips    ),
        .head_b   ( head_b_chips   ),
        .dor_b    ( dor_b_chips    ),
        .head_c   ( head_c_chips   ),
        .dor_c    ( dor_c_chips    ),
        .dir_c    ( dir_c_chips    ),
        .transfer ( transfer_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: three queues with the head in place 0, the buttons at
    // the last edge, and the transfer pulse

    logic [2:0] queue_a [0:15], queue_b [0:15];
    logic [3:0] queue_c [0:15];
    int         count_a, count_b, count_c;
    logic       push_a_was, push_b_was, pop_c_was, t;

    wire put_a  = push_a & ~ push_a_was & count_a < 16;
    wire put_b  = push_b & ~ push_b_was & count_b < 16;
    wire go     = count_a > 0 && count_b > 0 && count_c < 16 && ! t;
    wire take_c = pop_c & ~ pop_c_was & count_c > 0;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            count_a    <= 0;
            count_b    <= 0;
            count_c    <= 0;
            push_a_was <= 1'b0;
            push_b_was <= 1'b0;
            pop_c_was  <= 1'b0;
            t          <= 1'b0;
        end
        else
        begin
            push_a_was <= push_a;
            push_b_was <= push_b;
            pop_c_was  <= pop_c;
            t          <= go;

            // A and B drop the pair at the falling edge of t, one clock
            // after C took the sum

            if (t)
                for (int k = 0; k < 15; k ++)
                begin
                    queue_a [k] <= queue_a [k + 1];
                    queue_b [k] <= queue_b [k + 1];
                end

            if (take_c)
                for (int k = 0; k < 15; k ++)
                    queue_c [k] <= queue_c [k + 1];

            // After the shifts above, so that these writes win

            if (put_a)
                queue_a [t ? count_a - 1 : count_a] <= data;

            if (put_b)
                queue_b [t ? count_b - 1 : count_b] <= data;

            if (go)
                queue_c [take_c ? count_c - 1 : count_c] <= 4' (queue_a [0]) + 4' (queue_b [0]);

            count_a <= count_a + (put_a ? 1 : 0) - (t ? 1 : 0);
            count_b <= count_b + (put_b ? 1 : 0) - (t ? 1 : 0);
            count_c <= count_c + (go    ? 1 : 0) - (take_c ? 1 : 0);
        end

    // Heads are checked only while their FIFO has data

    function automatic logic ok (input logic [2:0] ha, input logic ra, input logic [2:0] hb, input logic rb,
                                 input logic [3:0] hc, input logic vc, input logic fc, input logic tr);
        return ra === (count_a > 0) && rb === (count_b > 0) && vc === (count_c > 0) && fc === (count_c < 16)
            && tr === t && (count_a == 0 || ha === queue_a [0]) && (count_b == 0 || hb === queue_b [0])
            && (count_c == 0 || hc === queue_c [0]);
    endfunction

    wire ok_generic = ok (head_a, dor_a, head_b, dor_b, head_c, dor_c, dir_c, transfer);
    wire ok_chips   = ok (head_a_chips, dor_a_chips, head_b_chips, dor_b_chips, head_c_chips, dor_c_chips,
                          dir_c_chips, transfer_chips);

    //------------------------------------------------------------------------
    // 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 n_transfers = 0;
    int n_stalled   = 0;  // Clock edges at which A and B had data but C was full

    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);
            n_transfers <= n_transfers + (~ rst && go ? 1 : 0);
            n_stalled   <= n_stalled + (~ rst && count_a > 0 && count_b > 0 && count_c == 16 ? 1 : 0);

            $display ("%5d  %b   %b %b %b  %0d  | %b %0d  %b %0d | %b | %b %b %2d %2d  %s  %s",
                cycle + 1, rst, push_a, push_b, pop_c, data, dor_a, head_a, dor_b, head_b, transfer,
                dor_c, dir_c, head_c, count_c, ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, all FIFOs must be empty.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ dor_a, dor_b, dor_c, dir_c, transfer, dor_a_chips, dor_b_chips, dor_c_chips, dir_c_chips,
              transfer_chips } !== 10'b00010_00010)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs.  As on the breadboard, the data bits change only
    // while both PUSH buttons are released: a FIFO reads them at the very
    // edge that loads them.

    // One press of a button: hold it through one edge, release it for one

    task automatic press (input logic a_on, input logic b_on, input logic c_on, input logic [2:0] value);
        data   <= value;
        push_a <= a_on;
        push_b <= b_on;
        pop_c  <= c_on;
        @ (posedge clk);
        push_a <= 1'b0;
        push_b <= 1'b0;
        pop_c  <= 1'b0;
        @ (posedge clk);
    endtask

    logic [31:0] seed = 32'd17;

    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 PA PB PC  D  | A     B    | T | C          generic  chips");

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

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

        // The example of section 2: 3 into A, 2 into B, the sum 5 in C

        press (1, 0, 0, 3);
        press (0, 1, 0, 2);
        repeat (3) @ (posedge clk);
        press (0, 0, 1, 0);

        // Five numbers into A, then three into B: three pairs move

        for (int i = 1; i <= 5; i ++)
            press (1, 0, 0, 3' (i));

        for (int i = 4; i <= 6; i ++)
            press (0, 1, 0, 3' (i));

        repeat (4) @ (posedge clk);

        // B catches up with a push into both at once

        press (1, 1, 0, 7);
        press (0, 1, 0, 1);
        press (0, 1, 0, 2);
        repeat (6) @ (posedge clk);

        // Fill C without popping until A and B have to wait

        for (int i = 0; i < 18; i ++)
            press (1, 1, 0, 3' (i));

        repeat (6) @ (posedge clk);

        // Pop C: every pop makes room for one more pair

        for (int i = 0; i < 24; i ++)
            press (0, 0, 1, 0);

        // Pseudo-random presses, the same in every simulator.  The data
        // change only while both PUSH buttons are released.

        for (int i = 0; i < 200; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;

            if (! push_a && ! push_b)
                data <= seed [26:24];

            push_a <= seed [31] & seed [30];
            push_b <= seed [29] & seed [28];
            pop_c  <= seed [27] & (seed [23] | seed [22]);

            @ (posedge clk);
        end

        push_a <= 1'b0;
        push_b <= 1'b0;
        pop_c  <= 1'b0;
        @ (posedge clk);

        // Reset in the middle, with words in the FIFOs

        press (1, 1, 0, 5);
        press (1, 0, 0, 6);
        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;
        @ (posedge clk);

        press (1, 1, 0, 4);
        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 && n_transfers >= 30 && n_stalled > 0 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, %0d transfers, %0d stalled edges, %0d resets",
                      n_errors, n_checks, n_transfers, n_stalled, n_async);
    end

endmodule
