src/HOL/Tools/quickcheck_generators.ML
author haftmann
Tue Jun 09 22:59:54 2009 +0200 (2009-06-09)
changeset 31595 bd2f7211a420
parent 31485 259a3c90016e
child 31603 fa30cd74d7d6
permissions -rw-r--r--
first running version of qc generators for datatypes
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@31485
    14
  val random_aux_specification: string -> term list -> local_theory -> local_theory
haftmann@31595
    15
  val mk_random_aux_eqs: theory -> DatatypeAux.descr -> (string * sort) list
haftmann@31595
    16
    -> typ list -> typ list -> string list -> string list
haftmann@31595
    17
    -> string * (term list * (term * term) list)
haftmann@31595
    18
  val ensure_random_datatype: string list -> theory -> theory
haftmann@31260
    19
  val eval_ref: (unit -> int -> int * int -> term list option * (int * int)) 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@31260
    52
      (Sign.mk_const thy (@{const_name 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@31260
    68
fun random_fun (T1 : typ) (T2 : typ) (eq : 'a -> 'a -> bool) (term_of : 'a -> term)
haftmann@31260
    69
    (random : seed -> ('b * (unit -> term)) * seed)
haftmann@31260
    70
    (random_split : seed -> seed * seed)
haftmann@31260
    71
    (seed : seed) =
haftmann@31260
    72
  let
haftmann@31260
    73
    val (seed', seed'') = random_split seed;
haftmann@31260
    74
    val state = ref (seed', [], Const (@{const_name undefined}, T1 --> T2));
haftmann@31260
    75
    val fun_upd = Const (@{const_name fun_upd},
haftmann@31260
    76
      (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
haftmann@31260
    77
    fun random_fun' x =
haftmann@31260
    78
      let
haftmann@31260
    79
        val (seed, fun_map, f_t) = ! state;
haftmann@31260
    80
      in case AList.lookup (uncurry eq) fun_map x
haftmann@31260
    81
       of SOME y => y
haftmann@31260
    82
        | NONE => let
haftmann@31260
    83
              val t1 = term_of x;
haftmann@31260
    84
              val ((y, t2), seed') = random seed;
haftmann@31260
    85
              val fun_map' = (x, y) :: fun_map;
haftmann@31260
    86
              val f_t' = fun_upd $ f_t $ t1 $ t2 ();
haftmann@31260
    87
              val _ = state := (seed', fun_map', f_t');
haftmann@31260
    88
            in y end
haftmann@31260
    89
      end;
haftmann@31260
    90
    fun term_fun' () = #3 (! state);
haftmann@31260
    91
  in ((random_fun', term_fun'), seed'') end;
haftmann@31260
    92
haftmann@31260
    93
haftmann@31260
    94
(** type copies **)
haftmann@31260
    95
haftmann@31260
    96
fun mk_random_typecopy tyco vs constr typ thy =
haftmann@31260
    97
  let
haftmann@31260
    98
    val Ts = map TFree vs;  
haftmann@31260
    99
    val T = Type (tyco, Ts);
haftmann@31260
   100
    fun mk_termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"})
haftmann@31260
   101
    val Ttm = mk_termifyT T;
haftmann@31260
   102
    val typtm = mk_termifyT typ;
haftmann@31260
   103
    fun mk_const c Ts = Const (c, Sign.const_instance thy (c, Ts));
haftmann@31260
   104
    fun mk_random T = mk_const @{const_name random} [T];
haftmann@31260
   105
    val size = @{term "j::code_numeral"};
haftmann@31260
   106
    val v = "x";
haftmann@31260
   107
    val t_v = Free (v, typtm);
haftmann@31260
   108
    val t_constr = mk_const constr Ts;
haftmann@31260
   109
    val lhs = mk_random T $ size;
haftmann@31260
   110
    val rhs = HOLogic.mk_ST [(((mk_random typ) $ size, @{typ Random.seed}), SOME (v, typtm))]
haftmann@31260
   111
      (HOLogic.mk_return Ttm @{typ Random.seed}
haftmann@31260
   112
      (mk_const "Code_Eval.valapp" [typ, T]
haftmann@31260
   113
        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
haftmann@31260
   114
      @{typ Random.seed} (SOME Ttm, @{typ Random.seed});
haftmann@31260
   115
    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
haftmann@31260
   116
  in   
haftmann@31260
   117
    thy
haftmann@31260
   118
    |> TheoryTarget.instantiation ([tyco], vs, @{sort random})
haftmann@31260
   119
    |> `(fn lthy => Syntax.check_term lthy eq)
haftmann@31260
   120
    |-> (fn eq => Specification.definition (NONE, (Attrib.empty_binding, eq)))
haftmann@31260
   121
    |> snd
haftmann@31260
   122
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@31260
   123
  end;
haftmann@31260
   124
haftmann@31260
   125
fun ensure_random_typecopy tyco thy =
haftmann@31260
   126
  let
haftmann@31260
   127
    val SOME { vs = raw_vs, constr, typ = raw_typ, ... } =
haftmann@31260
   128
      TypecopyPackage.get_info thy tyco;
haftmann@31260
   129
    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
haftmann@31260
   130
    val typ = map_atyps (fn TFree (v, sort) =>
haftmann@31260
   131
      TFree (v, constrain sort @{sort random})) raw_typ;
haftmann@31260
   132
    val vs' = Term.add_tfreesT typ [];
haftmann@31260
   133
    val vs = map (fn (v, sort) =>
haftmann@31260
   134
      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
haftmann@31260
   135
    val do_inst = Sign.of_sort thy (typ, @{sort random});
haftmann@31260
   136
  in if do_inst then mk_random_typecopy tyco vs constr typ thy else thy end;
haftmann@31260
   137
haftmann@31260
   138
haftmann@31260
   139
(** datatypes **)
haftmann@31260
   140
haftmann@31485
   141
(* definitional scheme for random instances on datatypes *)
haftmann@31485
   142
haftmann@31485
   143
(*FIXME avoid this low-level proving*)
haftmann@31485
   144
val rct = Thm.cprop_of @{thm random_aux_rec} |> Thm.dest_arg |> Thm.dest_arg
haftmann@31485
   145
  |> Thm.dest_arg |> Thm.dest_arg1 |> Thm.dest_fun;
haftmann@31485
   146
fun dest_ctyp_nth k cT = nth (Thm.dest_ctyp cT) k;
haftmann@31485
   147
val aT = rct |> Thm.ctyp_of_term |> dest_ctyp_nth 1;
haftmann@31485
   148
haftmann@31485
   149
fun random_aux_primrec eq lthy =
haftmann@31485
   150
  let
haftmann@31485
   151
    val thy = ProofContext.theory_of lthy;
haftmann@31485
   152
    val rews = map mk_meta_eq [@{thm code_numeral_zero_minus_one},
haftmann@31485
   153
      @{thm Suc_code_numeral_minus_one}, @{thm select_weight_cons_zero}, @{thm beyond_zero}];
haftmann@31485
   154
    val (rt as Free (random_aux, T)) $ (vt as Free (v, _)) =
haftmann@31485
   155
      (fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31485
   156
    val Type (_, [_, iT]) = T;
haftmann@31485
   157
    val icT = Thm.ctyp_of thy iT;
haftmann@31485
   158
    fun subst_v t' = map_aterms (fn t as Free (w, _) => if v = w then t' else t | t => t);
haftmann@31485
   159
    val eqs0 = [subst_v @{term "0::code_numeral"} eq, subst_v (@{term "Suc_code_numeral"} $ vt) eq];
haftmann@31485
   160
    val eqs1 = map (Pattern.rewrite_term thy (map (Logic.dest_equals o Thm.prop_of) rews) []) eqs0
haftmann@31485
   161
    val ((_, eqs2), lthy') = PrimrecPackage.add_primrec_simple
haftmann@31485
   162
      [((Binding.name random_aux, T), NoSyn)] eqs1 lthy;
haftmann@31485
   163
    val eq_tac = ALLGOALS Goal.conjunction_tac THEN ALLGOALS (simp_tac (HOL_ss addsimps rews))
haftmann@31485
   164
      THEN (ALLGOALS (ProofContext.fact_tac (flat eqs2)));
haftmann@31485
   165
    val eqs3 = Goal.prove_multi lthy' [v] [] eqs0 (K eq_tac);
haftmann@31485
   166
    val rct' = Thm.instantiate_cterm ([(aT, icT)], []) rct
haftmann@31485
   167
    val rule = @{thm random_aux_rec}
haftmann@31485
   168
      |> Drule.instantiate ([(aT, icT)], [(rct', Thm.cterm_of thy rt)])
haftmann@31485
   169
      |> (fn thm => thm OF eqs3)
haftmann@31485
   170
    val tac = ALLGOALS (rtac rule);
haftmann@31485
   171
    val simp = Goal.prove lthy' [v] [] eq (K tac);
haftmann@31485
   172
  in (simp, lthy') end;
haftmann@31485
   173
haftmann@31485
   174
fun random_aux_primrec_multi prefix [eq] lthy =
haftmann@31485
   175
      lthy
haftmann@31485
   176
      |> random_aux_primrec eq
haftmann@31485
   177
      |>> (fn simp => [simp])
haftmann@31485
   178
  | random_aux_primrec_multi prefix (eqs as _ :: _ :: _) lthy =
haftmann@31485
   179
      let
haftmann@31485
   180
        val thy = ProofContext.theory_of lthy;
haftmann@31485
   181
        val (lhss, rhss) = map_split (HOLogic.dest_eq o HOLogic.dest_Trueprop) eqs;
haftmann@31485
   182
        val (vs, (arg as Free (v, _)) :: _) = map_split (fn (t1 $ t2) => (t1, t2)) lhss;
haftmann@31485
   183
        val Ts = map fastype_of lhss;
haftmann@31485
   184
        val tupleT = foldr1 HOLogic.mk_prodT Ts;
haftmann@31485
   185
        val aux_lhs = Free ("mutual_" ^ prefix, fastype_of arg --> tupleT) $ arg;
haftmann@31485
   186
        val aux_eq = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@31485
   187
          (aux_lhs, foldr1 HOLogic.mk_prod rhss);
haftmann@31485
   188
        fun mk_proj t [T] = [t]
haftmann@31485
   189
          | mk_proj t (Ts as T :: (Ts' as _ :: _)) =
haftmann@31485
   190
              Const (@{const_name fst}, foldr1 HOLogic.mk_prodT Ts --> T) $ t
haftmann@31485
   191
                :: mk_proj (Const (@{const_name snd},
haftmann@31485
   192
                  foldr1 HOLogic.mk_prodT Ts --> foldr1 HOLogic.mk_prodT Ts') $ t) Ts';
haftmann@31485
   193
        val projs = mk_proj (aux_lhs) Ts;
haftmann@31485
   194
        val proj_eqs = map2 (fn v => fn proj => (v, lambda arg proj)) vs projs;
haftmann@31485
   195
        val proj_defs = map2 (fn Free (name, _) => fn (_, rhs) =>
haftmann@31485
   196
          ((Binding.name name, NoSyn), (Attrib.empty_binding, rhs))) vs proj_eqs;
haftmann@31485
   197
        val aux_eq' = Pattern.rewrite_term thy proj_eqs [] aux_eq;
haftmann@31485
   198
        fun prove_eqs aux_simp proj_defs lthy = 
haftmann@31485
   199
          let
haftmann@31485
   200
            val proj_simps = map (snd o snd) proj_defs;
haftmann@31485
   201
            fun tac { context = ctxt, ... } = ALLGOALS Goal.conjunction_tac
haftmann@31485
   202
              THEN ALLGOALS (simp_tac (HOL_ss addsimps proj_simps))
haftmann@31485
   203
              THEN ALLGOALS (EqSubst.eqsubst_tac ctxt [0] [aux_simp])
haftmann@31485
   204
              THEN ALLGOALS (simp_tac (HOL_ss addsimps [fst_conv, snd_conv]));
haftmann@31485
   205
          in (Goal.prove_multi lthy [v] [] eqs tac, lthy) end;
haftmann@31485
   206
      in
haftmann@31485
   207
        lthy
haftmann@31485
   208
        |> random_aux_primrec aux_eq'
haftmann@31485
   209
        ||>> fold_map (LocalTheory.define Thm.definitionK) proj_defs
haftmann@31485
   210
        |-> (fn (aux_simp, proj_defs) => prove_eqs aux_simp proj_defs)
haftmann@31485
   211
      end;
haftmann@31485
   212
haftmann@31485
   213
fun random_aux_specification prefix eqs lthy =
haftmann@31485
   214
  let
haftmann@31595
   215
    val vs = fold Term.add_free_names ((snd o strip_comb o fst o HOLogic.dest_eq
haftmann@31595
   216
      o HOLogic.dest_Trueprop o hd) eqs) [];
haftmann@31485
   217
    fun mk_proto_eq eq =
haftmann@31485
   218
      let
haftmann@31595
   219
        val (head $ t $ u, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31595
   220
      in ((HOLogic.mk_Trueprop o HOLogic.mk_eq) (head, lambda t (lambda u rhs))) end;
haftmann@31485
   221
    val proto_eqs = map mk_proto_eq eqs;
haftmann@31485
   222
    fun prove_simps proto_simps lthy =
haftmann@31485
   223
      let
haftmann@31595
   224
        val ext_simps = map (fn thm => fun_cong OF [fun_cong OF  [thm]]) proto_simps;
haftmann@31485
   225
        val tac = ALLGOALS Goal.conjunction_tac
haftmann@31485
   226
          THEN ALLGOALS (ProofContext.fact_tac ext_simps);
haftmann@31595
   227
      in (Goal.prove_multi lthy vs [] eqs (K tac), lthy) end;
haftmann@31485
   228
    val b = Binding.qualify true prefix (Binding.name "simps");
haftmann@31485
   229
  in
haftmann@31485
   230
    lthy
haftmann@31485
   231
    |> random_aux_primrec_multi prefix proto_eqs
haftmann@31485
   232
    |-> (fn proto_simps => prove_simps proto_simps)
haftmann@31485
   233
    |-> (fn simps => LocalTheory.note Thm.generatedK ((b,
haftmann@31485
   234
           Code.add_default_eqn_attrib :: map (Attrib.internal o K)
haftmann@31485
   235
          [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add, Quickcheck_RecFun_Simp_Thms.add]),
haftmann@31485
   236
            simps))
haftmann@31485
   237
    |> snd
haftmann@31485
   238
  end
haftmann@31485
   239
haftmann@31485
   240
haftmann@31485
   241
(* constructing random instances on datatypes *)
haftmann@31485
   242
haftmann@31595
   243
fun mk_random_aux_eqs thy descr vs Ts rtyps tycos names =
haftmann@31595
   244
  let
haftmann@31595
   245
    val mk_const = curry (Sign.mk_const thy);
haftmann@31595
   246
    val i = @{term "i\<Colon>code_numeral"};
haftmann@31595
   247
    val i1 = @{term "(i\<Colon>code_numeral) - 1"};
haftmann@31595
   248
    val j = @{term "j\<Colon>code_numeral"};
haftmann@31595
   249
    val seed = @{term "s\<Colon>Random.seed"};
haftmann@31595
   250
    val random_auxN = "random_aux";
haftmann@31595
   251
    val random_auxsN = map (prefix (random_auxN ^ "_"))
haftmann@31595
   252
      (map Long_Name.base_name names @ map DatatypeAux.name_of_typ rtyps);
haftmann@31595
   253
    fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit \<Rightarrow> term"});
haftmann@31595
   254
    val rTs = Ts @ rtyps;
haftmann@31595
   255
    fun random_resultT T = @{typ Random.seed}
haftmann@31595
   256
      --> HOLogic.mk_prodT (termifyT T,@{typ Random.seed});
haftmann@31595
   257
    val pTs = map random_resultT rTs;
haftmann@31595
   258
    fun sizeT T = @{typ code_numeral} --> @{typ code_numeral} --> T;
haftmann@31595
   259
    val random_auxT = sizeT o random_resultT;
haftmann@31595
   260
    val random_auxs = map2 (fn s => fn rT => Free (s, random_auxT rT))
haftmann@31595
   261
      random_auxsN rTs;
haftmann@31595
   262
    fun mk_random_call T = (NONE, (HOLogic.mk_random T j, T));
haftmann@31595
   263
    fun mk_random_aux_call T =
haftmann@31595
   264
      let
haftmann@31595
   265
        val k = find_index (fn T' => T = T') rTs;
haftmann@31595
   266
        val random = nth random_auxs k;
haftmann@31595
   267
        val size = Option.map snd (DatatypeCodegen.find_shortest_path descr k)
haftmann@31595
   268
          |> the_default 0;
haftmann@31595
   269
      in (SOME size, (random $ i1 $ j, T)) end;
haftmann@31595
   270
    fun atom T = mk_random_call T;
haftmann@31595
   271
    fun dtyp tyco = mk_random_aux_call (Type (tyco, map TFree vs));
haftmann@31595
   272
    fun rtyp (tyco, Ts) _ = mk_random_aux_call (Type (tyco, Ts));
haftmann@31595
   273
    val (tss1, tss2) = DatatypePackage.construction_interpretation thy
haftmann@31595
   274
      {atom = atom, dtyp = dtyp, rtyp = rtyp} vs tycos;
haftmann@31595
   275
    fun mk_consexpr simpleT (c, xs) =
haftmann@31595
   276
      let
haftmann@31595
   277
        val (ks, simple_tTs) = split_list xs;
haftmann@31595
   278
        val T = termifyT simpleT;
haftmann@31595
   279
        val tTs = (map o apsnd) termifyT simple_tTs;
haftmann@31595
   280
        val is_rec = exists is_some ks;
haftmann@31595
   281
        val k = fold (fn NONE => I | SOME k => curry Int.max k) ks 0;
haftmann@31595
   282
        val vs = Name.names Name.context "x" (map snd simple_tTs);
haftmann@31595
   283
        val vs' = (map o apsnd) termifyT vs;
haftmann@31595
   284
        val tc = HOLogic.mk_return T @{typ Random.seed}
haftmann@31595
   285
          (HOLogic.mk_valtermify_app c vs simpleT);
haftmann@31595
   286
        val t = HOLogic.mk_ST (map (fn (t, _) => (t, @{typ Random.seed})) tTs ~~ map SOME vs')
haftmann@31595
   287
          tc @{typ Random.seed} (SOME T, @{typ Random.seed});
haftmann@31595
   288
        val tk = if is_rec
haftmann@31595
   289
          then if k = 0 then i
haftmann@31595
   290
            else @{term "Quickcheck.beyond :: code_numeral \<Rightarrow> code_numeral \<Rightarrow> code_numeral"}
haftmann@31595
   291
             $ HOLogic.mk_number @{typ code_numeral} k $ i
haftmann@31595
   292
          else @{term "1::code_numeral"}
haftmann@31595
   293
      in (is_rec, HOLogic.mk_prod (tk, t)) end;
haftmann@31595
   294
    fun sort_rec xs =
haftmann@31595
   295
      map_filter (fn (true, t) => SOME t | _ =>  NONE) xs
haftmann@31595
   296
      @ map_filter (fn (false, t) => SOME t | _ =>  NONE) xs;
haftmann@31595
   297
    val gen_exprss = (map o apfst) (fn tyco => Type (tyco, map TFree vs)) tss1
haftmann@31595
   298
      @ (map o apfst) Type tss2
haftmann@31595
   299
      |> map (fn (T, cs) => (T, (sort_rec o map (mk_consexpr T)) cs));
haftmann@31595
   300
    fun mk_select (rT, xs) =
haftmann@31595
   301
      mk_const @{const_name Quickcheck.collapse} [@{typ "Random.seed"}, termifyT rT]
haftmann@31595
   302
      $ (mk_const @{const_name Random.select_weight} [random_resultT rT]
haftmann@31595
   303
        $ HOLogic.mk_list (HOLogic.mk_prodT (@{typ code_numeral}, random_resultT rT)) xs)
haftmann@31595
   304
          $ seed;
haftmann@31595
   305
    val auxs_lhss = map (fn t => t $ i $ j $ seed) random_auxs;
haftmann@31595
   306
    val auxs_rhss = map mk_select gen_exprss;
haftmann@31595
   307
    val prefix = space_implode "_" (random_auxN :: names);
haftmann@31595
   308
  in (prefix, (random_auxs, auxs_lhss ~~ auxs_rhss)) end;
haftmann@31595
   309
haftmann@31595
   310
fun mk_random_datatype descr vs rtyps tycos names thy =
haftmann@31595
   311
  let
haftmann@31595
   312
    val i = @{term "i\<Colon>code_numeral"};
haftmann@31595
   313
    val mk_prop_eq = HOLogic.mk_Trueprop o HOLogic.mk_eq;
haftmann@31595
   314
    val Ts = map (fn tyco => Type (tyco, map TFree vs)) tycos;
haftmann@31595
   315
    fun mk_size_arg k = case DatatypeCodegen.find_shortest_path descr k
haftmann@31595
   316
     of SOME (_, l) => if l = 0 then i
haftmann@31595
   317
          else @{term "max :: code_numeral \<Rightarrow> code_numeral \<Rightarrow> code_numeral"}
haftmann@31595
   318
            $ HOLogic.mk_number @{typ code_numeral} l $ i
haftmann@31595
   319
      | NONE => i;
haftmann@31595
   320
    val (prefix, (random_auxs, auxs_eqs)) = (apsnd o apsnd o map) mk_prop_eq
haftmann@31595
   321
      (mk_random_aux_eqs thy descr vs Ts rtyps tycos names);
haftmann@31595
   322
    val random_defs = map_index (fn (k, T) => mk_prop_eq
haftmann@31595
   323
      (HOLogic.mk_random T i, nth random_auxs k $ mk_size_arg k $ i)) Ts;
haftmann@31595
   324
  in
haftmann@31595
   325
    thy
haftmann@31595
   326
    |> TheoryTarget.instantiation (tycos, vs, @{sort random})
haftmann@31595
   327
    |> random_aux_specification prefix auxs_eqs
haftmann@31595
   328
    |> `(fn lthy => map (Syntax.check_term lthy) random_defs)
haftmann@31595
   329
    |-> (fn random_defs' => fold_map (fn random_def =>
haftmann@31595
   330
          Specification.definition (NONE, (Attrib.empty_binding,
haftmann@31595
   331
            random_def))) random_defs')
haftmann@31595
   332
    |> snd
haftmann@31595
   333
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@31595
   334
  end;
haftmann@31595
   335
haftmann@31595
   336
fun ensure_random_datatype (raw_tycos as tyco :: _) thy =
haftmann@31595
   337
  let
haftmann@31595
   338
    val pp = Syntax.pp_global thy;
haftmann@31595
   339
    val algebra = Sign.classes_of thy;
haftmann@31595
   340
    val info = DatatypePackage.the_datatype thy tyco;
haftmann@31595
   341
    val descr = #descr info;
haftmann@31595
   342
    val tycos = Library.take (length raw_tycos, descr)
haftmann@31595
   343
      |> map (fn (_, (tyco, dTs, _)) => tyco);
haftmann@31595
   344
    val names = map Long_Name.base_name (the_default tycos (#alt_names info));
haftmann@31595
   345
    val (raw_vs :: _, raw_coss) = (split_list
haftmann@31595
   346
      o map (DatatypePackage.the_datatype_spec thy)) tycos;
haftmann@31595
   347
    val raw_Ts = maps (maps snd) raw_coss;
haftmann@31595
   348
    val vs' = (fold o fold_atyps) (fn TFree (v, _) => insert (op =) v) raw_Ts [];
haftmann@31595
   349
    val vs = map (fn (v, sort) => (v, if member (op =) vs' v
haftmann@31595
   350
      then Sorts.inter_sort algebra (sort, @{sort random}) else sort)) raw_vs;
haftmann@31595
   351
    val rtyps = Library.drop (length tycos, descr)
haftmann@31595
   352
      |> map (fn (_, (tyco, dTs, _)) =>
haftmann@31595
   353
          Type (tyco, map (DatatypeAux.typ_of_dtyp descr vs) dTs));
haftmann@31595
   354
    val sorts = map snd vs;
haftmann@31595
   355
    val constrain = map_atyps
haftmann@31595
   356
      (fn TFree (v, _) => TFree (v, (the o AList.lookup (op =) vs) v));
haftmann@31595
   357
    val Ts = map constrain raw_Ts;
haftmann@31595
   358
    val algebra' = algebra
haftmann@31595
   359
      |> fold (fn tyco => Sorts.add_arities pp
haftmann@31595
   360
           (tyco, map (rpair sorts) @{sort random})) tycos;
haftmann@31595
   361
    val can_inst = forall (fn T =>
haftmann@31595
   362
      Sorts.of_sort algebra' (T, @{sort random})) Ts;
haftmann@31595
   363
    val hast_inst = exists (fn tyco =>
haftmann@31595
   364
      can (Sorts.mg_domain algebra tyco) @{sort random}) tycos;
haftmann@31595
   365
  in if can_inst andalso not hast_inst then (mk_random_datatype descr vs rtyps tycos names thy
haftmann@31595
   366
    (*FIXME ephemeral handles*)
haftmann@31595
   367
    handle e as TERM (msg, ts) => (tracing (cat_lines (msg :: map (Syntax.string_of_term_global thy) ts)); raise e)
haftmann@31595
   368
         | e as TYPE (msg, _, _) =>  (tracing msg; raise e)
haftmann@31595
   369
         | e as ERROR msg =>  (tracing msg; raise e))
haftmann@31595
   370
  else thy end;
haftmann@31260
   371
haftmann@31260
   372
haftmann@31260
   373
(** setup **)
haftmann@31260
   374
haftmann@31260
   375
val setup = Code_Target.extend_target (target, (Code_ML.target_Eval, K I))
haftmann@31260
   376
  #> Quickcheck.add_generator ("code", compile_generator_expr o ProofContext.theory_of)
haftmann@31595
   377
  #> TypecopyPackage.interpretation ensure_random_typecopy
haftmann@31595
   378
  #> DatatypePackage.interpretation ensure_random_datatype;
haftmann@31260
   379
haftmann@31260
   380
end;