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