src/HOL/Tools/quickcheck_generators.ML
author bulwahn
Thu Feb 25 09:28:01 2010 +0100 (2010-02-25)
changeset 35378 95d0e3adf38e
parent 35166 a57ef2cd2236
child 35845 e5980f0ad025
permissions -rw-r--r--
added basic reporting of test cases to quickcheck
haftmann@31260
     1
(* Author: Florian Haftmann, TU Muenchen
haftmann@31260
     2
haftmann@31260
     3
Quickcheck generators for various types.
haftmann@31260
     4
*)
haftmann@31260
     5
haftmann@31260
     6
signature QUICKCHECK_GENERATORS =
haftmann@31260
     7
sig
haftmann@31260
     8
  type seed = Random_Engine.seed
haftmann@31260
     9
  val random_fun: typ -> typ -> ('a -> 'a -> bool) -> ('a -> term)
haftmann@31260
    10
    -> (seed -> ('b * (unit -> term)) * seed) -> (seed -> seed * seed)
wenzelm@33243
    11
    -> seed -> (('a -> 'b) * (unit -> term)) * seed
haftmann@31260
    12
  val ensure_random_typecopy: string -> theory -> theory
haftmann@31868
    13
  val random_aux_specification: string -> string -> term list -> local_theory -> local_theory
haftmann@31737
    14
  val mk_random_aux_eqs: theory -> Datatype.descr -> (string * sort) list
haftmann@31603
    15
    -> string list -> string list * string list -> typ list * typ list
haftmann@31868
    16
    -> term list * (term * term) list
haftmann@31737
    17
  val ensure_random_datatype: Datatype.config -> string list -> theory -> theory
bulwahn@35378
    18
  val compile_generator_expr:
bulwahn@35378
    19
    theory -> bool -> term -> int -> term list option * (bool list * bool)
wenzelm@32740
    20
  val eval_ref: (unit -> int -> seed -> term list option * seed) option Unsynchronized.ref
bulwahn@35378
    21
  val eval_report_ref:
bulwahn@35378
    22
    (unit -> int -> seed -> (term list option * (bool list * bool)) * seed) option Unsynchronized.ref
haftmann@31260
    23
  val setup: theory -> theory
haftmann@31260
    24
end;
haftmann@31260
    25
haftmann@31260
    26
structure Quickcheck_Generators : QUICKCHECK_GENERATORS =
haftmann@31260
    27
struct
haftmann@31260
    28
haftmann@31950
    29
(** abstract syntax **)
haftmann@31260
    30
haftmann@31950
    31
fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"})
haftmann@31950
    32
val size = @{term "i::code_numeral"};
haftmann@31984
    33
val size_pred = @{term "(i::code_numeral) - 1"};
haftmann@31950
    34
val size' = @{term "j::code_numeral"};
haftmann@31950
    35
val seed = @{term "s::Random.seed"};
haftmann@31260
    36
haftmann@31260
    37
haftmann@31260
    38
(** typ "'a => 'b" **)
haftmann@31260
    39
haftmann@31260
    40
type seed = Random_Engine.seed;
haftmann@31260
    41
haftmann@31603
    42
fun random_fun T1 T2 eq term_of random random_split seed =
haftmann@31260
    43
  let
haftmann@31260
    44
    val fun_upd = Const (@{const_name fun_upd},
haftmann@31260
    45
      (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
haftmann@32344
    46
    val ((y, t2), seed') = random seed;
haftmann@32344
    47
    val (seed'', seed''') = random_split seed';
haftmann@31933
    48
wenzelm@32740
    49
    val state = Unsynchronized.ref (seed'', [], fn () => Abs ("x", T1, t2 ()));
haftmann@31260
    50
    fun random_fun' x =
haftmann@31260
    51
      let
haftmann@31260
    52
        val (seed, fun_map, f_t) = ! state;
haftmann@31260
    53
      in case AList.lookup (uncurry eq) fun_map x
haftmann@31260
    54
       of SOME y => y
haftmann@31260
    55
        | NONE => let
haftmann@31260
    56
              val t1 = term_of x;
haftmann@31260
    57
              val ((y, t2), seed') = random seed;
haftmann@31260
    58
              val fun_map' = (x, y) :: fun_map;
haftmann@31933
    59
              val f_t' = fn () => fun_upd $ f_t () $ t1 $ t2 ();
haftmann@31260
    60
              val _ = state := (seed', fun_map', f_t');
haftmann@31260
    61
            in y end
haftmann@31260
    62
      end;
haftmann@31933
    63
    fun term_fun' () = #3 (! state) ();
haftmann@32344
    64
  in ((random_fun', term_fun'), seed''') end;
haftmann@31260
    65
haftmann@31260
    66
haftmann@31260
    67
(** type copies **)
haftmann@31260
    68
haftmann@31950
    69
fun mk_random_typecopy tyco vs constr T' thy =
haftmann@31260
    70
  let
haftmann@34969
    71
    val mk_const = curry (Sign.mk_const thy);
haftmann@31260
    72
    val Ts = map TFree vs;  
haftmann@31260
    73
    val T = Type (tyco, Ts);
haftmann@31950
    74
    val Tm = termifyT T;
haftmann@31950
    75
    val Tm' = termifyT T';
haftmann@31260
    76
    val v = "x";
haftmann@31950
    77
    val t_v = Free (v, Tm');
haftmann@34969
    78
    val t_constr = Const (constr, T' --> T);
haftmann@31950
    79
    val lhs = HOLogic.mk_random T size;
haftmann@31950
    80
    val rhs = HOLogic.mk_ST [((HOLogic.mk_random T' size, @{typ Random.seed}), SOME (v, Tm'))]
haftmann@31950
    81
      (HOLogic.mk_return Tm @{typ Random.seed}
haftmann@32657
    82
      (mk_const "Code_Evaluation.valapp" [T', T]
haftmann@31260
    83
        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
haftmann@31950
    84
      @{typ Random.seed} (SOME Tm, @{typ Random.seed});
haftmann@31260
    85
    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
haftmann@31260
    86
  in   
haftmann@31260
    87
    thy
wenzelm@33553
    88
    |> Theory_Target.instantiation ([tyco], vs, @{sort random})
haftmann@31260
    89
    |> `(fn lthy => Syntax.check_term lthy eq)
wenzelm@33280
    90
    |-> (fn eq => Specification.definition (NONE, (apfst Binding.conceal Attrib.empty_binding, eq)))
haftmann@31260
    91
    |> snd
haftmann@31260
    92
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@31260
    93
  end;
haftmann@31260
    94
haftmann@31260
    95
fun ensure_random_typecopy tyco thy =
haftmann@31260
    96
  let
haftmann@31950
    97
    val SOME { vs = raw_vs, constr, typ = raw_T, ... } =
haftmann@31723
    98
      Typecopy.get_info thy tyco;
haftmann@31260
    99
    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
haftmann@31950
   100
    val T = map_atyps (fn TFree (v, sort) =>
haftmann@31950
   101
      TFree (v, constrain sort @{sort random})) raw_T;
haftmann@31950
   102
    val vs' = Term.add_tfreesT T [];
haftmann@31260
   103
    val vs = map (fn (v, sort) =>
haftmann@31260
   104
      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
haftmann@31950
   105
    val can_inst = Sign.of_sort thy (T, @{sort random});
haftmann@31950
   106
  in if can_inst then mk_random_typecopy tyco vs constr T thy else thy end;
haftmann@31260
   107
haftmann@31260
   108
haftmann@31260
   109
(** datatypes **)
haftmann@31260
   110
haftmann@31485
   111
(* definitional scheme for random instances on datatypes *)
haftmann@31485
   112
haftmann@31485
   113
(*FIXME avoid this low-level proving*)
haftmann@31611
   114
local
haftmann@31611
   115
haftmann@31485
   116
fun dest_ctyp_nth k cT = nth (Thm.dest_ctyp cT) k;
haftmann@31611
   117
val eq = Thm.cprop_of @{thm random_aux_rec} |> Thm.dest_arg |> Thm.dest_arg |> Thm.dest_arg;
haftmann@31611
   118
val lhs = eq |> Thm.dest_arg1;
haftmann@31611
   119
val pt_random_aux = lhs |> Thm.dest_fun;
haftmann@31611
   120
val ct_k = lhs |> Thm.dest_arg;
haftmann@31611
   121
val pt_rhs = eq |> Thm.dest_arg |> Thm.dest_fun;
haftmann@31611
   122
val aT = pt_random_aux |> Thm.ctyp_of_term |> dest_ctyp_nth 1;
haftmann@31611
   123
haftmann@31611
   124
val rew_thms = map mk_meta_eq [@{thm code_numeral_zero_minus_one},
haftmann@31611
   125
  @{thm Suc_code_numeral_minus_one}, @{thm select_weight_cons_zero}, @{thm beyond_zero}];
haftmann@31611
   126
val rew_ts = map (Logic.dest_equals o Thm.prop_of) rew_thms;
haftmann@31611
   127
val rew_ss = HOL_ss addsimps rew_thms;
haftmann@31611
   128
haftmann@31611
   129
in
haftmann@31485
   130
haftmann@31485
   131
fun random_aux_primrec eq lthy =
haftmann@31485
   132
  let
haftmann@31485
   133
    val thy = ProofContext.theory_of lthy;
haftmann@31611
   134
    val ((t_random_aux as Free (random_aux, T)) $ (t_k as Free (v, _)), proto_t_rhs) =
haftmann@31611
   135
      (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31485
   136
    val Type (_, [_, iT]) = T;
haftmann@31485
   137
    val icT = Thm.ctyp_of thy iT;
haftmann@31611
   138
    val cert = Thm.cterm_of thy;
haftmann@31611
   139
    val inst = Thm.instantiate_cterm ([(aT, icT)], []);
haftmann@31485
   140
    fun subst_v t' = map_aterms (fn t as Free (w, _) => if v = w then t' else t | t => t);
haftmann@31611
   141
    val t_rhs = lambda t_k proto_t_rhs;
haftmann@31785
   142
    val eqs0 = [subst_v @{term "0::code_numeral"} eq,
haftmann@31785
   143
      subst_v (@{term "Suc_code_numeral"} $ t_k) eq];
haftmann@31611
   144
    val eqs1 = map (Pattern.rewrite_term thy rew_ts []) eqs0;
haftmann@35166
   145
    val ((_, (_, eqs2)), lthy') = Primrec.add_primrec_simple
haftmann@33205
   146
      [((Binding.conceal (Binding.name random_aux), T), NoSyn)] eqs1 lthy;
haftmann@31611
   147
    val cT_random_aux = inst pt_random_aux;
haftmann@31611
   148
    val cT_rhs = inst pt_rhs;
haftmann@31485
   149
    val rule = @{thm random_aux_rec}
haftmann@31611
   150
      |> Drule.instantiate ([(aT, icT)],
haftmann@31785
   151
           [(cT_random_aux, cert t_random_aux), (cT_rhs, cert t_rhs)]);
haftmann@31785
   152
    val tac = ALLGOALS (rtac rule)
haftmann@31785
   153
      THEN ALLGOALS (simp_tac rew_ss)
haftmann@35166
   154
      THEN (ALLGOALS (ProofContext.fact_tac eqs2))
wenzelm@32970
   155
    val simp = Skip_Proof.prove lthy' [v] [] eq (K tac);
haftmann@31485
   156
  in (simp, lthy') end;
haftmann@31485
   157
haftmann@31611
   158
end;
haftmann@31611
   159
haftmann@31868
   160
fun random_aux_primrec_multi auxname [eq] lthy =
haftmann@31485
   161
      lthy
haftmann@31485
   162
      |> random_aux_primrec eq
haftmann@31485
   163
      |>> (fn simp => [simp])
haftmann@31868
   164
  | random_aux_primrec_multi auxname (eqs as _ :: _ :: _) lthy =
haftmann@31485
   165
      let
haftmann@31485
   166
        val thy = ProofContext.theory_of lthy;
haftmann@31485
   167
        val (lhss, rhss) = map_split (HOLogic.dest_eq o HOLogic.dest_Trueprop) eqs;
haftmann@31485
   168
        val (vs, (arg as Free (v, _)) :: _) = map_split (fn (t1 $ t2) => (t1, t2)) lhss;
haftmann@31485
   169
        val Ts = map fastype_of lhss;
haftmann@31485
   170
        val tupleT = foldr1 HOLogic.mk_prodT Ts;
haftmann@31868
   171
        val aux_lhs = Free ("mutual_" ^ auxname, fastype_of arg --> tupleT) $ arg;
haftmann@31485
   172
        val aux_eq = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@31485
   173
          (aux_lhs, foldr1 HOLogic.mk_prod rhss);
haftmann@31485
   174
        fun mk_proj t [T] = [t]
haftmann@31485
   175
          | mk_proj t (Ts as T :: (Ts' as _ :: _)) =
haftmann@31485
   176
              Const (@{const_name fst}, foldr1 HOLogic.mk_prodT Ts --> T) $ t
haftmann@31485
   177
                :: mk_proj (Const (@{const_name snd},
haftmann@31485
   178
                  foldr1 HOLogic.mk_prodT Ts --> foldr1 HOLogic.mk_prodT Ts') $ t) Ts';
haftmann@31485
   179
        val projs = mk_proj (aux_lhs) Ts;
haftmann@31485
   180
        val proj_eqs = map2 (fn v => fn proj => (v, lambda arg proj)) vs projs;
haftmann@31485
   181
        val proj_defs = map2 (fn Free (name, _) => fn (_, rhs) =>
haftmann@33205
   182
          ((Binding.conceal (Binding.name name), NoSyn),
wenzelm@33280
   183
            (apfst Binding.conceal Attrib.empty_binding, rhs))) vs proj_eqs;
haftmann@31485
   184
        val aux_eq' = Pattern.rewrite_term thy proj_eqs [] aux_eq;
haftmann@31485
   185
        fun prove_eqs aux_simp proj_defs lthy = 
haftmann@31485
   186
          let
haftmann@31485
   187
            val proj_simps = map (snd o snd) proj_defs;
wenzelm@31645
   188
            fun tac { context = ctxt, prems = _ } =
haftmann@31625
   189
              ALLGOALS (simp_tac (HOL_ss addsimps proj_simps))
haftmann@31485
   190
              THEN ALLGOALS (EqSubst.eqsubst_tac ctxt [0] [aux_simp])
haftmann@31485
   191
              THEN ALLGOALS (simp_tac (HOL_ss addsimps [fst_conv, snd_conv]));
wenzelm@32970
   192
          in (map (fn prop => Skip_Proof.prove lthy [v] [] prop tac) eqs, lthy) end;
haftmann@31485
   193
      in
haftmann@31485
   194
        lthy
haftmann@31485
   195
        |> random_aux_primrec aux_eq'
wenzelm@33766
   196
        ||>> fold_map Local_Theory.define proj_defs
haftmann@31485
   197
        |-> (fn (aux_simp, proj_defs) => prove_eqs aux_simp proj_defs)
haftmann@31485
   198
      end;
haftmann@31485
   199
haftmann@31868
   200
fun random_aux_specification prfx name eqs lthy =
haftmann@31485
   201
  let
haftmann@31595
   202
    val vs = fold Term.add_free_names ((snd o strip_comb o fst o HOLogic.dest_eq
haftmann@31595
   203
      o HOLogic.dest_Trueprop o hd) eqs) [];
haftmann@31485
   204
    fun mk_proto_eq eq =
haftmann@31485
   205
      let
haftmann@31595
   206
        val (head $ t $ u, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31595
   207
      in ((HOLogic.mk_Trueprop o HOLogic.mk_eq) (head, lambda t (lambda u rhs))) end;
haftmann@31485
   208
    val proto_eqs = map mk_proto_eq eqs;
haftmann@31485
   209
    fun prove_simps proto_simps lthy =
haftmann@31485
   210
      let
haftmann@31625
   211
        val ext_simps = map (fn thm => fun_cong OF [fun_cong OF [thm]]) proto_simps;
haftmann@31625
   212
        val tac = ALLGOALS (ProofContext.fact_tac ext_simps);
wenzelm@32970
   213
      in (map (fn prop => Skip_Proof.prove lthy vs [] prop (K tac)) eqs, lthy) end;
haftmann@33205
   214
    val b = Binding.conceal (Binding.qualify true prfx
haftmann@33205
   215
      (Binding.qualify true name (Binding.name "simps")));
haftmann@31485
   216
  in
haftmann@31485
   217
    lthy
haftmann@31868
   218
    |> random_aux_primrec_multi (name ^ prfx) proto_eqs
haftmann@31485
   219
    |-> (fn proto_simps => prove_simps proto_simps)
wenzelm@33671
   220
    |-> (fn simps => Local_Theory.note
wenzelm@33666
   221
      ((b, Code.add_default_eqn_attrib :: map (Attrib.internal o K)
wenzelm@33552
   222
          [Simplifier.simp_add, Nitpick_Simps.add]), simps))
haftmann@31485
   223
    |> snd
haftmann@31485
   224
  end
haftmann@31485
   225
haftmann@31485
   226
haftmann@31485
   227
(* constructing random instances on datatypes *)
haftmann@31485
   228
haftmann@31868
   229
val random_auxN = "random_aux";
haftmann@31868
   230
haftmann@31603
   231
fun mk_random_aux_eqs thy descr vs tycos (names, auxnames) (Ts, Us) =
haftmann@31595
   232
  let
haftmann@31595
   233
    val mk_const = curry (Sign.mk_const thy);
haftmann@31603
   234
    val random_auxsN = map (prefix (random_auxN ^ "_")) (names @ auxnames);
haftmann@31603
   235
    val rTs = Ts @ Us;
haftmann@31595
   236
    fun random_resultT T = @{typ Random.seed}
haftmann@31595
   237
      --> HOLogic.mk_prodT (termifyT T,@{typ Random.seed});
haftmann@31595
   238
    val pTs = map random_resultT rTs;
haftmann@31595
   239
    fun sizeT T = @{typ code_numeral} --> @{typ code_numeral} --> T;
haftmann@31595
   240
    val random_auxT = sizeT o random_resultT;
haftmann@31595
   241
    val random_auxs = map2 (fn s => fn rT => Free (s, random_auxT rT))
haftmann@31595
   242
      random_auxsN rTs;
haftmann@31950
   243
    fun mk_random_call T = (NONE, (HOLogic.mk_random T size', T));
haftmann@31603
   244
    fun mk_random_aux_call fTs (k, _) (tyco, Ts) =
haftmann@31595
   245
      let
haftmann@31623
   246
        val T = Type (tyco, Ts);
haftmann@31623
   247
        fun mk_random_fun_lift [] t = t
haftmann@31623
   248
          | mk_random_fun_lift (fT :: fTs) t =
haftmann@31623
   249
              mk_const @{const_name random_fun_lift} [fTs ---> T, fT] $
haftmann@31623
   250
                mk_random_fun_lift fTs t;
haftmann@31984
   251
        val t = mk_random_fun_lift fTs (nth random_auxs k $ size_pred $ size');
haftmann@33968
   252
        val size = Option.map snd (Datatype_Aux.find_shortest_path descr k)
haftmann@31595
   253
          |> the_default 0;
haftmann@31623
   254
      in (SOME size, (t, fTs ---> T)) end;
haftmann@33968
   255
    val tss = Datatype_Aux.interpret_construction descr vs
haftmann@31603
   256
      { atyp = mk_random_call, dtyp = mk_random_aux_call };
haftmann@31595
   257
    fun mk_consexpr simpleT (c, xs) =
haftmann@31595
   258
      let
haftmann@31595
   259
        val (ks, simple_tTs) = split_list xs;
haftmann@31595
   260
        val T = termifyT simpleT;
haftmann@31595
   261
        val tTs = (map o apsnd) termifyT simple_tTs;
haftmann@31595
   262
        val is_rec = exists is_some ks;
wenzelm@33029
   263
        val k = fold (fn NONE => I | SOME k => Integer.max k) ks 0;
haftmann@31595
   264
        val vs = Name.names Name.context "x" (map snd simple_tTs);
haftmann@31595
   265
        val vs' = (map o apsnd) termifyT vs;
haftmann@31595
   266
        val tc = HOLogic.mk_return T @{typ Random.seed}
haftmann@31595
   267
          (HOLogic.mk_valtermify_app c vs simpleT);
haftmann@31595
   268
        val t = HOLogic.mk_ST (map (fn (t, _) => (t, @{typ Random.seed})) tTs ~~ map SOME vs')
haftmann@31595
   269
          tc @{typ Random.seed} (SOME T, @{typ Random.seed});
haftmann@31595
   270
        val tk = if is_rec
haftmann@31950
   271
          then if k = 0 then size
haftmann@31595
   272
            else @{term "Quickcheck.beyond :: code_numeral \<Rightarrow> code_numeral \<Rightarrow> code_numeral"}
haftmann@31950
   273
             $ HOLogic.mk_number @{typ code_numeral} k $ size
haftmann@31595
   274
          else @{term "1::code_numeral"}
haftmann@31595
   275
      in (is_rec, HOLogic.mk_prod (tk, t)) end;
haftmann@31595
   276
    fun sort_rec xs =
haftmann@31595
   277
      map_filter (fn (true, t) => SOME t | _ =>  NONE) xs
haftmann@31595
   278
      @ map_filter (fn (false, t) => SOME t | _ =>  NONE) xs;
haftmann@31603
   279
    val gen_exprss = tss
haftmann@31603
   280
      |> (map o apfst) Type
haftmann@31595
   281
      |> map (fn (T, cs) => (T, (sort_rec o map (mk_consexpr T)) cs));
haftmann@31595
   282
    fun mk_select (rT, xs) =
haftmann@31595
   283
      mk_const @{const_name Quickcheck.collapse} [@{typ "Random.seed"}, termifyT rT]
haftmann@31595
   284
      $ (mk_const @{const_name Random.select_weight} [random_resultT rT]
haftmann@31595
   285
        $ HOLogic.mk_list (HOLogic.mk_prodT (@{typ code_numeral}, random_resultT rT)) xs)
haftmann@31595
   286
          $ seed;
haftmann@31950
   287
    val auxs_lhss = map (fn t => t $ size $ size' $ seed) random_auxs;
haftmann@31595
   288
    val auxs_rhss = map mk_select gen_exprss;
haftmann@31868
   289
  in (random_auxs, auxs_lhss ~~ auxs_rhss) end;
haftmann@31595
   290
haftmann@31868
   291
fun mk_random_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
haftmann@31595
   292
  let
haftmann@33968
   293
    val _ = Datatype_Aux.message config "Creating quickcheck generators ...";
haftmann@31595
   294
    val mk_prop_eq = HOLogic.mk_Trueprop o HOLogic.mk_eq;
haftmann@33968
   295
    fun mk_size_arg k = case Datatype_Aux.find_shortest_path descr k
haftmann@31950
   296
     of SOME (_, l) => if l = 0 then size
haftmann@31595
   297
          else @{term "max :: code_numeral \<Rightarrow> code_numeral \<Rightarrow> code_numeral"}
haftmann@31950
   298
            $ HOLogic.mk_number @{typ code_numeral} l $ size
haftmann@31950
   299
      | NONE => size;
haftmann@31868
   300
    val (random_auxs, auxs_eqs) = (apsnd o map) mk_prop_eq
haftmann@31603
   301
      (mk_random_aux_eqs thy descr vs tycos (names, auxnames) (Ts, Us));
haftmann@31595
   302
    val random_defs = map_index (fn (k, T) => mk_prop_eq
haftmann@31950
   303
      (HOLogic.mk_random T size, nth random_auxs k $ mk_size_arg k $ size)) Ts;
haftmann@31595
   304
  in
haftmann@31595
   305
    thy
wenzelm@33553
   306
    |> Theory_Target.instantiation (tycos, vs, @{sort random})
haftmann@31868
   307
    |> random_aux_specification prfx random_auxN auxs_eqs
haftmann@31595
   308
    |> `(fn lthy => map (Syntax.check_term lthy) random_defs)
haftmann@31595
   309
    |-> (fn random_defs' => fold_map (fn random_def =>
wenzelm@33280
   310
          Specification.definition (NONE, (apfst Binding.conceal
haftmann@33205
   311
            Attrib.empty_binding, random_def))) random_defs')
haftmann@31595
   312
    |> snd
haftmann@31595
   313
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@31595
   314
  end;
haftmann@31595
   315
haftmann@31623
   316
fun perhaps_constrain thy insts raw_vs =
haftmann@31623
   317
  let
haftmann@31623
   318
    fun meet_random (T, sort) = Sorts.meet_sort (Sign.classes_of thy) 
haftmann@31623
   319
      (Logic.varifyT T, sort);
haftmann@31623
   320
    val vtab = Vartab.empty
haftmann@31623
   321
      |> fold (fn (v, sort) => Vartab.update ((v, 0), sort)) raw_vs
haftmann@31623
   322
      |> fold meet_random insts;
haftmann@31623
   323
  in SOME (fn (v, _) => (v, (the o Vartab.lookup vtab) (v, 0)))
wenzelm@33087
   324
  end handle Sorts.CLASS_ERROR _ => NONE;
haftmann@31623
   325
haftmann@31668
   326
fun ensure_random_datatype config raw_tycos thy =
haftmann@31595
   327
  let
haftmann@31595
   328
    val algebra = Sign.classes_of thy;
haftmann@31868
   329
    val (descr, raw_vs, tycos, prfx, (names, auxnames), raw_TUs) =
haftmann@31784
   330
      Datatype.the_descr thy raw_tycos;
haftmann@32378
   331
    val typerep_vs = (map o apsnd)
haftmann@31744
   332
      (curry (Sorts.inter_sort algebra) @{sort typerep}) raw_vs;
haftmann@31623
   333
    val random_insts = (map (rpair @{sort random}) o flat o maps snd o maps snd)
haftmann@33968
   334
      (Datatype_Aux.interpret_construction descr typerep_vs
haftmann@31744
   335
        { atyp = single, dtyp = (K o K o K) [] });
haftmann@31623
   336
    val term_of_insts = (map (rpair @{sort term_of}) o flat o maps snd o maps snd)
haftmann@33968
   337
      (Datatype_Aux.interpret_construction descr typerep_vs
haftmann@31744
   338
        { atyp = K [], dtyp = K o K });
haftmann@31608
   339
    val has_inst = exists (fn tyco =>
haftmann@31595
   340
      can (Sorts.mg_domain algebra tyco) @{sort random}) tycos;
haftmann@31623
   341
  in if has_inst then thy
haftmann@32378
   342
    else case perhaps_constrain thy (random_insts @ term_of_insts) typerep_vs
haftmann@31668
   343
     of SOME constrain => mk_random_datatype config descr
haftmann@32378
   344
          (map constrain typerep_vs) tycos prfx (names, auxnames)
haftmann@31623
   345
            ((pairself o map o map_atyps) (fn TFree v => TFree (constrain v)) raw_TUs) thy
haftmann@31623
   346
      | NONE => thy
haftmann@31623
   347
  end;
haftmann@31260
   348
haftmann@31260
   349
haftmann@31950
   350
(** building and compiling generator expressions **)
haftmann@31950
   351
wenzelm@32740
   352
val eval_ref :
wenzelm@32740
   353
    (unit -> int -> int * int -> term list option * (int * int)) option Unsynchronized.ref =
wenzelm@32740
   354
  Unsynchronized.ref NONE;
haftmann@31950
   355
bulwahn@35378
   356
val eval_report_ref :
bulwahn@35378
   357
    (unit -> int -> seed -> (term list option * (bool list * bool)) * seed) option Unsynchronized.ref =
bulwahn@35378
   358
  Unsynchronized.ref NONE;
bulwahn@35378
   359
haftmann@31950
   360
val target = "Quickcheck";
haftmann@31950
   361
haftmann@31950
   362
fun mk_generator_expr thy prop Ts =
haftmann@31950
   363
  let
haftmann@31950
   364
    val bound_max = length Ts - 1;
haftmann@31950
   365
    val bounds = map_index (fn (i, ty) =>
haftmann@31950
   366
      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
haftmann@31950
   367
    val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
haftmann@31950
   368
    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
haftmann@31950
   369
    val check = @{term "If :: bool => term list option => term list option => term list option"}
bulwahn@35378
   370
      $ result $ @{term "None :: term list option"} $ (@{term "Some :: term list => term list option"} $ terms);
haftmann@31950
   371
    val return = @{term "Pair :: term list option => Random.seed => term list option * Random.seed"};
haftmann@31950
   372
    fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
haftmann@31950
   373
    fun mk_termtyp T = HOLogic.mk_prodT (T, @{typ "unit => term"});
haftmann@31950
   374
    fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
haftmann@31950
   375
      liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
haftmann@31950
   376
    fun mk_split T = Sign.mk_const thy
haftmann@31950
   377
      (@{const_name split}, [T, @{typ "unit => term"}, liftT @{typ "term list option"} @{typ Random.seed}]);
haftmann@31950
   378
    fun mk_scomp_split T t t' =
haftmann@31950
   379
      mk_scomp (mk_termtyp T) @{typ "term list option"} @{typ Random.seed} t
haftmann@31950
   380
        (mk_split T $ Abs ("", T, Abs ("", @{typ "unit => term"}, t')));
haftmann@31950
   381
    fun mk_bindclause (_, _, i, T) = mk_scomp_split T
haftmann@31950
   382
      (Sign.mk_const thy (@{const_name Quickcheck.random}, [T]) $ Bound i);
haftmann@31950
   383
  in Abs ("n", @{typ code_numeral}, fold_rev mk_bindclause bounds (return $ check)) end;
haftmann@31950
   384
bulwahn@35378
   385
fun mk_reporting_generator_expr thy prop Ts =
bulwahn@35378
   386
  let
bulwahn@35378
   387
    val bound_max = length Ts - 1;
bulwahn@35378
   388
    val bounds = map_index (fn (i, ty) =>
bulwahn@35378
   389
      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
bulwahn@35378
   390
    fun strip_imp (Const("op -->",_) $ A $ B) = apfst (cons A) (strip_imp B)
bulwahn@35378
   391
      | strip_imp A = ([], A)
bulwahn@35378
   392
    val prop' = betapplys (prop, map (fn (i, _, _, _) => Bound i) bounds);
bulwahn@35378
   393
    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds)
bulwahn@35378
   394
    val (assms, concl) = strip_imp prop'
bulwahn@35378
   395
    val return =
bulwahn@35378
   396
      @{term "Pair :: term list option * (bool list * bool) => Random.seed => (term list option * (bool list * bool)) * Random.seed"};
bulwahn@35378
   397
    fun mk_assms_report i =
bulwahn@35378
   398
      HOLogic.mk_prod (@{term "None :: term list option"},
bulwahn@35378
   399
        HOLogic.mk_prod (HOLogic.mk_list @{typ "bool"}
bulwahn@35378
   400
          (replicate i @{term "True"} @ replicate (length assms - i) @{term "False"}),
bulwahn@35378
   401
        @{term "False"}))
bulwahn@35378
   402
    fun mk_concl_report b =
bulwahn@35378
   403
      HOLogic.mk_prod (HOLogic.mk_list @{typ "bool"} (replicate (length assms) @{term "True"}),
bulwahn@35378
   404
        if b then @{term True} else @{term False})
bulwahn@35378
   405
    val If =
bulwahn@35378
   406
      @{term "If :: bool => term list option * (bool list * bool) => term list option * (bool list * bool) => term list option * (bool list * bool)"}
bulwahn@35378
   407
    val concl_check = If $ concl $
bulwahn@35378
   408
      HOLogic.mk_prod (@{term "None :: term list option"}, mk_concl_report true) $
bulwahn@35378
   409
      HOLogic.mk_prod (@{term "Some :: term list  => term list option"} $ terms, mk_concl_report false)
bulwahn@35378
   410
    val check = fold_rev (fn (i, assm) => fn t => If $ assm $ t $ mk_assms_report i)
bulwahn@35378
   411
      (map_index I assms) concl_check
bulwahn@35378
   412
    fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
bulwahn@35378
   413
    fun mk_termtyp T = HOLogic.mk_prodT (T, @{typ "unit => term"});
bulwahn@35378
   414
    fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
bulwahn@35378
   415
      liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
bulwahn@35378
   416
    fun mk_split T = Sign.mk_const thy
bulwahn@35378
   417
      (@{const_name split}, [T, @{typ "unit => term"},
bulwahn@35378
   418
        liftT @{typ "term list option * (bool list * bool)"} @{typ Random.seed}]);
bulwahn@35378
   419
    fun mk_scomp_split T t t' =
bulwahn@35378
   420
      mk_scomp (mk_termtyp T) @{typ "term list option * (bool list * bool)"} @{typ Random.seed} t
bulwahn@35378
   421
        (mk_split T $ Abs ("", T, Abs ("", @{typ "unit => term"}, t')));
bulwahn@35378
   422
    fun mk_bindclause (_, _, i, T) = mk_scomp_split T
bulwahn@35378
   423
      (Sign.mk_const thy (@{const_name Quickcheck.random}, [T]) $ Bound i);
bulwahn@35378
   424
  in
bulwahn@35378
   425
    Abs ("n", @{typ code_numeral}, fold_rev mk_bindclause bounds (return $ check))
bulwahn@35378
   426
  end
bulwahn@35378
   427
bulwahn@35378
   428
fun compile_generator_expr thy report t =
haftmann@31950
   429
  let
haftmann@31950
   430
    val Ts = (map snd o fst o strip_abs) t;
bulwahn@35378
   431
  in
bulwahn@35378
   432
    if report then
bulwahn@35378
   433
      let
bulwahn@35378
   434
        val t' = mk_reporting_generator_expr thy t Ts;
bulwahn@35378
   435
        val compile = Code_Eval.eval (SOME target) ("Quickcheck_Generators.eval_report_ref", eval_report_ref)
bulwahn@35378
   436
          (fn proc => fn g => fn s => g s #>> ((apfst o Option.map o map) proc)) thy t' [];
bulwahn@35378
   437
      in
bulwahn@35378
   438
        compile #> Random_Engine.run
bulwahn@35378
   439
      end
bulwahn@35378
   440
    else
bulwahn@35378
   441
      let
bulwahn@35378
   442
        val t' = mk_generator_expr thy t Ts;
bulwahn@35378
   443
        val compile = Code_Eval.eval (SOME target) ("Quickcheck_Generators.eval_ref", eval_ref)
bulwahn@35378
   444
          (fn proc => fn g => fn s => g s #>> (Option.map o map) proc) thy t' [];
bulwahn@35378
   445
        val dummy_report = ([], false)
bulwahn@35378
   446
      in fn s => ((compile #> Random_Engine.run) s, dummy_report) end
bulwahn@35378
   447
  end;
haftmann@31950
   448
haftmann@31950
   449
haftmann@31260
   450
(** setup **)
haftmann@31260
   451
haftmann@31950
   452
val setup = Typecopy.interpretation ensure_random_typecopy
haftmann@31950
   453
  #> Datatype.interpretation ensure_random_datatype
haftmann@34028
   454
  #> Code_Target.extend_target (target, (Code_Eval.target, K I))
haftmann@31950
   455
  #> Quickcheck.add_generator ("code", compile_generator_expr o ProofContext.theory_of);
haftmann@31260
   456
haftmann@31260
   457
end;