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