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