src/HOL/Tools/Quickcheck/random_generators.ML
author wenzelm
Wed Mar 27 14:19:18 2013 +0100 (2013-03-27)
changeset 51551 88d1d19fb74f
parent 51143 0a2371e7ced3
child 51717 9e7d1c139569
permissions -rw-r--r--
tuned signature and module arrangement;
     1 (*  Title:      HOL/Tools/Quickcheck/random_generators.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Random generators for various types.
     5 *)
     6 
     7 signature RANDOM_GENERATORS =
     8 sig
     9   type seed = Random_Engine.seed
    10   val random_fun: typ -> typ -> ('a -> 'a -> bool) -> ('a -> term)
    11     -> (seed -> ('b * (unit -> term)) * seed) -> (seed -> seed * seed)
    12     -> seed -> (('a -> 'b) * (unit -> term)) * seed
    13   val compile_generator_expr:
    14     Proof.context -> (term * term list) list -> bool -> int list -> (bool * term list) option * Quickcheck.report option
    15   val put_counterexample: (unit -> Code_Numeral.natural -> bool -> Code_Numeral.natural -> seed -> (bool * term list) option * seed)
    16     -> Proof.context -> Proof.context
    17   val put_counterexample_report: (unit -> Code_Numeral.natural -> bool -> Code_Numeral.natural -> seed -> ((bool * term list) option * (bool list * bool)) * seed)
    18     -> Proof.context -> Proof.context
    19   val instantiate_random_datatype : Datatype_Aux.config -> Datatype_Aux.descr ->
    20     (string * sort) list -> string list -> string -> string list * string list -> typ list * typ list -> theory -> theory
    21   val setup: theory -> theory
    22 end;
    23 
    24 structure Random_Generators : RANDOM_GENERATORS =
    25 struct
    26 
    27 (** abstract syntax **)
    28 
    29 fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"})
    30 val size = @{term "i::natural"};
    31 val size_pred = @{term "(i::natural) - 1"};
    32 val size' = @{term "j::natural"};
    33 val seed = @{term "s::Random.seed"};
    34 
    35 val resultT =  @{typ "(bool * term list) option"};
    36 
    37 (** typ "'a => 'b" **)
    38 
    39 type seed = Random_Engine.seed;
    40 
    41 fun random_fun T1 T2 eq term_of random random_split seed =
    42   let
    43     val fun_upd = Const (@{const_name fun_upd},
    44       (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
    45     val ((_, t2), seed') = random seed;
    46     val (seed'', seed''') = random_split seed';
    47 
    48     val state = Unsynchronized.ref (seed'', [], fn () => Abs ("x", T1, t2 ()));
    49     fun random_fun' x =
    50       let
    51         val (seed, fun_map, f_t) = ! state;
    52       in case AList.lookup (uncurry eq) fun_map x
    53        of SOME y => y
    54         | NONE => let
    55               val t1 = term_of x;
    56               val ((y, t2), seed') = random seed;
    57               val fun_map' = (x, y) :: fun_map;
    58               val f_t' = fn () => fun_upd $ f_t () $ t1 $ t2 ();
    59               val _ = state := (seed', fun_map', f_t');
    60             in y end
    61       end;
    62     fun term_fun' () = #3 (! state) ();
    63   in ((random_fun', term_fun'), seed''') end;
    64 
    65   
    66 (** datatypes **)
    67 
    68 (* definitional scheme for random instances on datatypes *)
    69 
    70 local
    71 
    72 fun dest_ctyp_nth k cT = nth (Thm.dest_ctyp cT) k;
    73 val eq = Thm.cprop_of @{thm random_aux_rec} |> Thm.dest_arg |> Thm.dest_arg |> Thm.dest_arg;
    74 val lhs = eq |> Thm.dest_arg1;
    75 val pt_random_aux = lhs |> Thm.dest_fun;
    76 val pt_rhs = eq |> Thm.dest_arg |> Thm.dest_fun;
    77 val aT = pt_random_aux |> Thm.ctyp_of_term |> dest_ctyp_nth 1;
    78 
    79 val rew_thms = map mk_meta_eq [@{thm natural_zero_minus_one},
    80   @{thm Suc_natural_minus_one}, @{thm select_weight_cons_zero}, @{thm beyond_zero}];
    81 val rew_ts = map (Logic.dest_equals o Thm.prop_of) rew_thms;
    82 val rew_ss = HOL_ss addsimps rew_thms;
    83 
    84 in
    85 
    86 fun random_aux_primrec eq lthy =
    87   let
    88     val thy = Proof_Context.theory_of lthy;
    89     val ((t_random_aux as Free (random_aux, T)) $ (t_k as Free (v, _)), proto_t_rhs) =
    90       (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
    91     val Type (_, [_, iT]) = T;
    92     val icT = Thm.ctyp_of thy iT;
    93     val cert = Thm.cterm_of thy;
    94     val inst = Thm.instantiate_cterm ([(aT, icT)], []);
    95     fun subst_v t' = map_aterms (fn t as Free (w, _) => if v = w then t' else t | t => t);
    96     val t_rhs = lambda t_k proto_t_rhs;
    97     val eqs0 = [subst_v @{term "0::natural"} eq,
    98       subst_v (@{const Code_Numeral.Suc} $ t_k) eq];
    99     val eqs1 = map (Pattern.rewrite_term thy rew_ts []) eqs0;
   100     val ((_, (_, eqs2)), lthy') = Primrec.add_primrec_simple
   101       [((Binding.conceal (Binding.name random_aux), T), NoSyn)] eqs1 lthy;
   102     val cT_random_aux = inst pt_random_aux;
   103     val cT_rhs = inst pt_rhs;
   104     val rule = @{thm random_aux_rec}
   105       |> Drule.instantiate_normalize ([(aT, icT)],
   106            [(cT_random_aux, cert t_random_aux), (cT_rhs, cert t_rhs)]);
   107     val tac = ALLGOALS (rtac rule)
   108       THEN ALLGOALS (simp_tac rew_ss)
   109       THEN (ALLGOALS (Proof_Context.fact_tac eqs2))
   110     val simp = Goal.prove_sorry lthy' [v] [] eq (K tac);
   111   in (simp, lthy') end;
   112 
   113 end;
   114 
   115 fun random_aux_primrec_multi auxname [eq] lthy =
   116       lthy
   117       |> random_aux_primrec eq
   118       |>> (fn simp => [simp])
   119   | random_aux_primrec_multi auxname (eqs as _ :: _ :: _) lthy =
   120       let
   121         val thy = Proof_Context.theory_of lthy;
   122         val (lhss, rhss) = map_split (HOLogic.dest_eq o HOLogic.dest_Trueprop) eqs;
   123         val (vs, (arg as Free (v, _)) :: _) = map_split (fn (t1 $ t2) => (t1, t2)) lhss;
   124         val Ts = map fastype_of lhss;
   125         val tupleT = foldr1 HOLogic.mk_prodT Ts;
   126         val aux_lhs = Free ("mutual_" ^ auxname, fastype_of arg --> tupleT) $ arg;
   127         val aux_eq = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
   128           (aux_lhs, foldr1 HOLogic.mk_prod rhss);
   129         fun mk_proj t [T] = [t]
   130           | mk_proj t (Ts as T :: (Ts' as _ :: _)) =
   131               Const (@{const_name fst}, foldr1 HOLogic.mk_prodT Ts --> T) $ t
   132                 :: mk_proj (Const (@{const_name snd},
   133                   foldr1 HOLogic.mk_prodT Ts --> foldr1 HOLogic.mk_prodT Ts') $ t) Ts';
   134         val projs = mk_proj (aux_lhs) Ts;
   135         val proj_eqs = map2 (fn v => fn proj => (v, lambda arg proj)) vs projs;
   136         val proj_defs = map2 (fn Free (name, _) => fn (_, rhs) =>
   137           ((Binding.conceal (Binding.name name), NoSyn),
   138             (apfst Binding.conceal Attrib.empty_binding, rhs))) vs proj_eqs;
   139         val aux_eq' = Pattern.rewrite_term thy proj_eqs [] aux_eq;
   140         fun prove_eqs aux_simp proj_defs lthy = 
   141           let
   142             val proj_simps = map (snd o snd) proj_defs;
   143             fun tac { context = ctxt, prems = _ } =
   144               ALLGOALS (simp_tac (HOL_ss addsimps proj_simps))
   145               THEN ALLGOALS (EqSubst.eqsubst_tac ctxt [0] [aux_simp])
   146               THEN ALLGOALS (simp_tac (HOL_ss addsimps [@{thm fst_conv}, @{thm snd_conv}]));
   147           in (map (fn prop => Goal.prove_sorry lthy [v] [] prop tac) eqs, lthy) end;
   148       in
   149         lthy
   150         |> random_aux_primrec aux_eq'
   151         ||>> fold_map Local_Theory.define proj_defs
   152         |-> (fn (aux_simp, proj_defs) => prove_eqs aux_simp proj_defs)
   153       end;
   154 
   155 fun random_aux_specification prfx name eqs lthy =
   156   let
   157     val vs = fold Term.add_free_names ((snd o strip_comb o fst o HOLogic.dest_eq
   158       o HOLogic.dest_Trueprop o hd) eqs) [];
   159     fun mk_proto_eq eq =
   160       let
   161         val (head $ t $ u, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
   162       in ((HOLogic.mk_Trueprop o HOLogic.mk_eq) (head, lambda t (lambda u rhs))) end;
   163     val proto_eqs = map mk_proto_eq eqs;
   164     fun prove_simps proto_simps lthy =
   165       let
   166         val ext_simps = map (fn thm => fun_cong OF [fun_cong OF [thm]]) proto_simps;
   167         val tac = ALLGOALS (Proof_Context.fact_tac ext_simps);
   168       in (map (fn prop => Goal.prove_sorry lthy vs [] prop (K tac)) eqs, lthy) end;
   169     val b = Binding.conceal (Binding.qualify true prfx
   170       (Binding.qualify true name (Binding.name "simps")));
   171   in
   172     lthy
   173     |> random_aux_primrec_multi (name ^ prfx) proto_eqs
   174     |-> (fn proto_simps => prove_simps proto_simps)
   175     |-> (fn simps => Local_Theory.note
   176       ((b, Code.add_default_eqn_attrib :: @{attributes [simp, nitpick_simp]}), simps))
   177     |> snd
   178   end
   179 
   180 
   181 (* constructing random instances on datatypes *)
   182 
   183 val random_auxN = "random_aux";
   184 
   185 fun mk_random_aux_eqs thy descr vs (names, auxnames) (Ts, Us) =
   186   let
   187     val mk_const = curry (Sign.mk_const thy);
   188     val random_auxsN = map (prefix (random_auxN ^ "_")) (names @ auxnames);
   189     val rTs = Ts @ Us;
   190     fun random_resultT T = @{typ Random.seed}
   191       --> HOLogic.mk_prodT (termifyT T,@{typ Random.seed});
   192     fun sizeT T = @{typ natural} --> @{typ natural} --> T;
   193     val random_auxT = sizeT o random_resultT;
   194     val random_auxs = map2 (fn s => fn rT => Free (s, random_auxT rT))
   195       random_auxsN rTs;
   196     fun mk_random_call T = (NONE, (HOLogic.mk_random T size', T));
   197     fun mk_random_aux_call fTs (k, _) (tyco, Ts) =
   198       let
   199         val T = Type (tyco, Ts);
   200         fun mk_random_fun_lift [] t = t
   201           | mk_random_fun_lift (fT :: fTs) t =
   202               mk_const @{const_name random_fun_lift} [fTs ---> T, fT] $
   203                 mk_random_fun_lift fTs t;
   204         val t = mk_random_fun_lift fTs (nth random_auxs k $ size_pred $ size');
   205         val size = Option.map snd (Datatype_Aux.find_shortest_path descr k)
   206           |> the_default 0;
   207       in (SOME size, (t, fTs ---> T)) end;
   208     val tss = Datatype_Aux.interpret_construction descr vs
   209       { atyp = mk_random_call, dtyp = mk_random_aux_call };
   210     fun mk_consexpr simpleT (c, xs) =
   211       let
   212         val (ks, simple_tTs) = split_list xs;
   213         val T = termifyT simpleT;
   214         val tTs = (map o apsnd) termifyT simple_tTs;
   215         val is_rec = exists is_some ks;
   216         val k = fold (fn NONE => I | SOME k => Integer.max k) ks 0;
   217         val vs = Name.invent_names Name.context "x" (map snd simple_tTs);
   218         val tc = HOLogic.mk_return T @{typ Random.seed}
   219           (HOLogic.mk_valtermify_app c vs simpleT);
   220         val t = HOLogic.mk_ST
   221           (map2 (fn (t, _) => fn (v, T') => ((t, @{typ Random.seed}), SOME ((v, termifyT T')))) tTs vs)
   222             tc @{typ Random.seed} (SOME T, @{typ Random.seed});
   223         val tk = if is_rec
   224           then if k = 0 then size
   225             else @{term "Quickcheck_Random.beyond :: natural \<Rightarrow> natural \<Rightarrow> natural"}
   226              $ HOLogic.mk_number @{typ natural} k $ size
   227           else @{term "1::natural"}
   228       in (is_rec, HOLogic.mk_prod (tk, t)) end;
   229     fun sort_rec xs =
   230       map_filter (fn (true, t) => SOME t | _ =>  NONE) xs
   231       @ map_filter (fn (false, t) => SOME t | _ =>  NONE) xs;
   232     val gen_exprss = tss
   233       |> (map o apfst) Type
   234       |> map (fn (T, cs) => (T, (sort_rec o map (mk_consexpr T)) cs));
   235     fun mk_select (rT, xs) =
   236       mk_const @{const_name Quickcheck_Random.collapse} [@{typ Random.seed}, termifyT rT]
   237       $ (mk_const @{const_name Random.select_weight} [random_resultT rT]
   238         $ HOLogic.mk_list (HOLogic.mk_prodT (@{typ natural}, random_resultT rT)) xs)
   239           $ seed;
   240     val auxs_lhss = map (fn t => t $ size $ size' $ seed) random_auxs;
   241     val auxs_rhss = map mk_select gen_exprss;
   242   in (random_auxs, auxs_lhss ~~ auxs_rhss) end;
   243 
   244 fun instantiate_random_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   245   let
   246     val _ = Datatype_Aux.message config "Creating quickcheck generators ...";
   247     val mk_prop_eq = HOLogic.mk_Trueprop o HOLogic.mk_eq;
   248     fun mk_size_arg k = case Datatype_Aux.find_shortest_path descr k
   249      of SOME (_, l) => if l = 0 then size
   250           else @{term "max :: natural \<Rightarrow> natural \<Rightarrow> natural"}
   251             $ HOLogic.mk_number @{typ natural} l $ size
   252       | NONE => size;
   253     val (random_auxs, auxs_eqs) = (apsnd o map) mk_prop_eq
   254       (mk_random_aux_eqs thy descr vs (names, auxnames) (Ts, Us));
   255     val random_defs = map_index (fn (k, T) => mk_prop_eq
   256       (HOLogic.mk_random T size, nth random_auxs k $ mk_size_arg k $ size)) Ts;
   257   in
   258     thy
   259     |> Class.instantiation (tycos, vs, @{sort random})
   260     |> random_aux_specification prfx random_auxN auxs_eqs
   261     |> `(fn lthy => map (Syntax.check_term lthy) random_defs)
   262     |-> (fn random_defs' => fold_map (fn random_def =>
   263           Specification.definition (NONE, (apfst Binding.conceal
   264             Attrib.empty_binding, random_def))) random_defs')
   265     |> snd
   266     |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   267   end;
   268 
   269 (** building and compiling generator expressions **)
   270 
   271 (* FIXME just one data slot (record) per program unit *)
   272 
   273 structure Counterexample = Proof_Data
   274 (
   275   type T = unit -> Code_Numeral.natural -> bool -> Code_Numeral.natural -> seed -> (bool * term list) option * seed
   276   (* FIXME avoid user error with non-user text *)
   277   fun init _ () = error "Counterexample"
   278 );
   279 val put_counterexample = Counterexample.put;
   280 
   281 structure Counterexample_Report = Proof_Data
   282 (
   283   type T = unit -> Code_Numeral.natural -> bool -> Code_Numeral.natural -> seed -> ((bool * term list) option * (bool list * bool)) * seed
   284   (* FIXME avoid user error with non-user text *)
   285   fun init _ () = error "Counterexample_Report"
   286 );
   287 val put_counterexample_report = Counterexample_Report.put;
   288 
   289 val target = "Quickcheck";
   290 
   291 fun mk_generator_expr ctxt (t, _) =
   292   let  
   293     val thy = Proof_Context.theory_of ctxt
   294     val prop = fold_rev absfree (Term.add_frees t []) t
   295     val Ts = (map snd o fst o strip_abs) prop
   296     val bound_max = length Ts - 1;
   297     val bounds = map_index (fn (i, ty) =>
   298       (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
   299     val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
   300     val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
   301     val ([genuine_only_name], _) = Variable.variant_fixes ["genuine_only"] ctxt
   302     val genuine_only = Free (genuine_only_name, @{typ bool})
   303     val none_t = Const (@{const_name "None"}, resultT)
   304     val check = Quickcheck_Common.mk_safe_if genuine_only none_t (result, none_t,
   305       fn genuine => @{term "Some :: bool * term list => (bool * term list) option"} $
   306         HOLogic.mk_prod (Quickcheck_Common.reflect_bool genuine, terms))
   307     val return = HOLogic.pair_const resultT @{typ Random.seed};
   308     fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
   309     fun mk_termtyp T = HOLogic.mk_prodT (T, @{typ "unit => term"});
   310     fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
   311       liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
   312     fun mk_split T = Sign.mk_const thy
   313       (@{const_name prod_case}, [T, @{typ "unit => term"}, liftT resultT @{typ Random.seed}]);
   314     fun mk_scomp_split T t t' =
   315       mk_scomp (mk_termtyp T) resultT @{typ Random.seed} t
   316         (mk_split T $ Abs ("", T, Abs ("", @{typ "unit => term"}, t')));
   317     fun mk_bindclause (_, _, i, T) = mk_scomp_split T
   318       (Sign.mk_const thy (@{const_name Quickcheck_Random.random}, [T]) $ Bound i);
   319   in
   320     lambda genuine_only
   321       (Abs ("n", @{typ natural}, fold_rev mk_bindclause bounds (return $ check true)))
   322   end;
   323 
   324 fun mk_reporting_generator_expr ctxt (t, _) =
   325   let
   326     val thy = Proof_Context.theory_of ctxt
   327     val resultT = @{typ "(bool * term list) option * (bool list * bool)"}
   328     val prop = fold_rev absfree (Term.add_frees t []) t
   329     val Ts = (map snd o fst o strip_abs) prop
   330     val bound_max = length Ts - 1
   331     val bounds = map_index (fn (i, ty) =>
   332       (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
   333     val prop' = betapplys (prop, map (fn (i, _, _, _) => Bound i) bounds);
   334     val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds)
   335     val (assms, concl) = Quickcheck_Common.strip_imp prop'
   336     val return = HOLogic.pair_const resultT @{typ Random.seed};
   337     fun mk_assms_report i =
   338       HOLogic.mk_prod (@{term "None :: (bool * term list) option"},
   339         HOLogic.mk_prod (HOLogic.mk_list HOLogic.boolT
   340           (replicate i @{term True} @ replicate (length assms - i) @{term False}),
   341         @{term False}))
   342     fun mk_concl_report b =
   343       HOLogic.mk_prod (HOLogic.mk_list HOLogic.boolT (replicate (length assms) @{term True}),
   344         Quickcheck_Common.reflect_bool b)
   345     val ([genuine_only_name], _) = Variable.variant_fixes ["genuine_only"] ctxt
   346     val genuine_only = Free (genuine_only_name, @{typ bool})
   347     val none_t = HOLogic.mk_prod (@{term "None :: (bool * term list) option"}, mk_concl_report true)
   348     val concl_check = Quickcheck_Common.mk_safe_if genuine_only none_t (concl, none_t,
   349       fn genuine => HOLogic.mk_prod (@{term "Some :: bool * term list => (bool * term list) option"} $
   350         HOLogic.mk_prod (Quickcheck_Common.reflect_bool genuine, terms), mk_concl_report false))
   351     val check = fold_rev (fn (i, assm) => fn t => Quickcheck_Common.mk_safe_if genuine_only
   352       (mk_assms_report i) (HOLogic.mk_not assm, mk_assms_report i, t))
   353       (map_index I assms) concl_check
   354     fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
   355     fun mk_termtyp T = HOLogic.mk_prodT (T, @{typ "unit => term"});
   356     fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
   357       liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
   358     fun mk_split T = Sign.mk_const thy
   359       (@{const_name prod_case}, [T, @{typ "unit => term"}, liftT resultT @{typ Random.seed}]);
   360     fun mk_scomp_split T t t' =
   361       mk_scomp (mk_termtyp T) resultT @{typ Random.seed} t
   362         (mk_split T $ Abs ("", T, Abs ("", @{typ "unit => term"}, t')));
   363     fun mk_bindclause (_, _, i, T) = mk_scomp_split T
   364       (Sign.mk_const thy (@{const_name Quickcheck_Random.random}, [T]) $ Bound i);
   365   in
   366     lambda genuine_only
   367       (Abs ("n", @{typ natural}, fold_rev mk_bindclause bounds (return $ check true)))
   368   end
   369 
   370 val mk_parametric_generator_expr = Quickcheck_Common.gen_mk_parametric_generator_expr 
   371   ((mk_generator_expr, 
   372     absdummy @{typ bool} (absdummy @{typ natural}
   373       @{term "Pair None :: Random.seed => (bool * term list) option * Random.seed"})),
   374     @{typ "bool => natural => Random.seed => (bool * term list) option * Random.seed"})
   375 
   376 val mk_parametric_reporting_generator_expr = Quickcheck_Common.gen_mk_parametric_generator_expr 
   377   ((mk_reporting_generator_expr,
   378     absdummy @{typ bool} (absdummy @{typ natural}
   379       @{term "Pair (None, ([], False)) :: Random.seed =>
   380         ((bool * term list) option * (bool list * bool)) * Random.seed"})),
   381     @{typ "bool => natural => Random.seed => ((bool * term list) option * (bool list * bool)) * Random.seed"})
   382     
   383     
   384 (* single quickcheck report *)
   385 
   386 datatype single_report = Run of bool list * bool | MatchExc
   387 
   388 fun collect_single_report single_report
   389     (Quickcheck.Report {iterations = iterations, raised_match_errors = raised_match_errors,
   390     satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
   391   case single_report
   392   of MatchExc =>
   393     Quickcheck.Report {iterations = iterations + 1, raised_match_errors = raised_match_errors + 1,
   394       satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}
   395    | Run (assms, concl) =>
   396     Quickcheck.Report {iterations = iterations + 1, raised_match_errors = raised_match_errors,
   397       satisfied_assms =
   398         map2 (fn b => fn s => if b then s + 1 else s) assms
   399          (if null satisfied_assms then replicate (length assms) 0 else satisfied_assms),
   400       positive_concl_tests = if concl then positive_concl_tests + 1 else positive_concl_tests}
   401 
   402 val empty_report = Quickcheck.Report { iterations = 0, raised_match_errors = 0,
   403   satisfied_assms = [], positive_concl_tests = 0 }
   404     
   405 fun compile_generator_expr_raw ctxt ts =
   406   let
   407     val thy = Proof_Context.theory_of ctxt
   408     val iterations = Config.get ctxt Quickcheck.iterations
   409   in
   410     if Config.get ctxt Quickcheck.report then
   411       let
   412         val t' = mk_parametric_reporting_generator_expr ctxt ts;
   413         val compile = Code_Runtime.dynamic_value_strict
   414           (Counterexample_Report.get, put_counterexample_report, "Random_Generators.put_counterexample_report")
   415           thy (SOME target)
   416           (fn proc => fn g => fn c => fn b => fn s => g c b s
   417             #>> (apfst o Option.map o apsnd o map) proc) t' [];
   418         fun single_tester c b s = compile c b s |> Random_Engine.run
   419         fun iterate_and_collect _ _ 0 report = (NONE, report)
   420           | iterate_and_collect genuine_only (card, size) j report =
   421             let
   422               val (test_result, single_report) = apsnd Run (single_tester card genuine_only size)
   423               val report = collect_single_report single_report report
   424             in
   425               case test_result of NONE => iterate_and_collect genuine_only (card, size) (j - 1) report
   426                 | SOME q => (SOME q, report)
   427             end
   428       in
   429         fn genuine_only => fn [card, size] =>
   430           apsnd SOME (iterate_and_collect genuine_only (card, size) iterations empty_report)
   431       end
   432     else
   433       let
   434         val t' = mk_parametric_generator_expr ctxt ts;
   435         val compile = Code_Runtime.dynamic_value_strict
   436           (Counterexample.get, put_counterexample, "Random_Generators.put_counterexample")
   437           thy (SOME target)
   438           (fn proc => fn g => fn c => fn b => fn s => g c b s
   439             #>> (Option.map o apsnd o map) proc) t' [];
   440         fun single_tester c b s = compile c b s |> Random_Engine.run
   441         fun iterate _ _ 0 = NONE
   442           | iterate genuine_only (card, size) j =
   443             case single_tester card genuine_only size of
   444               NONE => iterate genuine_only (card, size) (j - 1)
   445             | SOME q => SOME q
   446       in
   447         fn genuine_only => fn [card, size] =>
   448           (rpair NONE (iterate genuine_only (card, size) iterations))
   449       end
   450   end;
   451 
   452 fun compile_generator_expr ctxt ts =
   453   let
   454     val compiled = compile_generator_expr_raw ctxt ts
   455   in fn genuine_only => fn [card, size] =>
   456     compiled genuine_only [Code_Numeral.natural_of_integer card, Code_Numeral.natural_of_integer size]
   457   end;
   458 
   459 val size_types = [@{type_name Enum.finite_1}, @{type_name Enum.finite_2},
   460   @{type_name Enum.finite_3}, @{type_name Enum.finite_4}, @{type_name Enum.finite_5}];
   461 
   462 fun size_matters_for _ Ts =
   463   not (forall (fn Type (tyco, []) => member (op =) size_types tyco | _ => false) Ts);
   464 
   465 val test_goals =
   466   Quickcheck_Common.generator_test_goal_terms ("random", (size_matters_for, compile_generator_expr));
   467   
   468 (** setup **)
   469 
   470 val active = Attrib.setup_config_bool @{binding quickcheck_random_active} (K false);
   471 
   472 val setup =
   473   Quickcheck_Common.datatype_interpretation (@{sort random}, instantiate_random_datatype)
   474   #> Context.theory_map (Quickcheck.add_tester ("random", (active, test_goals)));
   475 
   476 end;