src/HOL/Tools/quickcheck_generators.ML
author haftmann
Mon Jun 08 08:38:53 2009 +0200 (2009-06-08)
changeset 31485 259a3c90016e
parent 31260 4d273d043d59
child 31595 bd2f7211a420
permissions -rw-r--r--
added infrastructure for definitorial construction of 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@31260
    15
  val eval_ref: (unit -> int -> int * int -> term list option * (int * int)) option ref
haftmann@31260
    16
  val setup: theory -> theory
haftmann@31260
    17
end;
haftmann@31260
    18
haftmann@31260
    19
structure Quickcheck_Generators : QUICKCHECK_GENERATORS =
haftmann@31260
    20
struct
haftmann@31260
    21
haftmann@31260
    22
(** building and compiling generator expressions **)
haftmann@31260
    23
haftmann@31260
    24
val eval_ref : (unit -> int -> int * int -> term list option * (int * int)) option ref = ref NONE;
haftmann@31260
    25
haftmann@31260
    26
val target = "Quickcheck";
haftmann@31260
    27
haftmann@31260
    28
fun mk_generator_expr thy prop tys =
haftmann@31260
    29
  let
haftmann@31260
    30
    val bound_max = length tys - 1;
haftmann@31260
    31
    val bounds = map_index (fn (i, ty) =>
haftmann@31260
    32
      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) tys;
haftmann@31260
    33
    val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
haftmann@31260
    34
    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
haftmann@31260
    35
    val check = @{term "If :: bool => term list option => term list option => term list option"}
haftmann@31260
    36
      $ result $ @{term "None :: term list option"} $ (@{term "Some :: term list => term list option "} $ terms);
haftmann@31260
    37
    val return = @{term "Pair :: term list option => Random.seed => term list option * Random.seed"};
haftmann@31260
    38
    fun liftT T sT = sT --> HOLogic.mk_prodT (T, sT);
haftmann@31260
    39
    fun mk_termtyp ty = HOLogic.mk_prodT (ty, @{typ "unit => term"});
haftmann@31260
    40
    fun mk_scomp T1 T2 sT f g = Const (@{const_name scomp},
haftmann@31260
    41
      liftT T1 sT --> (T1 --> liftT T2 sT) --> liftT T2 sT) $ f $ g;
haftmann@31260
    42
    fun mk_split ty = Sign.mk_const thy
haftmann@31260
    43
      (@{const_name split}, [ty, @{typ "unit => term"}, liftT @{typ "term list option"} @{typ Random.seed}]);
haftmann@31260
    44
    fun mk_scomp_split ty t t' =
haftmann@31260
    45
      mk_scomp (mk_termtyp ty) @{typ "term list option"} @{typ Random.seed} t
haftmann@31260
    46
        (mk_split ty $ Abs ("", ty, Abs ("", @{typ "unit => term"}, t')));
haftmann@31260
    47
    fun mk_bindclause (_, _, i, ty) = mk_scomp_split ty
haftmann@31260
    48
      (Sign.mk_const thy (@{const_name random}, [ty]) $ Bound i);
haftmann@31260
    49
  in Abs ("n", @{typ code_numeral}, fold_rev mk_bindclause bounds (return $ check)) end;
haftmann@31260
    50
haftmann@31260
    51
fun compile_generator_expr thy t =
haftmann@31260
    52
  let
haftmann@31260
    53
    val tys = (map snd o fst o strip_abs) t;
haftmann@31260
    54
    val t' = mk_generator_expr thy t tys;
haftmann@31260
    55
    val f = Code_ML.eval (SOME target) ("Quickcheck_Generators.eval_ref", eval_ref)
haftmann@31260
    56
      (fn proc => fn g => fn s => g s #>> (Option.map o map) proc) thy t' [];
haftmann@31260
    57
  in f #> Random_Engine.run end;
haftmann@31260
    58
haftmann@31260
    59
haftmann@31260
    60
(** typ "'a => 'b" **)
haftmann@31260
    61
haftmann@31260
    62
type seed = Random_Engine.seed;
haftmann@31260
    63
haftmann@31260
    64
fun random_fun (T1 : typ) (T2 : typ) (eq : 'a -> 'a -> bool) (term_of : 'a -> term)
haftmann@31260
    65
    (random : seed -> ('b * (unit -> term)) * seed)
haftmann@31260
    66
    (random_split : seed -> seed * seed)
haftmann@31260
    67
    (seed : seed) =
haftmann@31260
    68
  let
haftmann@31260
    69
    val (seed', seed'') = random_split seed;
haftmann@31260
    70
    val state = ref (seed', [], Const (@{const_name undefined}, T1 --> T2));
haftmann@31260
    71
    val fun_upd = Const (@{const_name fun_upd},
haftmann@31260
    72
      (T1 --> T2) --> T1 --> T2 --> T1 --> T2);
haftmann@31260
    73
    fun random_fun' x =
haftmann@31260
    74
      let
haftmann@31260
    75
        val (seed, fun_map, f_t) = ! state;
haftmann@31260
    76
      in case AList.lookup (uncurry eq) fun_map x
haftmann@31260
    77
       of SOME y => y
haftmann@31260
    78
        | NONE => let
haftmann@31260
    79
              val t1 = term_of x;
haftmann@31260
    80
              val ((y, t2), seed') = random seed;
haftmann@31260
    81
              val fun_map' = (x, y) :: fun_map;
haftmann@31260
    82
              val f_t' = fun_upd $ f_t $ t1 $ t2 ();
haftmann@31260
    83
              val _ = state := (seed', fun_map', f_t');
haftmann@31260
    84
            in y end
haftmann@31260
    85
      end;
haftmann@31260
    86
    fun term_fun' () = #3 (! state);
haftmann@31260
    87
  in ((random_fun', term_fun'), seed'') end;
haftmann@31260
    88
haftmann@31260
    89
haftmann@31260
    90
(** type copies **)
haftmann@31260
    91
haftmann@31260
    92
fun mk_random_typecopy tyco vs constr typ thy =
haftmann@31260
    93
  let
haftmann@31260
    94
    val Ts = map TFree vs;  
haftmann@31260
    95
    val T = Type (tyco, Ts);
haftmann@31260
    96
    fun mk_termifyT T = HOLogic.mk_prodT (T, @{typ "unit => term"})
haftmann@31260
    97
    val Ttm = mk_termifyT T;
haftmann@31260
    98
    val typtm = mk_termifyT typ;
haftmann@31260
    99
    fun mk_const c Ts = Const (c, Sign.const_instance thy (c, Ts));
haftmann@31260
   100
    fun mk_random T = mk_const @{const_name random} [T];
haftmann@31260
   101
    val size = @{term "j::code_numeral"};
haftmann@31260
   102
    val v = "x";
haftmann@31260
   103
    val t_v = Free (v, typtm);
haftmann@31260
   104
    val t_constr = mk_const constr Ts;
haftmann@31260
   105
    val lhs = mk_random T $ size;
haftmann@31260
   106
    val rhs = HOLogic.mk_ST [(((mk_random typ) $ size, @{typ Random.seed}), SOME (v, typtm))]
haftmann@31260
   107
      (HOLogic.mk_return Ttm @{typ Random.seed}
haftmann@31260
   108
      (mk_const "Code_Eval.valapp" [typ, T]
haftmann@31260
   109
        $ HOLogic.mk_prod (t_constr, Abs ("u", @{typ unit}, HOLogic.reflect_term t_constr)) $ t_v))
haftmann@31260
   110
      @{typ Random.seed} (SOME Ttm, @{typ Random.seed});
haftmann@31260
   111
    val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
haftmann@31260
   112
  in   
haftmann@31260
   113
    thy
haftmann@31260
   114
    |> TheoryTarget.instantiation ([tyco], vs, @{sort random})
haftmann@31260
   115
    |> `(fn lthy => Syntax.check_term lthy eq)
haftmann@31260
   116
    |-> (fn eq => Specification.definition (NONE, (Attrib.empty_binding, eq)))
haftmann@31260
   117
    |> snd
haftmann@31260
   118
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@31260
   119
  end;
haftmann@31260
   120
haftmann@31260
   121
fun ensure_random_typecopy tyco thy =
haftmann@31260
   122
  let
haftmann@31260
   123
    val SOME { vs = raw_vs, constr, typ = raw_typ, ... } =
haftmann@31260
   124
      TypecopyPackage.get_info thy tyco;
haftmann@31260
   125
    val constrain = curry (Sorts.inter_sort (Sign.classes_of thy));
haftmann@31260
   126
    val typ = map_atyps (fn TFree (v, sort) =>
haftmann@31260
   127
      TFree (v, constrain sort @{sort random})) raw_typ;
haftmann@31260
   128
    val vs' = Term.add_tfreesT typ [];
haftmann@31260
   129
    val vs = map (fn (v, sort) =>
haftmann@31260
   130
      (v, the_default (constrain sort @{sort typerep}) (AList.lookup (op =) vs' v))) raw_vs;
haftmann@31260
   131
    val do_inst = Sign.of_sort thy (typ, @{sort random});
haftmann@31260
   132
  in if do_inst then mk_random_typecopy tyco vs constr typ thy else thy end;
haftmann@31260
   133
haftmann@31260
   134
haftmann@31260
   135
(** datatypes **)
haftmann@31260
   136
haftmann@31485
   137
(* definitional scheme for random instances on datatypes *)
haftmann@31485
   138
haftmann@31485
   139
(*FIXME avoid this low-level proving*)
haftmann@31485
   140
val rct = Thm.cprop_of @{thm random_aux_rec} |> Thm.dest_arg |> Thm.dest_arg
haftmann@31485
   141
  |> Thm.dest_arg |> Thm.dest_arg1 |> Thm.dest_fun;
haftmann@31485
   142
fun dest_ctyp_nth k cT = nth (Thm.dest_ctyp cT) k;
haftmann@31485
   143
val aT = rct |> Thm.ctyp_of_term |> dest_ctyp_nth 1;
haftmann@31485
   144
haftmann@31485
   145
fun random_aux_primrec eq lthy =
haftmann@31485
   146
  let
haftmann@31485
   147
    val thy = ProofContext.theory_of lthy;
haftmann@31485
   148
    val rews = map mk_meta_eq [@{thm code_numeral_zero_minus_one},
haftmann@31485
   149
      @{thm Suc_code_numeral_minus_one}, @{thm select_weight_cons_zero}, @{thm beyond_zero}];
haftmann@31485
   150
    val (rt as Free (random_aux, T)) $ (vt as Free (v, _)) =
haftmann@31485
   151
      (fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31485
   152
    val Type (_, [_, iT]) = T;
haftmann@31485
   153
    val icT = Thm.ctyp_of thy iT;
haftmann@31485
   154
    fun subst_v t' = map_aterms (fn t as Free (w, _) => if v = w then t' else t | t => t);
haftmann@31485
   155
    val eqs0 = [subst_v @{term "0::code_numeral"} eq, subst_v (@{term "Suc_code_numeral"} $ vt) eq];
haftmann@31485
   156
    val eqs1 = map (Pattern.rewrite_term thy (map (Logic.dest_equals o Thm.prop_of) rews) []) eqs0
haftmann@31485
   157
    val ((_, eqs2), lthy') = PrimrecPackage.add_primrec_simple
haftmann@31485
   158
      [((Binding.name random_aux, T), NoSyn)] eqs1 lthy;
haftmann@31485
   159
    val eq_tac = ALLGOALS Goal.conjunction_tac THEN ALLGOALS (simp_tac (HOL_ss addsimps rews))
haftmann@31485
   160
      THEN (ALLGOALS (ProofContext.fact_tac (flat eqs2)));
haftmann@31485
   161
    val eqs3 = Goal.prove_multi lthy' [v] [] eqs0 (K eq_tac);
haftmann@31485
   162
    val rct' = Thm.instantiate_cterm ([(aT, icT)], []) rct
haftmann@31485
   163
    val rule = @{thm random_aux_rec}
haftmann@31485
   164
      |> Drule.instantiate ([(aT, icT)], [(rct', Thm.cterm_of thy rt)])
haftmann@31485
   165
      |> (fn thm => thm OF eqs3)
haftmann@31485
   166
    val tac = ALLGOALS (rtac rule);
haftmann@31485
   167
    val simp = Goal.prove lthy' [v] [] eq (K tac);
haftmann@31485
   168
  in (simp, lthy') end;
haftmann@31485
   169
haftmann@31485
   170
fun random_aux_primrec_multi prefix [eq] lthy =
haftmann@31485
   171
      lthy
haftmann@31485
   172
      |> random_aux_primrec eq
haftmann@31485
   173
      |>> (fn simp => [simp])
haftmann@31485
   174
  | random_aux_primrec_multi prefix (eqs as _ :: _ :: _) lthy =
haftmann@31485
   175
      let
haftmann@31485
   176
        val thy = ProofContext.theory_of lthy;
haftmann@31485
   177
        val (lhss, rhss) = map_split (HOLogic.dest_eq o HOLogic.dest_Trueprop) eqs;
haftmann@31485
   178
        val (vs, (arg as Free (v, _)) :: _) = map_split (fn (t1 $ t2) => (t1, t2)) lhss;
haftmann@31485
   179
        val Ts = map fastype_of lhss;
haftmann@31485
   180
        val tupleT = foldr1 HOLogic.mk_prodT Ts;
haftmann@31485
   181
        val aux_lhs = Free ("mutual_" ^ prefix, fastype_of arg --> tupleT) $ arg;
haftmann@31485
   182
        val aux_eq = (HOLogic.mk_Trueprop o HOLogic.mk_eq)
haftmann@31485
   183
          (aux_lhs, foldr1 HOLogic.mk_prod rhss);
haftmann@31485
   184
        fun mk_proj t [T] = [t]
haftmann@31485
   185
          | mk_proj t (Ts as T :: (Ts' as _ :: _)) =
haftmann@31485
   186
              Const (@{const_name fst}, foldr1 HOLogic.mk_prodT Ts --> T) $ t
haftmann@31485
   187
                :: mk_proj (Const (@{const_name snd},
haftmann@31485
   188
                  foldr1 HOLogic.mk_prodT Ts --> foldr1 HOLogic.mk_prodT Ts') $ t) Ts';
haftmann@31485
   189
        val projs = mk_proj (aux_lhs) Ts;
haftmann@31485
   190
        val proj_eqs = map2 (fn v => fn proj => (v, lambda arg proj)) vs projs;
haftmann@31485
   191
        val proj_defs = map2 (fn Free (name, _) => fn (_, rhs) =>
haftmann@31485
   192
          ((Binding.name name, NoSyn), (Attrib.empty_binding, rhs))) vs proj_eqs;
haftmann@31485
   193
        val aux_eq' = Pattern.rewrite_term thy proj_eqs [] aux_eq;
haftmann@31485
   194
        fun prove_eqs aux_simp proj_defs lthy = 
haftmann@31485
   195
          let
haftmann@31485
   196
            val proj_simps = map (snd o snd) proj_defs;
haftmann@31485
   197
            fun tac { context = ctxt, ... } = ALLGOALS Goal.conjunction_tac
haftmann@31485
   198
              THEN ALLGOALS (simp_tac (HOL_ss addsimps proj_simps))
haftmann@31485
   199
              THEN ALLGOALS (EqSubst.eqsubst_tac ctxt [0] [aux_simp])
haftmann@31485
   200
              THEN ALLGOALS (simp_tac (HOL_ss addsimps [fst_conv, snd_conv]));
haftmann@31485
   201
          in (Goal.prove_multi lthy [v] [] eqs tac, lthy) end;
haftmann@31485
   202
      in
haftmann@31485
   203
        lthy
haftmann@31485
   204
        |> random_aux_primrec aux_eq'
haftmann@31485
   205
        ||>> fold_map (LocalTheory.define Thm.definitionK) proj_defs
haftmann@31485
   206
        |-> (fn (aux_simp, proj_defs) => prove_eqs aux_simp proj_defs)
haftmann@31485
   207
      end;
haftmann@31485
   208
haftmann@31485
   209
fun random_aux_specification prefix eqs lthy =
haftmann@31485
   210
  let
haftmann@31485
   211
    val _ $ Free (v, _) $ Free (w, _) =
haftmann@31485
   212
      (fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o hd) eqs;
haftmann@31485
   213
    fun mk_proto_eq eq =
haftmann@31485
   214
      let
haftmann@31485
   215
        val (head $ arg, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop) eq;
haftmann@31485
   216
      in ((HOLogic.mk_Trueprop o HOLogic.mk_eq) (head, lambda arg rhs)) end;
haftmann@31485
   217
    val proto_eqs = map mk_proto_eq eqs;
haftmann@31485
   218
    fun prove_simps proto_simps lthy =
haftmann@31485
   219
      let
haftmann@31485
   220
        val ext_simps = map (fn thm => fun_cong OF [thm]) proto_simps;
haftmann@31485
   221
        val tac = ALLGOALS Goal.conjunction_tac
haftmann@31485
   222
          THEN ALLGOALS (ProofContext.fact_tac ext_simps);
haftmann@31485
   223
      in (Goal.prove_multi lthy [v, w] [] eqs (K tac), lthy) end;
haftmann@31485
   224
    val b = Binding.qualify true prefix (Binding.name "simps");
haftmann@31485
   225
  in
haftmann@31485
   226
    lthy
haftmann@31485
   227
    |> random_aux_primrec_multi prefix proto_eqs
haftmann@31485
   228
    |-> (fn proto_simps => prove_simps proto_simps)
haftmann@31485
   229
    |-> (fn simps => LocalTheory.note Thm.generatedK ((b,
haftmann@31485
   230
           Code.add_default_eqn_attrib :: map (Attrib.internal o K)
haftmann@31485
   231
          [Simplifier.simp_add, Nitpick_Const_Simp_Thms.add, Quickcheck_RecFun_Simp_Thms.add]),
haftmann@31485
   232
            simps))
haftmann@31485
   233
    |> snd
haftmann@31485
   234
  end
haftmann@31485
   235
haftmann@31485
   236
haftmann@31485
   237
(* constructing random instances on datatypes *)
haftmann@31485
   238
haftmann@31485
   239
(*still under construction*)
haftmann@31260
   240
haftmann@31260
   241
haftmann@31260
   242
(** setup **)
haftmann@31260
   243
haftmann@31260
   244
val setup = Code_Target.extend_target (target, (Code_ML.target_Eval, K I))
haftmann@31260
   245
  #> Quickcheck.add_generator ("code", compile_generator_expr o ProofContext.theory_of)
haftmann@31260
   246
  #> TypecopyPackage.interpretation ensure_random_typecopy;
haftmann@31260
   247
haftmann@31260
   248
end;