// Testbench for exercise P7.
//
// Runs the generic design (serial_compare.sv) and the chip-level design
// (serial_compare_chips.sv) side by side and compares both with a reference
// model that collects the bits since reset into two numbers and compares
// the numbers.  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.  Every comparison starts with a reset
// and feeds two numbers lowest bit first, up to 16 bits long, beyond what
// one 4063 can compare.

// 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 a = 1'b0;
    logic b = 1'b0;

    wire  gt, gt_chips;
    wire  lt, lt_chips;
    wire  eq, eq_chips;

    serial_compare i_generic
    (
        .clk ( clk ),
        .rst ( rst ),
        .a   ( a   ),
        .b   ( b   ),
        .gt  ( gt  ),
        .lt  ( lt  ),
        .eq  ( eq  )
    );

    serial_compare_chips i_chips
    (
        .clk ( clk      ),
        .rst ( rst      ),
        .a   ( a        ),
        .b   ( b        ),
        .gt  ( gt_chips ),
        .lt  ( lt_chips ),
        .eq  ( eq_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 numbers made of the bits since reset

    logic [31:0] value_a, value_b;
    int          n_bits;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            value_a <= '0;
            value_b <= '0;
            n_bits  <= 0;
        end
        else
        begin
            value_a <= value_a | (32' (a) << n_bits);
            value_b <= value_b | (32' (b) << n_bits);
            n_bits  <= n_bits + 1;
        end

    wire [2:0] expected = { value_a > value_b, value_a == value_b, value_a < value_b };

    wire ok_generic = { gt,       eq,       lt       } === expected;
    wire ok_chips   = { gt_chips, eq_chips, lt_chips } === 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] results_seen = '0;  // GT, EQ, LT after more than 4 bits
    int         n_compared   = 0;

    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 (n_bits > 4)
                results_seen <= results_seen | expected;

            $display ("%5d  %b    %b  %b  %b   %b   %b   %5d %5d  %s  %s",
                cycle + 1, rst, a, b, gt, eq, lt, value_a, value_b,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both designs must say A = B.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ gt, eq, lt, gt_chips, eq_chips, lt_chips } !== 6'b010_010)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs

    // One comparison: reset, the bits lowest first, then one more pair of
    // zeros, which does not change the numbers, so that the last result
    // stays for a clock edge before the next reset

    task automatic compare (input logic [15:0] x, input logic [15:0] y, input int n);
        rst <= 1'b1;
        a   <= 1'b0;
        b   <= 1'b0;
        @ (posedge clk);
        rst <= 1'b0;

        for (int k = 0; k < n; k ++)
        begin
            a <= x [k];
            b <= y [k];
            @ (posedge clk);
        end

        a <= 1'b0;
        b <= 1'b0;
        @ (posedge clk);

        n_compared <= n_compared + 1;
    endtask

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

    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  A  B  GT  EQ  LT   A so far B so far  generic  chips");

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

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

        // The example of section 2, then numbers of growing length

        compare (    6,    10,  4);
        compare (    5,     3,  4);
        compare (    9,     9,  4);
        compare (  200,   201,  8);
        compare ( 1000,   999, 10);
        compare (12345, 12345, 16);
        compare (65535, 65534, 16);

        // Pseudo-random pairs, the same in every simulator; every third pair
        // is equal

        for (int i = 0; i < 12; i ++)
        begin
            logic [15:0] x, y;

            seed = seed * 32'd1664525 + 32'd1013904223;
            x    = seed [31:16];
            seed = seed * 32'd1664525 + 32'd1013904223;
            y    = i % 3 == 0 ? x : seed [31:16];

            compare (x, y, 1 + int' (seed [3:0]));
        end

        // 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 && results_seen == 3'b111 && n_compared == 19 && n_async >= 19)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, results seen %b, %0d comparisons, %0d resets",
                      n_errors, n_checks, results_seen, n_compared, n_async);
    end

endmodule
