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