library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity test_cpu is end entity;
architecture bench of test_cpu is
    signal clk, run : std_logic := '0';
    signal reset_n : std_logic := '1';
    signal word, view : unsigned(15 downto 0) := (others => '0');
    signal probe : unsigned(2 downto 0) := (others => '0');
    signal done, busy : std_logic;
begin
    dut : entity work.course_cpu port map(clk, reset_n, run, word, probe, view, done, busy);
    process
        type bank is array (0 to 7) of integer;
        variable model : bank := (others => 0);
        variable dst, src, op, value, instruction, operand : integer;
        variable immediate : boolean;
        procedure tick is
        begin
            wait for 2 ns; clk <= '1'; wait for 2 ns; clk <= '0'; wait for 1 ns;
        end procedure;
        procedure check(d, b : std_logic) is
        begin
            assert done = d and busy = b and to_integer(view) = model(to_integer(probe))
                report "FAIL instruction " & integer'image(instruction) & " r" &
                       integer'image(to_integer(probe)) & " observed " & integer'image(to_integer(view))
                severity failure;
        end procedure;
    begin
        wait for 1 ns; reset_n <= '0'; wait for 1 ns; reset_n <= '1';
        for i in 0 to 511 loop
            dst := (i/4) mod 8; src := (i/32+3) mod 8; op := i mod 4;
            immediate := (i/32) mod 2 = 1 or op = 1; value := (i*89+257) mod 512;
            instruction := op*8192+dst*512;
            if immediate then
                instruction := instruction+4096+value; operand := value;
                if value>=256 then operand:=value-512; end if;
            else instruction := instruction+src; operand:=model(src);
            end if;
            probe <= to_unsigned(dst,3); word <= to_unsigned(instruction,16); run <= '0';
            tick; check('0','0');
            run <= '1'; tick; run <= '0'; word <= not to_unsigned(instruction,16); wait for 1 ns;
            if op>=2 then check('0','1'); tick; check('0','1'); tick; end if;
            check('1','1');
            case op is
                when 0 => model(dst) := operand mod 65536;
                when 1 => model(dst) := (value mod 256)*256;
                when 2 => model(dst) := (model(dst)+operand) mod 65536;
                when others => model(dst) := (model(dst)-operand) mod 65536;
            end case;
            tick; check('0','0');
            for index in 0 to 7 loop
                probe <= to_unsigned(index,3); wait for 1 ns; check('0','0');
            end loop;
        end loop;
        report "PASS 512 instructions, eight register readbacks per instruction";
        wait;
    end process;
end architecture;
