:- module(type_tests, [write_promotion/0]).

:- use_module(library(array/type)).
:- use_module(library(clpBNR)).
:- use_module(library(apply)).
:- use_module(library(lists)).
:- use_module(library(readutil)).

% The types of the tests
% ======================

% operand(?Name, ?Kind): every kind of operand: a value held in each format, strong, and
% the weak ones, two int literals, a negative one, a float literal and an index of 7 bits.
operand(F, K) :- formats(Fs), member(F, Fs), format_kind(F, K).
operand(int(1), 1).
operand(int(300), 1).
operand(int(-5), 1).
operand(int(-1), 1).
operand(float(0.5), 2).
operand(index(7), 1).

% typed(+Name, -Type): the type of an operand.
typed(int(N), T) => literal_type(N, T).
typed(float(X), T) => literal_type(X, T).
typed(index(B), T) => index_type(T, 0, B, M), M is max(B - 1, 0).
typed(F, T) => format_type(F, T).

strong(F) :- atom(F).

% arith(+Ks, -K): the kind of an arithmetic on values of the kinds Ks, an int at the least.
arith(Ks, K) :- foldl([A, B, C]>>(C is max(A, B)), Ks, 1, K).

% joined(+Names, +Kind, -Type): the join of the operands Names as a value of Kind.
joined(Names, Kind, Type) :-
   maplist(typed, Names, Ts),
   join(Ts, Kind, Type).

% posted(+Names, +Kind, -Type): the same join posted on open types and an open kind, bound
% after: what the constraints give where joined/3 computes.
posted(Names, Kind, Type) :-
   maplist([_, T]>>new_type(T), Names, Ts),
   K::integer(0, 2),
   join(Ts, K, Type),
   maplist(typed, Names, Ts),
   K = Kind,
   least(Type).

% host(-Formats): every format; small_device(-Formats): a device of 32 bits without half floats.
host(Formats) :- formats(Formats).
small_device([bool, int8, uint8, int16, uint16, int32, uint32, bfloat16, float32]).

device(host, Fs) :- host(Fs).
device(small, Fs) :- small_device(Fs).

% round(+Type, +Kind, +Formats, -Format): the format of a ground Type, none when it has none.
round(Type, Kind, Formats, Format), rounded(Type, Kind, Formats, F) => Format = F.
round(_, _, _, Format) => Format = none.

% holds(+Format, +Need): the format has what Need asks.
holds(_, bool) => true.
holds(F, int(S, B)) => format_type(F, type(S1, B1, _, _, _, _, _)), S1 >= S, B1 >= B.
holds(F, float(E, M)) => format_type(F, type(_, _, E1, M1, _, _, _)), E1 >= E, M1 >= M.

% failing(+Template, :Generator, :Check, -Cases): the cases of Generator whose Check fails.
:- meta_predicate failing(?, 0, 0, -).
failing(Template, Generator, Check, Cases) :-
   findall(Template, ( Generator, \+ Check ), Cases).

pair(A, B, Ka, Kb) :- operand(A, Ka), operand(B, Kb).

% kinds(+Ks, -K): the kinds a value of operands of the kinds Ks may have: that of an
% arithmetic, and float, a division.
kinds(Ks, K) :- arith(Ks, K0), ( K = K0 ; K0 < 2, K = 2 ).

% The promotion table
% ===================

% promotion(-Lines): the table of the joins of two formats, a line per pair and per device:
% the format of their arithmetic and that of their division.
promotion(Lines) :-
   findall(Line,
           ( device(D, Fs), operand(A, Ka), strong(A), operand(B, Kb), strong(B),
             arith([Ka, Kb], K),
             joined([A, B], K, T), round(T, K, Fs, F),
             joined([A, B], 2, T2), round(T2, 2, Fs, F2),
             format(string(Line), "~w ~w ~w ~w ~w", [D, A, B, F, F2]) ),
           Lines).

promotion_file(File) :-
   module_property(type_tests, file(This)),
   file_directory_name(This, Dir),
   directory_file_path(Dir, 'promotion.txt', File).

% write_promotion: the table written to test/promotion.txt, to review as a diff when the
% model changes: swipl -g type_tests:write_promotion -t halt test/test_array.pl
write_promotion :-
   promotion(Lines),
   promotion_file(File),
   setup_call_cleanup(open(File, write, S),
                      ( format(S, "# device a b arithmetic division~n", []),
                        forall(member(L, Lines), format(S, "~s~n", [L])) ),
                      close(S)).

:- begin_tests(type).

% The table
% ---------

test(int8_uint8, [timeout(10), true(F == int16)]) :-
   joined([int8, uint8], 1, T), host(Fs), round(T, 1, Fs, F).
test(jax_example_is_associative, [timeout(10), true(F1-F2 == float16-float16)]) :-
   % NumPy gives float32 for (i8 v u8) v f16 and float16 for i8 v (u8 v f16)
   host(Fs),
   joined([int8, uint8], 0, T0), format_type(float16, H), join([T0, H], 2, T1), round(T1, 2, Fs, F1),
   joined([uint8, float16], 0, T2), format_type(int8, I), join([I, T2], 2, T3), round(T3, 2, Fs, F2).
test(int_into_float_needs_its_mantissa, [timeout(10), true(Fs1 == [float16, float32, float64, none])]) :-
   host(Fs),
   maplist({Fs}/[I-F, R]>>( joined([I, F], 2, T), round(T, 2, Fs, R) ),
           [uint8-float16, int16-float16, int32-float32, int64-float32], Fs1).
test(uint64_int64_has_no_format, [timeout(10), true(F == none)]) :-
   joined([uint64, int64], 1, T), host(Fs), round(T, 1, Fs, F).
test(float16_bfloat16_round_at_the_end, [timeout(10), true(F-F1 == float32-bfloat16)]) :-
   % the join of the two needs both, a float32; a need of bfloat16's exponent and less
   % mantissa is a bfloat16, which rounding the first operand to float16 first would lose
   host(Fs),
   joined([float16, bfloat16], 2, T), round(T, 2, Fs, F),
   format_type(bfloat16, B), join([type(1, 64, 5, 7, 1, 0, 1), B], 2, T1), round(T1, 2, Fs, F1).

% Weak types
% ----------

test(literal_keeps_the_strong_type, [timeout(10), true(Fs1 == [uint8, int16, float16, float16])]) :-
   host(Fs),
   maplist({Fs}/[Ns-K, R]>>( joined(Ns, K, T), round(T, K, Fs, R) ),
           [[uint8, int(1)]-1, [uint8, int(300)]-1, [float16, float(0.5)]-2, [float16, index(7)]-2], Fs1).
test(negative_literal_needs_a_sign, [timeout(10), true(F == int16)]) :-
   joined([uint8, int(-5)], 1, T), host(Fs), round(T, 1, Fs, F).
test(negative_literal_bits, [timeout(10), true(Ts == [type(1, 0, 0, 0, 0, 0, 0), type(1, 7, 0, 0, 0, 0, 0), type(1, 8, 0, 7, 0, 0, 0)])]) :-
   maplist(literal_type, [-1, -128, -129], Ts).
test(weak_stays_weak, [timeout(10), true(W == 0)]) :-
   joined([int(1), float(0.5), index(7)], 2, type(_, _, _, _, W, _, _)).
test(weak_takes_the_default, [timeout(10), true(Fs1 == [int32, float32, float32, int64])]) :-
   host(Fs),
   maplist({Fs}/[Ns-K, R]>>( joined(Ns, K, T), round(T, K, Fs, R) ),
           [[int(1), int(300)]-1, [float(0.5)]-2, [index(7), int(1)]-2, [int(5000000000)]-1], Fs1).
test(literal_exact_bits, [timeout(10), true(Ms == [0, 0, 6, 11])]) :-
   maplist([N, M]>>literal_type(N, type(_, _, _, M, _, _, _)), [1, 2048, 1000, 100000], Ms).
test(index_bits_bound_late, [timeout(10), true(F == float32)]) :-
   index_type(T, S, B, M), format_type(float16, H), join([H, T], 2, J),
   new_type(R), written(J, R),
   S = 0, B = 20, M = 19, least(R), host(Fs), round(R, 2, Fs, F).

% Floors
% ------

test(float_of_ints_is_a_float32, [timeout(10), true(Fs1 == [float32, float32, float32, float64])]) :-
   host(Fs),
   maplist({Fs}/[Ns, R]>>( joined(Ns, 2, T), round(T, 2, Fs, R) ),
           [[int8, int8], [bool, float(0.5)], [uint8, index(7)], [int32, int(2)]], Fs1).
test(int_of_bools_is_an_int32, [timeout(10), true(F == int32)]) :-
   joined([bool, bool], 1, T), host(Fs), round(T, 1, Fs, F).
test(strong_float_no_floor, [timeout(10), true(F == float16)]) :-
   joined([float16, int8], 2, T), host(Fs), round(T, 2, Fs, F).
test(floor_breaks_grouping, [timeout(10), true(F1-F2 == float32-float16)]) :-
   % (i8 / i8) * f16 is a float32, i8 / (i8 * f16) a float16: a floor is of an operation
   host(Fs), format_type(float16, H), format_type(int8, I),
   joined([int8, int8], 2, T0), join([T0, H], 2, T1), round(T1, 2, Fs, F1),
   joined([int8, float16], 2, T2), join([I, T2], 2, T3), round(T3, 2, Fs, F2).
test(floor_kind_bound_late, [timeout(10), true(M-M1 == 23-6)]) :-
   K::integer(0, 2), format_type(int8, I), join([I, I], K, T), new_type(R), written(T, R),
   K1::integer(0, 2), join([I, I], K1, T1), new_type(R1), written(T1, R1),
   K = 2, K1 = 1, least(R), least(R1),
   R = type(_, _, _, M, _, _, _), R1 = type(_, _, _, M1, _, _, _).
test(floor_does_not_push_back, [timeout(10), true(D == integer(0, 2))]) :-
   % a bound on the result leaves the kind open
   K::integer(0, 2), format_type(int8, I), join([I, I], K, T),
   format_type(float16, H), written(T, H),
   domain(K, D).
test(bound_then_float_fails, [timeout(10), fail]) :-
   K::integer(0, 2), format_type(int8, I), join([I, I], K, T),
   format_type(float16, H), written(T, H),
   K = 2.

% Writes
% ------

test(write_cycle_least, [timeout(10), true(F == int8)]) :-
   % S := 0, S := S + X with X an int8
   new_type(S), literal_type(0, Z), written(Z, S),
   new_type(X), join([S, X], 1, J), written(J, S),
   format_type(int8, X), least(S), host(Fs), round(S, 1, Fs, F).
test(counter_of_literals_is_default, [timeout(10), true(F == int32)]) :-
   new_type(S), literal_type(0, Z), written(Z, S),
   literal_type(1, One), join([S, One], 1, J), written(J, S),
   least(S), host(Fs), round(S, 1, Fs, F).
test(two_writes, [timeout(10), true(F == int16)]) :-
   new_type(S), new_type(A), new_type(B), written(A, S), written(B, S),
   format_type(int8, A), format_type(uint8, B), least(S), host(Fs), round(S, 1, Fs, F).
test(write_does_not_narrow_value, [timeout(10), true(D == integer(0, 64))]) :-
   new_type(V), format_type(uint8, U), written(V, U),
   V = type(_, B, _, _, _, _, _), domain(B, D).
test(declared_narrower_passes, [timeout(10)]) :-
   format_type(int8, V), format_type(float32, F), written(V, F).
test(declared_wider_fails, [timeout(10), fail]) :-
   format_type(float32, V), format_type(float16, F), written(V, F).
test(declared_wider_fails_late, [timeout(10), fail]) :-
   new_type(V), format_type(float16, F), written(V, F), format_type(float32, V).
test(int32_into_float32_fails, [timeout(10), fail]) :-
   format_type(int32, V), format_type(float32, F), written(V, F).
test(literal_into_uint8, [timeout(10), true(Rs == [true, false])]) :-
   format_type(uint8, U),
   maplist({U}/[N, R]>>( literal_type(N, L), ( written(L, U) -> R = true ; R = false ) ), [255, 256], Rs).
test(like_one_way, [timeout(10), true(D-B1 == integer(0, 64)-8)]) :-
   new_type(T), like(T, C),
   format_type(float16, H), written(C, H),
   T = type(_, B, _, _, _, _, _), domain(B, D),
   new_type(T1), like(T1, C1), format_type(uint8, T1), C1 = type(_, B1, _, _, _, _, _).

% Inputs
% ------

test(input_strong_int_by_kind, [timeout(10), true(I-I1 == 1-0)]) :-
   K::integer(0, 2), input_type(type(_, _, _, _, _, I, _), K), K = 1,
   input_type(type(_, _, _, _, _, I1, _), 2).

% Rounding and compute
% --------------------

test(rounding_ties, [timeout(10), true(Fs1 == [int8, uint8, float16, bfloat16])]) :-
   host(Fs),
   maplist({Fs}/[T-K, R]>>round(T, K, Fs, R),
           [type(0, 7, 0, 6, 1, 1, 0)-1, type(0, 8, 0, 7, 1, 1, 0)-1, type(1, 64, 5, 7, 1, 0, 1)-2, type(1, 64, 8, 7, 1, 0, 1)-2], Fs1).
test(rounding_on_a_small_device, [timeout(10), true(Fs1 == [float32, none, none])]) :-
   small_device(Fs),
   maplist({Fs}/[A-K, R]>>( joined([A], K, T), round(T, K, Fs, R) ), [float16-2, float64-2, int64-1], Fs1).
test(bool_is_bool, [timeout(10), true(F == bool)]) :-
   joined([bool, bool], 0, T), host(Fs), round(T, 0, Fs, F).
test(compute_formats, [timeout(10), true(Cs == [int32, int32, int32, uint32, int64, float32, float32, float64])]) :-
   maplist([F, C]>>compute(F, [int32, uint32, int64, uint64, float32, float64], C),
           [bool, uint8, int32, uint32, int64, float16, bfloat16, float64], Cs).
test(compute_without_double, [timeout(10), fail]) :-
   compute(float64, [int32, float32], _).
test(bits_formats, [timeout(10), true(Fs == [int16, int32, int64])]) :-
   maplist(bits_format, [float16, float32, float64], Fs).
test(format_ranges, [timeout(10), true(Rs == [0-1, (-128)-127, 0-255, (-2147483648)-2147483647])]) :-
   maplist([F, Lo-Hi]>>format_range(F, Lo, Hi), [bool, int8, uint8, int32], Rs).

% Copies
% ------

test(copy_join, [timeout(10), true(F == float32)]) :-
   new_type(A), new_type(B), K::integer(0, 2), join([A, B], K, T), new_type(R), written(T, R),
   copy_term(c(A, B, K, R), c(A1, B1, K1, R1), Gs), maplist(call, Gs),
   format_type(int8, A1), format_type(int8, B1), K1 = 2, least(R1),
   host(Fs), round(R1, 2, Fs, F).
test(copy_cycle, [timeout(10), true(F == int8)]) :-
   new_type(S), literal_type(0, Z), written(Z, S),
   new_type(X), join([S, X], 1, J), written(J, S),
   copy_term(S-X, S1-X1, Gs), maplist(call, Gs),
   format_type(int8, X1), least(S1), host(Fs), round(S1, 1, Fs, F).
test(copy_declared_fails, [timeout(10), fail]) :-
   new_type(V), new_type(D), written(V, D),
   copy_term(V-D, V1-D1, Gs), maplist(call, Gs),
   format_type(float16, D1), format_type(float32, V1).

% Every pair
% ----------

test(pairs_posted_as_computed, [timeout(60), true(Cases == [])]) :-
   failing(A-B-K,
           ( pair(A, B, Ka, Kb), kinds([Ka, Kb], K) ),
           ( joined([A, B], K, T), posted([A, B], K, T1), T == T1 ),
           Cases).
test(pairs_commutative, [timeout(30), true(Cases == [])]) :-
   failing(A-B-K,
           ( pair(A, B, Ka, Kb), kinds([Ka, Kb], K) ),
           ( joined([A, B], K, T), joined([B, A], K, T1), T == T1 ),
           Cases).
test(pairs_idempotent, [timeout(30), true(Cases == [])]) :-
   failing(A-K,
           ( operand(A, Ka), kinds([Ka], K) ),
           ( joined([A, A], K, T), joined([A], K, T1), T == T1 ),
           Cases).
test(pairs_upper_bound, [timeout(30), true(Cases == [])]) :-
   failing(A-B-K,
           ( pair(A, B, Ka, Kb), kinds([Ka, Kb], K) ),
           ( joined([A, B], K, T), typed(A, Ta), typed(B, Tb), written(Ta, T), written(Tb, T) ),
           Cases).
test(pairs_rounding_least, [timeout(30), true(Cases == [])]) :-
   % the format holds what the join needs, and no smaller format of the device does
   failing(D-A-B-K,
           ( device(D, Fs), pair(A, B, Ka, Kb), kinds([Ka, Kb], K),
             joined([A, B], K, T), rounded(T, K, Fs, F) ),
           ( required(T, K, Need), holds(F, Need), format_bytes(F, Bytes),
             \+ ( member(F1, Fs), format_kind(F1, K), format_bytes(F1, B1), B1 < Bytes, holds(F1, Need) ) ),
           Cases).
test(pairs_strong_keeps_its_format, [timeout(30), true(Cases == [])]) :-
   % a strong operand of the kind of the result, next to a weak one that fits it, keeps its format
   host(Fs),
   failing(A-B,
           ( pair(A, B, K, Kb), strong(A), \+ strong(B), K >= max(1, Kb),
             typed(A, Ta), typed(B, Tb), written(Tb, Ta) ),
           ( joined([A, B], K, T), rounded(T, K, Fs, F), F == A ),
           Cases).
test(pairs_weak_stay_weak, [timeout(30), true(Cases == [])]) :-
   host(Fs),
   failing(A-B-K,
           ( pair(A, B, Ka, Kb), \+ strong(A), \+ strong(B), kinds([Ka, Kb], K) ),
           ( joined([A, B], K, T), T = type(_, _, _, _, 0, _, _),
             rounded(T, K, Fs, F), format_bytes(F, Bytes), Bytes >= 4 ),
           Cases).
test(pairs_uint64_signed_no_format, [timeout(30), true(Cases == [])]) :-
   host(Fs),
   failing(B,
           ( operand(B, 1), typed(B, type(1, _, _, _, _, _, _)) ),
           ( joined([uint64, B], 1, T), \+ rounded(T, 1, Fs, _) ),
           Cases).
test(pairs_float_holds_the_int, [timeout(30), true(Cases == [])]) :-
   % rule (c): the float of an int and a float has the mantissa of the int
   host(Fs),
   failing(A-B,
           ( pair(A, B, 1, 2), strong(A), strong(B), joined([A, B], 2, T), rounded(T, 2, Fs, F) ),
           ( format_type(A, type(_, Bits, _, _, _, _, _)), format_type(F, type(_, _, _, M, _, _, _)), M >= Bits - 1 ),
           Cases).
test(pairs_float_floor, [timeout(30), true(Cases == [])]) :-
   % a float of two operands, one strong, none a strong float, is a float32 at the least
   host(Fs),
   failing(A-B,
           ( pair(A, B, Ka, Kb), ( strong(A) ; strong(B) ), \+ ( strong(A), Ka =:= 2 ), \+ ( strong(B), Kb =:= 2 ),
             joined([A, B], 2, T), rounded(T, 2, Fs, _) ),
           ( joined([A, B], 2, T), rounded(T, 2, Fs, F), memberchk(F, [float32, float64]) ),
           Cases).

% Every triple
% ------------

test(triples_associative, [timeout(120), true(Cases == [])]) :-
   % the join alone, kind 0, in both groupings and flat, then one floor: the same type
   failing(A-B-C-K,
           ( operand(A, Ka), operand(B, Kb), operand(C, Kc), kinds([Ka, Kb, Kc], K) ),
           ( typed(A, Ta), typed(B, Tb), typed(C, Tc),
             join([Ta, Tb], 0, Tab), join([Tab, Tc], K, T1),
             join([Tb, Tc], 0, Tbc), join([Ta, Tbc], K, T2),
             join([Ta, Tb, Tc], K, T3),
             T1 == T2, T2 == T3 ),
           Cases).

% The golden table
% ----------------

test(promotion_table, [timeout(30), true(Lines == Golden)]) :-
   promotion(Lines),
   promotion_file(File),
   read_file_to_string(File, String, []),
   split_string(String, "\n", "", Lines0),
   exclude([L]>>( L == "" ; sub_string(L, 0, 1, _, "#") ), Lines0, Golden).

:- end_tests(type).
