// Testbench for exercise BB6.
//
// Runs the generic design (priority_encoder.sv) and the chip-level design
// (priority_encoder_chips.sv) side by side and compares both with
// the number of the highest input at 1 and the digit that the 4511 draws for it.  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 256 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 [7:0] d;

    wire  [2:0] q,       q_chips;
    wire        gs,      gs_chips;
    wire        eo,      eo_chips;
    wire  [6:0] abcdefg, abcdefg_chips;

    priority_encoder i_generic
    (
        .d       ( d       ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    priority_encoder_chips i_chips
    (
        .d       ( d             ),
        .q       ( q_chips       ),
        .gs      ( gs_chips      ),
        .eo      ( eo_chips      ),
        .abcdefg ( abcdefg_chips )
    );

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

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the number of the highest input at 1 and the digit that the 4511 draws for it.
    // Bits, from the left: q, gs, eo, abcdefg.

    function automatic logic [11:0] expected (input logic [7:0] in_d);
        logic [2:0] n;
        logic [6:0] segments;

        n = '0;

        for (int i = 0; i < 8; i ++)
            if (in_d [i])
                n = 3' (i);

        // Segments a ... g of the digits 0-7 as the 4511 draws them; a is the top
        // segment.  Its 6 has no top segment.

        case (n)
        3'd0:    segments = 7'b111_1110;
        3'd1:    segments = 7'b011_0000;
        3'd2:    segments = 7'b110_1101;
        3'd3:    segments = 7'b111_1001;
        3'd4:    segments = 7'b011_0011;
        3'd5:    segments = 7'b101_1011;
        3'd6:    segments = 7'b001_1111;
        default: segments = 7'b111_0000;
        endcase

        return { n, in_d != 8'b0, in_d == 8'b0, segments };
    endfunction

    wire [11:0] out       = { q, gs, eo, abcdefg };
    wire [11:0] out_chips = { q_chips, gs_chips, eo_chips, abcdefg_chips };
    wire [11:0] out_model = expected (d);

    //------------------------------------------------------------------------
    // 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 [255: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 | 256'b1 << { d };

            $display ("%5d  %b %b %b   %b   %b  %s  %s",
                cycle + 1, d, q, gs, eo, abcdefg,
                out       === out_model ? "ok     " : "WRONG  ",
                out_chips === out_model ? "ok   "   : "WRONG");
        end

    //------------------------------------------------------------------------
    // Driving the inputs: all combinations, counting up, 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  D7..D0  Q  GS  EO  abcdefg  generic  chips");

        checking <= '1;

        for (int i = 0; i < 256; i ++)
        begin
            { d } <= 8' (i);
            @ (posedge clk);
        end

        for (int i = 0; i < 256; i ++)
        begin
            { d } <= 8' (i ^ (i >> 1));
            @ (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), 256);
    end

endmodule
