// Testbench for exercise BB1.
//
// Runs the generic design (multifunction_gate.sv) and the chip-level design
// (multifunction_gate_chips.sv) side by side and compares both with
// the function table of the 4048, written with comparisons.  Works with Icarus Verilog, Verilator (--binary)
// and Questa.
//
// The circuit has no clock, but like the testbenches of Basics-Graphics-Music
// this one drives and checks signals only at rising edges of its own clock:
// it changes the inputs after one edge and checks the outputs at the next.
// It tries all 2048 input combinations twice: counting up, and then in
// Gray code order, where one input changes at a time, as when a student
// presses or releases one button.

// 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       a;
    logic       b;
    logic       c;
    logic       d;
    logic [3:0] rest;
    logic [2:0] k;

    wire  j, j_chips;

    multifunction_gate i_generic
    (
        .a    ( a    ),
        .b    ( b    ),
        .c    ( c    ),
        .d    ( d    ),
        .rest ( rest ),
        .k    ( k    ),
        .j    ( j    )
    );

    multifunction_gate_chips i_chips
    (
        .a    ( a       ),
        .b    ( b       ),
        .c    ( c       ),
        .d    ( d       ),
        .rest ( rest    ),
        .k    ( k       ),
        .j    ( j_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the function table of the 4048, written with comparisons.
    // Bits, from the left: j.

    function automatic logic [0:0] expected
    (
        input logic       in_a,
        input logic       in_b,
        input logic       in_c,
        input logic       in_d,
        input logic [3:0] in_rest,
        input logic [2:0] in_k
    );
        // The two groups of four inputs, compared with all zeros and all ones

        logic [3:0] g1, g2;
        logic       y;

        g1 = { in_a, in_b, in_c, in_d };
        g2 = in_rest;

        case ({ in_k [0], in_k [1], in_k [2] })            // Ka Kb Kc, as in the datasheet
        3'b000:  y =    g1 == 4'h0 && g2 == 4'h0;          // NOR
        3'b001:  y = ! (g1 == 4'h0 && g2 == 4'h0);         // OR
        3'b010:  y =    g1 != 4'h0 && g2 != 4'h0;          // OR/AND
        3'b011:  y = ! (g1 != 4'h0 && g2 != 4'h0);         // OR/NAND
        3'b100:  y =    g1 == 4'hf && g2 == 4'hf;          // AND
        3'b101:  y = ! (g1 == 4'hf && g2 == 4'hf);         // NAND
        3'b110:  y = ! (g1 == 4'hf || g2 == 4'hf);         // AND/NOR
        3'b111:  y =    g1 == 4'hf || g2 == 4'hf;          // AND/OR
        default: y = 1'bx;
        endcase

        return y;
    endfunction

    wire [0:0] out       = { j };
    wire [0:0] out_chips = { j_chips };
    wire [0:0] out_model = expected (a, b, c, d, rest, k);

    //------------------------------------------------------------------------
    // Checking at every rising clock edge: the inputs still hold the values the
    // stimulus set at the previous edge, and the outputs have settled.

    // Initial values are fine in a testbench
    // verilator lint_off PROCASSINIT

    logic checking = 1'b0;  // Set by the stimulus after the first inputs
    logic done     = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    logic [2047:0] rows_seen = '0;  // Which input combinations were checked

    always @ (posedge clk)
        if (checking & ~ done)
        begin
            cycle     <= cycle + 1;
            n_checks  <= n_checks + 2;
            n_errors  <= n_errors + (out === out_model ? 0 : 1) + (out_chips === out_model ? 0 : 1);
            rows_seen <= rows_seen | 2048'b1 << { a, b, c, d, rest, k };

            // Print the first pass with E-H at 1, and every error

            if (rest == 4'hf & cycle < 2048 | out !== out_model | out_chips !== out_model)
                $display ("%5d  %b  %b  %b  %b  %b %b     %b  %s  %s",
                    cycle + 1, a, b, c, d, rest, k, j,
                    out       === out_model ? "ok     " : "WRONG  ",
                    out_chips === out_model ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs: all combinations, counting up from the AND function with
    // E-H at 1 as on the breadboard, then in Gray code order

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

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

        $display ("cycle  A  B  C  D  E-H  Kc..Ka  J  generic  chips");

        checking <= '1;

        for (int i = 0; i < 2048; i ++)
        begin
            { k, rest, a, b, c, d } <= 11' (i) ^ 11'h1f0;
            @ (posedge clk);
        end

        for (int i = 0; i < 2048; i ++)
        begin
            { k, rest, a, b, c, d } <= 11' (i ^ (i >> 1)) ^ 11'h1f0;
            @ (posedge clk);
        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 && & rows_seen)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, %0d of %0d input combinations seen",
                n_errors, n_checks, $countones (rows_seen), 2048);
    end

endmodule
