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