// Testbench for exercise P6.
//
// Runs the generic design (code_lock.sv) and the chip-level design
// (code_lock_chips.sv) side by side and compares both with a reference
// model that keeps the samples of the button instead of states: the lock is
// open once the samples since reset contain 1, 0, 1.  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 enters wrong codes, the right one,
// codes with extra digits before it, resets in between, makes pseudo-random
// presses, 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       btn = 1'b0;

    wire        a,     a_chips;
    wire  [1:0] state, state_chips;
    wire        open,  open_chips;

    code_lock i_generic
    (
        .clk   ( clk   ),
        .rst   ( rst   ),
        .btn   ( btn   ),
        .a     ( a     ),
        .state ( state ),
        .open  ( open  )
    );

    code_lock_chips i_chips
    (
        .clk   ( clk         ),
        .rst   ( rst         ),
        .btn   ( btn         ),
        .a     ( a_chips     ),
        .state ( state_chips ),
        .open  ( open_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 sampled button, the samples of it since reset
    // (the newest in bit 0) and whether 1, 0, 1 has been among them

    logic       a_model;
    logic [1:0] last_two;
    int         n_samples;
    logic       opened;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            a_model   <= 1'b0;
            n_samples <= 0;
            opened    <= 1'b0;
        end
        else
        begin
            a_model   <= btn;
            last_two  <= { last_two [0], a_model };
            n_samples <= n_samples + 1;

            if (n_samples >= 2 && last_two == 2'b10 && a_model)
                opened <= 1'b1;
        end

    // The state: how much of 1, 0, 1 the last samples match

    wire [1:0] state_expected = opened                                 ? 2'd3
                              : n_samples >= 2 && last_two == 2'b10    ? 2'd2
                              : n_samples >= 1 && last_two [0] == 1'b1 ? 2'd1
                              :                                          2'd0;

    wire ok_generic = { a,       state,       open       } === { a_model, state_expected, opened };
    wire ok_chips   = { a_chips, state_chips, open_chips } === { a_model, state_expected, opened };

    //------------------------------------------------------------------------
    // 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_opened = 0;  // Times the lock opened

    logic opened_before = 1'b0;

    logic [3:0] states_seen = '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);
            states_seen <= states_seen | (4'b1 << state_expected);

            opened_before <= opened;

            if (opened & ~ opened_before)
                n_opened <= n_opened + 1;

            $display ("%5d  %b    %b    %b  %b%b      %b   %s  %s",
                cycle + 1, rst, btn, a, state [1], state [0], open,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, everything must be 0.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ a, state, open, a_chips, state_chips, open_chips } !== 8'b0)
        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 digit of the code per clock edge, as when the
    // button is held or released through one tick of the clock module

    // n digits of code, the first digit in bit n - 1

    task automatic enter (input logic [7:0] code, input int n);
        for (int i = n - 1; i >= 0; i --)
        begin
            btn <= code [i];
            @ (posedge clk);
        end

        btn <= 1'b0;
    endtask

    task automatic reset_lock;
        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;
    endtask

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

    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  BTN  A  S1S0  OPEN  generic  chips");

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

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

        enter (8'b0110,    4);  // 0, 1, 1, 0: no 1, 0, 1 in it
        reset_lock;
        enter (8'b101,     3);  // the code: opens
        enter (8'b0000,    4);  // and the lock stays open
        reset_lock;
        enter (8'b1101,    4);  // the code after an extra 1: opens
        reset_lock;
        enter (8'b10001,   5);  // no 1, 0, 1 in it
        reset_lock;
        enter (8'b1001,    4);  // no 1, 0, 1 in it
        enter (8'b0110100, 7);  // 1, 0, 1 in the middle: opens
        reset_lock;

        // Pseudo-random presses, the same in every simulator, with a reset
        // now and then

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

            if (seed [31:28] == 4'b0)
                reset_lock;
            else
            begin
                btn <= seed [27];
                @ (posedge clk);
            end
        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 && states_seen == 4'b1111 && n_opened >= 2 && n_async >= 4)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, states seen %b, opened %0d times, %0d resets",
                      n_errors, n_checks, states_seen, n_opened, n_async);
    end

endmodule
