// Testbench for exercise P2.
//
// Runs the generic design (serial_adder_gates.sv) and the chip-level design
// (serial_adder_gates_chips.sv) side by side and compares both with a reference
// model that knows the answer in advance: at LOAD it takes a + b, and the
// bit streams are the bits of the numbers and of the sum, lowest first.
// 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 chosen and pseudo-random
// pairs, holds LOAD for several edges once, and checks the bit streams,
// the carry, the deserializer and the three displays at every edge.

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

    // load is a synchronous load and an asynchronous clear, as on the
    // breadboard

    // verilator lint_off SYNCASYNCNET

    logic       clk;
    logic       load = 1'b0;
    logic [3:0] a    = '0;
    logic [3:0] b    = '0;

    wire        serial_a,    serial_a_chips;
    wire        serial_b,    serial_b_chips;
    wire        serial_sum,  serial_sum_chips;
    wire        carry,       carry_chips;
    wire  [3:0] sum,         sum_chips;
    wire  [6:0] abcdefg_a,   abcdefg_a_chips;
    wire  [6:0] abcdefg_b,   abcdefg_b_chips;
    wire  [6:0] abcdefg_sum, abcdefg_sum_chips;

    serial_adder_gates i_generic
    (
        .clk         ( clk         ),
        .load        ( load        ),
        .a           ( a           ),
        .b           ( b           ),
        .serial_a    ( serial_a    ),
        .serial_b    ( serial_b    ),
        .serial_sum  ( serial_sum  ),
        .carry       ( carry       ),
        .sum         ( sum         ),
        .abcdefg_a   ( abcdefg_a   ),
        .abcdefg_b   ( abcdefg_b   ),
        .abcdefg_sum ( abcdefg_sum )
    );

    serial_adder_gates_chips i_chips
    (
        .clk         ( clk               ),
        .load        ( load              ),
        .a           ( a                 ),
        .b           ( b                 ),
        .serial_a    ( serial_a_chips    ),
        .serial_b    ( serial_b_chips    ),
        .serial_sum  ( serial_sum_chips  ),
        .carry       ( carry_chips       ),
        .sum         ( sum_chips         ),
        .abcdefg_a   ( abcdefg_a_chips   ),
        .abcdefg_b   ( abcdefg_b_chips   ),
        .abcdefg_sum ( abcdefg_sum_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 taken at the last LOAD edge, their sum,
    // and the number of edges since then

    logic [3:0] a_loaded, b_loaded;
    int         k;

    always @ (posedge clk)
        if (load)
        begin
            a_loaded <= a;
            b_loaded <= b;
            k        <= 0;
        end
        else
            k <= k + 1;

    wire [4:0] total = 5' (a_loaded) + 5' (b_loaded);

    function automatic logic bit_of (input logic [4:0] value, input int i);
        return i >= 0 && i < 5 ? value [i] : 1'b0;
    endfunction

    // After k edges the deserializer holds the sum bits k-1 (in sum [3])
    // down to k-4; LOAD at 1 clears it at once

    logic [3:0] sum_expected;

    always_comb
        for (int i = 0; i < 4; i ++)
            sum_expected [3 - i] = ~ load & bit_of (total, k - 1 - i);

    function automatic logic [6:0] digit (input logic [3:0] code);
        case (code)
        4'd0:    digit = 7'b111_1110;
        4'd1:    digit = 7'b011_0000;
        4'd2:    digit = 7'b110_1101;
        4'd3:    digit = 7'b111_1001;
        4'd4:    digit = 7'b011_0011;
        4'd5:    digit = 7'b101_1011;
        4'd6:    digit = 7'b001_1111;
        4'd7:    digit = 7'b111_0000;
        4'd8:    digit = 7'b111_1111;
        4'd9:    digit = 7'b111_0011;
        default: digit = 7'b000_0000;
        endcase
    endfunction

    // The carry into bit k: the carry out of the lower k bits.  LOAD at 1
    // clears the carry flip-flop at once, as RESET of the 4013.

    function automatic logic carry_into (input logic [3:0] x, input logic [3:0] y, input int i);
        logic [4:0] low;

        low = i <= 0 ? 5'd0 : i >= 5 ? 5' (x) + 5' (y) : 5' (x & 4' ((1 << i) - 1)) + 5' (y & 4' ((1 << i) - 1));
        return i >= 1 && i <= 4 ? low [i] : 1'b0;
    endfunction

    wire carry_expected = ~ load & carry_into (a_loaded, b_loaded, k);

    wire serial_a_expected = bit_of (5' (a_loaded), k);
    wire serial_b_expected = bit_of (5' (b_loaded), k);

    wire [28:0] expected = { serial_a_expected, serial_b_expected,
                             serial_a_expected ^ serial_b_expected ^ carry_expected, carry_expected,
                             sum_expected, digit (a), digit (b), digit (sum_expected) };

    wire [28:0] out       = { serial_a, serial_b, serial_sum, carry, sum, abcdefg_a, abcdefg_b, abcdefg_sum };
    wire [28:0] out_chips = { serial_a_chips, serial_b_chips, serial_sum_chips, carry_chips, sum_chips,
                              abcdefg_a_chips, abcdefg_b_chips, abcdefg_sum_chips };

    wire ok_generic = out       === expected;
    wire ok_chips   = out_chips === expected;

    //------------------------------------------------------------------------
    // Checking at every rising clock edge, from the first LOAD on.  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 load
    // at the clock edge on purpose, although it clears the deserializer at
    // once

    // verilator lint_off PROCASSINIT

    logic was_loaded = 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_sums   = 0;  // Complete sums seen in the deserializer
    int n_carry  = 0;  // Sums with a fifth bit

    always @ (posedge clk)
    begin
        if (load)
            was_loaded <= 1'b1;

        if (was_loaded & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1);

            if (~ load && k == 4)
            begin
                n_sums  <= n_sums + 1;
                n_carry <= n_carry + (total [4] ? 1 : 0);
            end

            $display ("%5d  %b     %2d  %2d   %b  %b  %b  %b   %b  %s  %s",
                cycle + 1, load, a, b, serial_a, serial_b, carry, serial_sum, sum,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

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

    // One addition: set the buttons, press LOAD through one or more edges,
    // then let six edges pass

    task automatic add (input logic [3:0] x, input logic [3:0] y, input int load_edges);
        a    <= x;
        b    <= y;
        load <= 1'b1;
        repeat (load_edges) @ (posedge clk);
        load <= 1'b0;
        repeat (6) @ (posedge clk);
    endtask

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

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

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

        $display ("cycle  LOAD   A   B   A> B> C  S>  4015  generic  chips");

        // Before the first LOAD the registers are unknown, as after power-up

        repeat (2) @ (posedge clk);

        add ( 5,  3, 1);  // The example of section 2
        add ( 9,  8, 1);  // 17: a fifth bit
        add (15, 15, 1);
        add ( 0,  0, 1);
        add ( 7,  2, 3);  // LOAD held for three edges

        // Pseudo-random pairs, the same in every simulator

        for (int i = 0; i < 10; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;
            add (seed [31:28], seed [27:24], 1);
        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 && n_sums == 15 && n_carry >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, %0d sums, %0d with a fifth bit", n_errors, n_checks, n_sums,
                      n_carry);
    end

endmodule
