`timescale 1ns / 1ps

module tb_basic_dff;

    localparam period         = 20;
    localparam timeout_cycles = 3000;

    logic clk = 1'b0;

    always # (period / 2) clk = ~ clk;

    logic rst = '0;
    logic d = '0;
    logic q_g;
    logic q_c;
    logic qn_g;
    logic qn_c;
    int checks = 0;

    basic_dff dut_g
    (
        .clk          (clk),
        .rst          (rst),
        .d            (d),
        .q            (q_g),
        .qn           (qn_g)
    );

    basic_dff_chips dut_c
    (
        .clk          (clk),
        .rst          (rst),
        .d            (d),
        .q            (q_c),
        .qn           (qn_c)
    );

    task check (input logic expected_q, input logic expected_qn);
        if (q_g !== expected_q || q_c !== expected_q)
            $fatal (1, "q: generic=%h chips=%h expected=%h", q_g, q_c, expected_q);
        if (qn_g !== expected_qn || qn_c !== expected_qn)
            $fatal (1, "qn: generic=%h chips=%h expected=%h", qn_g, qn_c, expected_qn);
        checks = checks + 1;
    endtask

    initial
    begin
        $dumpfile ("trace.vcd");
        $dumpvars (0, tb_basic_dff);

        @ (posedge clk);
        # 1;
        rst = 1'b1;
        # 1;  // Verify asynchronous clear before the next edge.
        check (0, 1);
        rst = 1'b0;

        for (int i = 0; i < 16; i ++)
        begin
            d = 1' ((i ^ (i >> 1)) & 1);
            @ (posedge clk);
            # 1;  // NBA and complement settling.
            check (d, ~ d);
            d = ~ d;
            # 1;  // D changing away from the edge must not change Q.
            check (~ d, d);
            rst = 1'b1;
            # 1;
            check (0, 1);
            @ (posedge clk);
            # 1;
            check (0, 1);
            rst = 1'b0;
        end

        $display ("PASS basic_dff: %0d independent checks", checks);
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout in clock cycles");
    end

endmodule
