-module(egg_tester).

-compile([export_all]).
-include("erl_gen.hrl").
-include("egg.hrl").

-define(GENMOD, erl_seq_gen).

%% =============================================================================
%% Testing

getvalue(Gen) -> ?LET(M, Gen, ?getattr(value, M)).

compiles(T) ->
    S = [erl_syntax:revert(T2) ||
	    T2 <- ?S:form_list_elements(eval(T))],
    C = compile:forms(S, [strong_validation, return_errors, nowarn_unused_vars]),
    element(1, C) == ok.
	
prop(Gen) ->
    G = getvalue(Gen),
    ?FORALL(
       Ts, G,
       begin
           io:format("----------------------------------------"
                     "--------------------------------------~n"),
           io:format("~nUsed memory after generation: ~pMB~n",
                     [round(erlang:memory(total)/1024/1024)]),
	   
	   check_trees(Ts),
	   lists:all(fun compiles/1, Ts)
       end).

prop2(Gen) -> ?FORALL(T, getvalue(Gen), begin io:format("~p~n", [eval(T)]), true end).

test(I) -> ?QuickCheck:quickcheck(?QuickCheck:numtests(I, prop(?GENMOD:mods(2)))).

print_trees(Ts) ->
%    [io:format("~p~n", [T]) || T <- Ts],
    [io:format("~s~n----------~n", [erl_prettypr:format(eval(T))]) || T <- Ts].

check_trees(Ts) ->
    [compile:forms(
       [erl_syntax:revert(T2) || T2 <- ?S:form_list_elements(eval(T))],
       [strong_validation, report, nowarn_unused_vars])
     || T <- Ts].
	
print_check_trees(Ts) ->
    print_trees(Ts),
%    check_trees(Ts),
    true.

z(N) ->
    P = ?FORALL(Ts, getvalue(?GENMOD:mods(N)), print_check_trees(Ts)),
    ?QuickCheck:quickcheck(?QuickCheck:numtests(1, P)).
a() ->
    P = ?FORALL(Ts, getvalue(?GENMOD:mods(2)), print_check_trees(Ts)),
    ?QuickCheck:quickcheck(?QuickCheck:numtests(1, P)).

x() ->
    P = ?FORALL(Ts, getvalue(?GENMOD:files(2, 2)), print_check_trees(Ts)),
    ?QuickCheck:quickcheck(?QuickCheck:numtests(1, P)).

pick_and_use(G, F) ->
    ?QuickCheck:quickcheck(?QuickCheck:numtests(1, ?FORALL(X, G, begin F(X), true end))).
a2() ->
    pick_and_use(noshrink(?GENMOD:mods(2)), fun a3/1).
a3(X) ->
    Ts = ?getattr(value, X),
    print_check_trees(Ts),
    true.

%a_old() ->
%    Ts = ?getattr(value, pick(erl_gen:mods(2))),
%    print_check_trees(Ts).

a_proper() ->
    Ts = ?getattr(value, element(2, proper_gen:pick(?GENMOD:mods(2)))),
    print_check_trees(Ts).
