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

entity test_stack is end;
architecture bench of test_stack is
    type digits_t is array(0 to 5) of std_logic_vector(6 downto 0);
    type integers_t is array(0 to 15) of natural;
    constant glyphs : integers_t := (63,6,91,79,102,109,125,7,127,111,119,124,57,94,121,113);
    constant seed : unsigned(15 downto 0) := x"9010";
    signal clk : std_logic := '0';
    signal key : std_logic_vector(3 downto 0) := "1110";
    signal switches, lamps : std_logic_vector(9 downto 0) := (others=>'0');
    signal digits : digits_t;
begin
    clk <= not clk after 1 ns;
    dut : entity work.stack_cpu port map(clk,key,switches,lamps,
        digits(0),digits(1),digits(2),digits(3),digits(4),digits(5));
    process
        variable wanted : digits_t;
        variable result : unsigned(15 downto 0);
        procedure advance(n : positive) is
        begin for j in 1 to n loop wait until falling_edge(clk); end loop; end procedure;
    begin
        advance(5); key<="1111";
        for op in 0 to 3 loop
            for n in 0 to 15 loop
                switches<=std_logic_vector(to_unsigned(512+32*op+n,10));
                case op is
                    when 0 => result:=shift_left(seed,n);
                    when 1 => result:=shift_right(seed,n);
                    when 2 => result:=unsigned(shift_right(signed(seed),n));
                    when others => result:=rotate_right(seed,n);
                end case;
                wanted:=(others=>(others=>'1'));
                for i in 0 to 3 loop
                    wanted(i):=not std_logic_vector(to_unsigned(glyphs(to_integer(result(4*i+3 downto 4*i))),7));
                end loop;
                advance(2400);
                assert digits=wanted and unsigned(lamps)=32*op+n
                    report "FAIL mode " & integer'image(op) & " amount " & integer'image(n) &
                           " expected " & to_hstring(result) & " pins " & to_hstring(digits(3)) & "/" &
                           to_hstring(digits(2)) & "/" & to_hstring(digits(1)) & "/" & to_hstring(digits(0)) &
                           " LEDs " & to_hstring(lamps) severity failure;
            end loop;
        end loop;
        report "PASS all 64 operation/amount pairs, nested calls, LIFO stack and hexadecimal output"; finish;
    end process;
end architecture;
