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