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