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