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