// Testbench for exercise P5.
//
// Runs the generic design (snail_fsm.sv) and the chip-level design
// (snail_fsm_chips.sv) side by side and compares both with a reference
// model that does not use states at all: it remembers the last two samples
// of a since reset.  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 feeds a sequence that holds every
// pair of bits, then pseudo-random bits, resets in the middle, 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       a = 1'b0;

    wire  [1:0] state, state_chips;

    snail_fsm i_generic
    (
        .clk   ( clk   ),
        .rst   ( rst   ),
        .a     ( a     ),
        .state ( state )
    );

    snail_fsm_chips i_chips
    (
        .clk   ( clk         ),
        .rst   ( rst         ),
        .a     ( a           ),
        .state ( state_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 number of samples since reset and the last two

    int   n_samples;
    logic last, before_last;

    always @ (posedge clk or posedge rst)
        if (rst)
            n_samples <= 0;
        else
        begin
            n_samples   <= n_samples + 1;
            before_last <= last;
            last        <= a;
        end

    // S0: the last sample was 0.  S1 = Y: the last two were 0, then 1.

    wire [1:0] state_expected = { n_samples >= 2 && before_last == 1'b0 && last == 1'b1,
                                  n_samples >= 1 && last == 1'b0 };

    wire ok_generic = state       === state_expected;
    wire ok_chips   = state_chips === state_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;
    int n_found  = 0;  // Cycles with y = 1

    logic [2:0] states_seen = '0;  // S0, S1, S2

    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);
            n_found     <= n_found + (state_expected [1] ? 1 : 0);

            states_seen <= states_seen | (state_expected == 2'b00 ? 3'b001 :
                                          state_expected == 2'b01 ? 3'b010 :
                                          state_expected == 2'b10 ? 3'b100 : 3'b000);

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

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both state registers must be 0.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ state, state_chips } !== 4'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 bit of the sequence per clock edge, as when
    // the button is held or released through one tick of the clock module

    // 1 1 0 0 1 0 1 1 1 0 1 0 0 0 1 1: every pair of bits, 0 1 found four times

    localparam logic [15:0] SEQUENCE = 16'b1100_1011_1010_0011;

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

    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  S1S0  Y  generic  chips");

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

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

        for (int i = 15; i >= 0; i --)
        begin
            a <= SEQUENCE [i];
            @ (posedge clk);
        end

        // Reset in the middle, right after a 0, so that the 0 is forgotten

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

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

        for (int i = 0; i < 60; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;
            a <= seed [31];
            @ (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 && states_seen == 3'b111 && n_found >= 4 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, states seen %b, 0 1 found %0d times, %0d resets",
                      n_errors, n_checks, states_seen, n_found, n_async);
    end

endmodule
