src/HOL/Tools/Quickcheck/exhaustive_generators.ML
author bulwahn
Mon Dec 05 12:36:20 2011 +0100 (2011-12-05)
changeset 45763 3bb2bdf654f7
parent 45761 90028fd2f1fa
child 45923 473b744c23f2
permissions -rw-r--r--
random reporting compilation returns if counterexample is genuine or potentially spurious, and takes genuine_only option as argument
bulwahn@41923
     1
(*  Title:      HOL/Tools/Quickcheck/exhaustive_generators.ML
bulwahn@40420
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@40420
     3
bulwahn@41918
     4
Exhaustive generators for various types.
bulwahn@40420
     5
*)
bulwahn@40420
     6
bulwahn@41918
     7
signature EXHAUSTIVE_GENERATORS =
bulwahn@40420
     8
sig
bulwahn@40420
     9
  val compile_generator_expr:
bulwahn@45754
    10
    Proof.context -> (term * term list) list -> bool -> int list -> (bool * term list) option * Quickcheck.report option
bulwahn@42159
    11
  val compile_generator_exprs: Proof.context -> term list -> (int -> term list option) list
bulwahn@42195
    12
  val compile_validator_exprs: Proof.context -> term list -> (int -> bool) list
bulwahn@45754
    13
  val put_counterexample: (unit -> int -> bool -> int -> (bool * term list) option)
bulwahn@40420
    14
    -> Proof.context -> Proof.context
bulwahn@41861
    15
  val put_counterexample_batch: (unit -> (int -> term list option) list)
bulwahn@41861
    16
    -> Proof.context -> Proof.context
bulwahn@42195
    17
  val put_validator_batch: (unit -> (int -> bool) list) -> Proof.context -> Proof.context
bulwahn@42306
    18
  exception Counterexample of term list
bulwahn@42195
    19
  val smart_quantifier : bool Config.T
bulwahn@42195
    20
  val quickcheck_pretty : bool Config.T
bulwahn@45484
    21
  val setup_exhaustive_datatype_interpretation : theory -> theory
bulwahn@40420
    22
  val setup: theory -> theory
bulwahn@40420
    23
end;
bulwahn@40420
    24
bulwahn@41918
    25
structure Exhaustive_Generators : EXHAUSTIVE_GENERATORS =
bulwahn@40420
    26
struct
bulwahn@40420
    27
bulwahn@42308
    28
(* basics *)
bulwahn@42308
    29
bulwahn@42308
    30
(** dynamic options **)
bulwahn@40907
    31
wenzelm@42616
    32
val smart_quantifier = Attrib.setup_config_bool @{binding quickcheck_smart_quantifier} (K true)
wenzelm@42616
    33
val fast = Attrib.setup_config_bool @{binding quickcheck_fast} (K false)
wenzelm@42616
    34
val bounded_forall = Attrib.setup_config_bool @{binding quickcheck_bounded_forall} (K false)
wenzelm@42616
    35
val full_support = Attrib.setup_config_bool @{binding quickcheck_full_support} (K true)
wenzelm@42616
    36
val quickcheck_pretty = Attrib.setup_config_bool @{binding quickcheck_pretty} (K true)
bulwahn@41903
    37
 
bulwahn@40420
    38
(** general term functions **)
bulwahn@40420
    39
bulwahn@40420
    40
fun mk_measure f =
bulwahn@40420
    41
  let
bulwahn@40420
    42
    val Type ("fun", [T, @{typ nat}]) = fastype_of f 
bulwahn@40420
    43
  in
bulwahn@40420
    44
    Const (@{const_name Wellfounded.measure},
bulwahn@40420
    45
      (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
bulwahn@40420
    46
    $ f
bulwahn@40420
    47
  end
bulwahn@40420
    48
bulwahn@40420
    49
fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
bulwahn@40420
    50
  let
bulwahn@40420
    51
    val lt = mk_sumcases rT f TL
bulwahn@40420
    52
    val rt = mk_sumcases rT f TR
bulwahn@40420
    53
  in
bulwahn@40420
    54
    SumTree.mk_sumcase TL TR rT lt rt
bulwahn@40420
    55
  end
bulwahn@40420
    56
  | mk_sumcases _ f T = f T
bulwahn@40420
    57
bulwahn@40420
    58
(** abstract syntax **)
bulwahn@40420
    59
bulwahn@40639
    60
fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => Code_Evaluation.term"});
bulwahn@40639
    61
bulwahn@40420
    62
val size = @{term "i :: code_numeral"}
bulwahn@40420
    63
val size_pred = @{term "(i :: code_numeral) - 1"}
bulwahn@40420
    64
val size_ge_zero = @{term "(i :: code_numeral) > 0"}
bulwahn@42304
    65
bulwahn@40420
    66
fun mk_none_continuation (x, y) =
bulwahn@40420
    67
  let
bulwahn@40420
    68
    val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
bulwahn@40420
    69
  in
bulwahn@42214
    70
    Const (@{const_name "Quickcheck_Exhaustive.orelse"}, T --> T --> T) $ x $ y
bulwahn@40420
    71
  end
bulwahn@40420
    72
bulwahn@42306
    73
fun mk_unit_let (x, y) =
wenzelm@44241
    74
  Const (@{const_name "Let"}, @{typ "unit => (unit => unit) => unit"}) $ x $ absdummy @{typ unit} y
bulwahn@45721
    75
bulwahn@45721
    76
fun mk_if (b, t, e) =
bulwahn@45721
    77
  let
bulwahn@45721
    78
    val T = fastype_of t
bulwahn@45721
    79
  in Const (@{const_name "HOL.If"}, @{typ bool} --> T --> T --> T) $ b $ t $ e end
bulwahn@45721
    80
bulwahn@42308
    81
(* handling inductive datatypes *)
bulwahn@40420
    82
bulwahn@42308
    83
(** constructing generator instances **)
bulwahn@40420
    84
bulwahn@40420
    85
exception FUNCTION_TYPE;
bulwahn@42306
    86
bulwahn@42306
    87
exception Counterexample of term list
bulwahn@42306
    88
bulwahn@45722
    89
val resultT =  @{typ "(bool * term list) option"};
bulwahn@45722
    90
bulwahn@41918
    91
val exhaustiveN = "exhaustive";
bulwahn@42304
    92
val full_exhaustiveN = "full_exhaustive";
bulwahn@42306
    93
val fast_exhaustiveN = "fast_exhaustive";
bulwahn@42308
    94
val bounded_forallN = "bounded_forall";
bulwahn@42306
    95
bulwahn@42306
    96
fun fast_exhaustiveT T = (T --> @{typ unit})
bulwahn@42306
    97
  --> @{typ code_numeral} --> @{typ unit}
bulwahn@42306
    98
bulwahn@45724
    99
fun exhaustiveT T = (T --> resultT) --> @{typ code_numeral} --> resultT
bulwahn@42304
   100
bulwahn@42308
   101
fun bounded_forallT T = (T --> @{typ bool}) --> @{typ code_numeral} --> @{typ bool}
bulwahn@42308
   102
bulwahn@45722
   103
fun full_exhaustiveT T = (termifyT T --> resultT) --> @{typ code_numeral} --> resultT
bulwahn@41085
   104
bulwahn@45722
   105
fun check_allT T = (termifyT T --> resultT) --> resultT
bulwahn@41085
   106
bulwahn@42307
   107
fun mk_equation_terms generics (descr, vs, Ts) =
bulwahn@42307
   108
  let
bulwahn@42307
   109
    val (mk_call, mk_aux_call, mk_consexpr, mk_rhs, test_function, exhaustives) = generics
bulwahn@42307
   110
    val rhss =
bulwahn@42307
   111
      Datatype_Aux.interpret_construction descr vs
bulwahn@42307
   112
        { atyp = mk_call, dtyp = mk_aux_call }
bulwahn@42307
   113
      |> (map o apfst) Type
bulwahn@42307
   114
      |> map (fn (T, cs) => map (mk_consexpr T) cs)
bulwahn@42307
   115
      |> map mk_rhs
bulwahn@42307
   116
    val lhss = map2 (fn t => fn T => t $ test_function T $ size) exhaustives Ts
bulwahn@42307
   117
  in
bulwahn@42307
   118
    map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
bulwahn@42307
   119
  end
bulwahn@42306
   120
wenzelm@44241
   121
fun gen_mk_call c T =  (T, fn t => c T $ absdummy T t $ size_pred)
bulwahn@42308
   122
bulwahn@42308
   123
fun gen_mk_aux_call functerms fTs (k, _) (tyco, Ts) =
bulwahn@42308
   124
  let
bulwahn@42308
   125
    val T = Type (tyco, Ts)
bulwahn@42308
   126
    val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
bulwahn@42308
   127
  in
wenzelm@44241
   128
   (T, fn t => nth functerms k $ absdummy T t $ size_pred)
bulwahn@42308
   129
  end
bulwahn@42308
   130
bulwahn@42308
   131
fun gen_mk_consexpr test_function functerms simpleT (c, xs) =
bulwahn@42308
   132
  let
bulwahn@42308
   133
    val (Ts, fns) = split_list xs
bulwahn@42308
   134
    val constr = Const (c, Ts ---> simpleT)
bulwahn@42308
   135
    val bounds = map Bound (((length xs) - 1) downto 0)
bulwahn@42308
   136
    val term_bounds = map (fn x => Bound (2 * x)) (((length xs) - 1) downto 0)
bulwahn@42308
   137
    val start_term = test_function simpleT $ list_comb (constr, bounds)
bulwahn@42308
   138
  in fold_rev (fn f => fn t => f t) fns start_term end
bulwahn@42308
   139
      
bulwahn@42307
   140
fun mk_fast_equations functerms =
bulwahn@42306
   141
  let
bulwahn@42307
   142
    fun test_function T = Free ("f", T --> @{typ "unit"})
bulwahn@42308
   143
    val mk_call = gen_mk_call (fn T =>
bulwahn@42308
   144
      Const (@{const_name "Quickcheck_Exhaustive.fast_exhaustive_class.fast_exhaustive"},
bulwahn@42308
   145
        fast_exhaustiveT T))
bulwahn@42308
   146
    val mk_aux_call = gen_mk_aux_call functerms
bulwahn@42308
   147
    val mk_consexpr = gen_mk_consexpr test_function functerms
bulwahn@42307
   148
    fun mk_rhs exprs = @{term "If :: bool => unit => unit => unit"}
bulwahn@42307
   149
        $ size_ge_zero $ (foldr1 mk_unit_let exprs) $ @{term "()"}
bulwahn@42306
   150
  in
bulwahn@42307
   151
    mk_equation_terms (mk_call, mk_aux_call, mk_consexpr, mk_rhs, test_function, functerms)
bulwahn@42306
   152
  end
bulwahn@42307
   153
bulwahn@42307
   154
fun mk_equations functerms =
bulwahn@40420
   155
  let
bulwahn@45724
   156
    fun test_function T = Free ("f", T --> resultT)
bulwahn@42308
   157
    val mk_call = gen_mk_call (fn T =>
bulwahn@42308
   158
      Const (@{const_name "Quickcheck_Exhaustive.exhaustive_class.exhaustive"}, exhaustiveT T))
bulwahn@42308
   159
    val mk_aux_call = gen_mk_aux_call functerms
bulwahn@42308
   160
    val mk_consexpr = gen_mk_consexpr test_function functerms
bulwahn@42304
   161
    fun mk_rhs exprs =
bulwahn@45724
   162
      mk_if (size_ge_zero, foldr1 mk_none_continuation exprs, Const (@{const_name "None"}, resultT))
bulwahn@42304
   163
  in
bulwahn@42307
   164
    mk_equation_terms (mk_call, mk_aux_call, mk_consexpr, mk_rhs, test_function, functerms)
bulwahn@42304
   165
  end
bulwahn@42308
   166
bulwahn@42308
   167
fun mk_bounded_forall_equations functerms =
bulwahn@42308
   168
  let
bulwahn@42308
   169
    fun test_function T = Free ("P", T --> @{typ bool})
bulwahn@42308
   170
    val mk_call = gen_mk_call (fn T =>
bulwahn@42308
   171
      Const (@{const_name "Quickcheck_Exhaustive.bounded_forall_class.bounded_forall"},
bulwahn@42308
   172
        bounded_forallT T))
bulwahn@42308
   173
    val mk_aux_call = gen_mk_aux_call functerms
bulwahn@42308
   174
    val mk_consexpr = gen_mk_consexpr test_function functerms
bulwahn@42308
   175
    fun mk_rhs exprs =
bulwahn@45721
   176
      mk_if (size_ge_zero, foldr1 HOLogic.mk_conj exprs, @{term "True"})
bulwahn@42308
   177
  in
bulwahn@42308
   178
    mk_equation_terms (mk_call, mk_aux_call, mk_consexpr, mk_rhs, test_function, functerms)
bulwahn@42308
   179
  end
bulwahn@42308
   180
  
bulwahn@42307
   181
fun mk_full_equations functerms =
bulwahn@42304
   182
  let
bulwahn@45722
   183
    fun test_function T = Free ("f", termifyT T --> resultT)
bulwahn@45722
   184
    fun split_const T = HOLogic.split_const (T, @{typ "unit => Code_Evaluation.term"}, resultT)
bulwahn@42304
   185
    fun mk_call T =
bulwahn@42304
   186
      let
bulwahn@42307
   187
        val full_exhaustive =
bulwahn@42310
   188
          Const (@{const_name "Quickcheck_Exhaustive.full_exhaustive_class.full_exhaustive"},
bulwahn@42308
   189
            full_exhaustiveT T)
bulwahn@45721
   190
      in                                   
wenzelm@44241
   191
        (T, fn t => full_exhaustive $
bulwahn@45722
   192
          (split_const T $ absdummy T (absdummy @{typ "unit => Code_Evaluation.term"} t)) $ size_pred)
bulwahn@40420
   193
      end
bulwahn@41918
   194
    fun mk_aux_call fTs (k, _) (tyco, Ts) =
bulwahn@40420
   195
      let
bulwahn@40420
   196
        val T = Type (tyco, Ts)
bulwahn@40420
   197
        val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
bulwahn@40420
   198
      in
wenzelm@44241
   199
        (T, fn t => nth functerms k $
bulwahn@45722
   200
          (split_const T $ absdummy T (absdummy @{typ "unit => Code_Evaluation.term"} t)) $ size_pred)
bulwahn@40420
   201
      end
bulwahn@40420
   202
    fun mk_consexpr simpleT (c, xs) =
bulwahn@40420
   203
      let
bulwahn@40420
   204
        val (Ts, fns) = split_list xs
bulwahn@40420
   205
        val constr = Const (c, Ts ---> simpleT)
bulwahn@40639
   206
        val bounds = map (fn x => Bound (2 * x + 1)) (((length xs) - 1) downto 0)
bulwahn@40639
   207
        val term_bounds = map (fn x => Bound (2 * x)) (((length xs) - 1) downto 0)
bulwahn@40639
   208
        val Eval_App = Const ("Code_Evaluation.App", HOLogic.termT --> HOLogic.termT --> HOLogic.termT)
bulwahn@40639
   209
        val Eval_Const = Const ("Code_Evaluation.Const", HOLogic.literalT --> @{typ typerep} --> HOLogic.termT)
bulwahn@40639
   210
        val term = fold (fn u => fn t => Eval_App $ t $ (u $ @{term "()"}))
bulwahn@40639
   211
          bounds (Eval_Const $ HOLogic.mk_literal c $ HOLogic.mk_typerep (Ts ---> simpleT))
bulwahn@42307
   212
        val start_term = test_function simpleT $ 
bulwahn@40639
   213
        (HOLogic.pair_const simpleT @{typ "unit => Code_Evaluation.term"}
wenzelm@44241
   214
          $ (list_comb (constr, bounds)) $ absdummy @{typ unit} term)
bulwahn@40420
   215
      in fold_rev (fn f => fn t => f t) fns start_term end
bulwahn@40420
   216
    fun mk_rhs exprs =
bulwahn@45721
   217
      mk_if (size_ge_zero, foldr1 mk_none_continuation exprs,
bulwahn@45722
   218
        Const (@{const_name "None"}, resultT))
bulwahn@40420
   219
  in
bulwahn@42307
   220
    mk_equation_terms (mk_call, mk_aux_call, mk_consexpr, mk_rhs, test_function, functerms)
bulwahn@40901
   221
  end
bulwahn@42307
   222
  
bulwahn@42308
   223
(** foundational definition with the function package **)
bulwahn@40901
   224
bulwahn@40901
   225
val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
bulwahn@40901
   226
bulwahn@40901
   227
fun mk_single_measure T = HOLogic.mk_comp (@{term "Code_Numeral.nat_of"},
bulwahn@40901
   228
    Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
bulwahn@40901
   229
bulwahn@40901
   230
fun mk_termination_measure T =
bulwahn@40901
   231
  let
bulwahn@40901
   232
    val T' = fst (HOLogic.dest_prodT (HOLogic.dest_setT T))
bulwahn@40901
   233
  in
bulwahn@40901
   234
    mk_measure (mk_sumcases @{typ nat} mk_single_measure T')
bulwahn@40420
   235
  end
bulwahn@40901
   236
bulwahn@40901
   237
fun termination_tac ctxt = 
bulwahn@40901
   238
  Function_Relation.relation_tac ctxt mk_termination_measure 1
bulwahn@40901
   239
  THEN rtac @{thm wf_measure} 1
bulwahn@40901
   240
  THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
bulwahn@40901
   241
    (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
bulwahn@40901
   242
     @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
bulwahn@40901
   243
bulwahn@42308
   244
(** instantiating generator classes **)
bulwahn@42315
   245
  
wenzelm@42325
   246
fun contains_recursive_type_under_function_types xs =
bulwahn@42312
   247
  exists (fn (_, (_, _, cs)) => cs |> exists (snd #> exists (fn dT =>
wenzelm@42325
   248
    (case Datatype_Aux.strip_dtyp dT of (_ :: _, Datatype.DtRec _) => true | _ => false)))) xs
bulwahn@42312
   249
    
bulwahn@42315
   250
fun instantiate_datatype (name, constprfx, sort, mk_equations, mk_T, argnames)
bulwahn@42315
   251
    config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
bulwahn@42312
   252
  if not (contains_recursive_type_under_function_types descr) then
bulwahn@42312
   253
    let
bulwahn@42315
   254
      val _ = Datatype_Aux.message config ("Creating " ^ name ^ "...")
bulwahn@42315
   255
      val fullnames = map (prefix (constprfx ^ "_")) (names @ auxnames)
bulwahn@42312
   256
    in
bulwahn@42312
   257
      thy
bulwahn@42315
   258
      |> Class.instantiation (tycos, vs, sort)
bulwahn@42312
   259
      |> Quickcheck_Common.define_functions
bulwahn@42315
   260
          (fn functerms => mk_equations functerms (descr, vs, Ts @ Us), NONE)
bulwahn@42315
   261
          prfx argnames fullnames (map mk_T (Ts @ Us))
bulwahn@42312
   262
      |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
bulwahn@42312
   263
    end
bulwahn@42312
   264
  else
bulwahn@42230
   265
    (Datatype_Aux.message config
bulwahn@42315
   266
      ("Creation of " ^ name ^ " failed because the datatype is recursive under a function type");
bulwahn@42230
   267
    thy)
bulwahn@42315
   268
bulwahn@42315
   269
val instantiate_bounded_forall_datatype = instantiate_datatype
bulwahn@42315
   270
 ("bounded universal quantifiers", bounded_forallN, @{sort bounded_forall},
bulwahn@42315
   271
   mk_bounded_forall_equations, bounded_forallT, ["P", "i"]);
bulwahn@42315
   272
bulwahn@42315
   273
val instantiate_fast_exhaustive_datatype = instantiate_datatype 
bulwahn@42315
   274
 ("fast exhaustive generators", fast_exhaustiveN, @{sort fast_exhaustive},
bulwahn@42315
   275
   mk_fast_equations, fast_exhaustiveT, ["f", "i"])
bulwahn@42315
   276
bulwahn@42315
   277
val instantiate_exhaustive_datatype = instantiate_datatype  
bulwahn@42390
   278
  ("exhaustive generators", exhaustiveN, @{sort exhaustive},
bulwahn@42390
   279
    mk_equations, exhaustiveT, ["f", "i"])
bulwahn@42315
   280
bulwahn@42315
   281
val instantiate_full_exhaustive_datatype = instantiate_datatype
bulwahn@42315
   282
  ("full exhaustive generators", full_exhaustiveN, @{sort full_exhaustive},
bulwahn@42390
   283
    mk_full_equations, full_exhaustiveT, ["f", "i"])
bulwahn@42390
   284
bulwahn@42308
   285
(* building and compiling generator expressions *)
bulwahn@40420
   286
bulwahn@42390
   287
bulwahn@42390
   288
fun mk_test_term lookup mk_closure mk_if none_t return ctxt =
bulwahn@42306
   289
  let
bulwahn@42306
   290
    fun mk_naive_test_term t =
bulwahn@45721
   291
      fold_rev mk_closure (map lookup (Term.add_free_names t []))
bulwahn@45761
   292
        (mk_if (t, none_t, return) true)
bulwahn@45721
   293
    fun mk_smart_test_term' concl bound_vars assms genuine =
bulwahn@42306
   294
      let
bulwahn@42306
   295
        fun vars_of t = subtract (op =) bound_vars (Term.add_free_names t [])
bulwahn@42306
   296
        val (vars, check) =
bulwahn@42306
   297
          case assms of [] => (vars_of concl, (concl, none_t, return))
bulwahn@45683
   298
            | assm :: assms => (vars_of assm, (HOLogic.mk_not assm, none_t, 
bulwahn@45683
   299
                mk_smart_test_term' concl (union (op =) (vars_of assm) bound_vars) assms))
bulwahn@42306
   300
      in
bulwahn@45761
   301
        fold_rev mk_closure (map lookup vars) (mk_if check genuine)
bulwahn@42306
   302
      end
bulwahn@42390
   303
    val mk_smart_test_term =
bulwahn@45721
   304
      Quickcheck_Common.strip_imp #> (fn (assms, concl) => mk_smart_test_term' concl [] assms true)
bulwahn@42390
   305
  in
bulwahn@42390
   306
    if Config.get ctxt smart_quantifier then mk_smart_test_term else mk_naive_test_term 
bulwahn@42390
   307
  end
bulwahn@42390
   308
bulwahn@42390
   309
fun mk_fast_generator_expr ctxt (t, eval_terms) =
bulwahn@42390
   310
  let
bulwahn@42390
   311
    val thy = Proof_Context.theory_of ctxt
bulwahn@42390
   312
    val ctxt' = Variable.auto_fixes t ctxt
bulwahn@42390
   313
    val names = Term.add_free_names t []
bulwahn@42390
   314
    val frees = map Free (Term.add_frees t [])
bulwahn@42390
   315
    fun lookup v = the (AList.lookup (op =) (names ~~ frees) v)
bulwahn@42390
   316
    val ([depth_name], ctxt'') = Variable.variant_fixes ["depth"] ctxt'
bulwahn@42390
   317
    val depth = Free (depth_name, @{typ code_numeral})
bulwahn@45721
   318
    fun return _ = @{term "throw_Counterexample :: term list => unit"} $
bulwahn@42390
   319
      (HOLogic.mk_list @{typ "term"}
bulwahn@42390
   320
        (map (fn t => HOLogic.mk_term_of (fastype_of t) t) (frees @ eval_terms)))
bulwahn@42390
   321
    fun mk_exhaustive_closure (free as Free (_, T)) t =
bulwahn@42390
   322
      Const (@{const_name "Quickcheck_Exhaustive.fast_exhaustive_class.fast_exhaustive"},
bulwahn@42390
   323
        fast_exhaustiveT T)
bulwahn@42390
   324
        $ lambda free t $ depth
bulwahn@42390
   325
    val none_t = @{term "()"}
bulwahn@45761
   326
    fun mk_safe_if (cond, then_t, else_t) genuine = mk_if (cond, then_t, else_t genuine)
bulwahn@42390
   327
    val mk_test_term = mk_test_term lookup mk_exhaustive_closure mk_safe_if none_t return ctxt 
bulwahn@42306
   328
  in lambda depth (@{term "catch_Counterexample :: unit => term list option"} $ mk_test_term t) end
bulwahn@42306
   329
bulwahn@45688
   330
fun mk_unknown_term T = HOLogic.reflect_term (Const ("Quickcheck_Exhaustive.unknown", T))
bulwahn@45688
   331
bulwahn@45732
   332
fun mk_safe_term t = @{term "Quickcheck.catch_match :: term => term => term"}
bulwahn@45688
   333
      $ (HOLogic.mk_term_of (fastype_of t) t) $ mk_unknown_term (fastype_of t)    
bulwahn@45688
   334
bulwahn@45724
   335
fun mk_return t genuine = @{term "Some :: bool * term list => (bool * term list) option"} $
bulwahn@45724
   336
  (HOLogic.pair_const @{typ bool} @{typ "term list"} $ Quickcheck_Common.reflect_bool genuine $ t)
bulwahn@45724
   337
bulwahn@42028
   338
fun mk_generator_expr ctxt (t, eval_terms) =
bulwahn@42028
   339
  let
wenzelm@42361
   340
    val thy = Proof_Context.theory_of ctxt
bulwahn@42028
   341
    val ctxt' = Variable.auto_fixes t ctxt
bulwahn@42028
   342
    val names = Term.add_free_names t []
bulwahn@42028
   343
    val frees = map Free (Term.add_frees t [])
bulwahn@42390
   344
    fun lookup v = the (AList.lookup (op =) (names ~~ frees) v)
bulwahn@45754
   345
    val ([depth_name, genuine_only_name], ctxt'') =
bulwahn@45754
   346
      Variable.variant_fixes ["depth", "genuine_only"] ctxt'
bulwahn@42304
   347
    val depth = Free (depth_name, @{typ code_numeral})
bulwahn@45754
   348
    val genuine_only = Free (genuine_only_name, @{typ bool}) 
bulwahn@45724
   349
    val return = mk_return (HOLogic.mk_list @{typ "term"}
bulwahn@45688
   350
        (map (fn t => HOLogic.mk_term_of (fastype_of t) t) frees @ map mk_safe_term eval_terms))
bulwahn@42304
   351
    fun mk_exhaustive_closure (free as Free (_, T)) t =
bulwahn@42304
   352
      Const (@{const_name "Quickcheck_Exhaustive.exhaustive_class.exhaustive"}, exhaustiveT T)
bulwahn@42304
   353
        $ lambda free t $ depth
bulwahn@45724
   354
    val none_t = Const (@{const_name "None"}, resultT)
bulwahn@45763
   355
    val mk_if = Quickcheck_Common.mk_safe_if genuine_only none_t
bulwahn@45718
   356
    val mk_test_term = mk_test_term lookup mk_exhaustive_closure mk_if none_t return ctxt
bulwahn@45754
   357
  in lambda genuine_only (lambda depth (mk_test_term t)) end
bulwahn@42304
   358
bulwahn@42304
   359
fun mk_full_generator_expr ctxt (t, eval_terms) =
bulwahn@42304
   360
  let
wenzelm@42361
   361
    val thy = Proof_Context.theory_of ctxt
bulwahn@42304
   362
    val ctxt' = Variable.auto_fixes t ctxt
bulwahn@42304
   363
    val names = Term.add_free_names t []
bulwahn@42304
   364
    val frees = map Free (Term.add_frees t [])
bulwahn@45753
   365
    val ([depth_name, genuine_only_name], ctxt'') =
bulwahn@45753
   366
      Variable.variant_fixes ["depth", "genuine_only"] ctxt'
bulwahn@42028
   367
    val (term_names, ctxt''') = Variable.variant_fixes (map (prefix "t_") names) ctxt''
bulwahn@42028
   368
    val depth = Free (depth_name, @{typ code_numeral})
bulwahn@45753
   369
    val genuine_only = Free (depth_name, @{typ bool})    
bulwahn@42028
   370
    val term_vars = map (fn n => Free (n, @{typ "unit => term"})) term_names
bulwahn@42390
   371
    fun lookup v = the (AList.lookup (op =) (names ~~ (frees ~~ term_vars)) v)
bulwahn@45724
   372
    val return = mk_return (HOLogic.mk_list @{typ term}
bulwahn@45724
   373
          (map (fn v => v $ @{term "()"}) term_vars @ map mk_safe_term eval_terms))
bulwahn@42028
   374
    fun mk_exhaustive_closure (free as Free (_, T), term_var) t =
bulwahn@42028
   375
      if Sign.of_sort thy (T, @{sort enum}) then
bulwahn@42028
   376
        Const (@{const_name "Quickcheck_Exhaustive.check_all_class.check_all"}, check_allT T)
bulwahn@45753
   377
          $ (HOLogic.split_const (T, @{typ "unit => term"}, resultT)
bulwahn@42028
   378
            $ lambda free (lambda term_var t))
bulwahn@42028
   379
      else
bulwahn@42314
   380
        Const (@{const_name "Quickcheck_Exhaustive.full_exhaustive_class.full_exhaustive"}, full_exhaustiveT T)
bulwahn@45722
   381
          $ (HOLogic.split_const (T, @{typ "unit => term"}, resultT)
bulwahn@42028
   382
            $ lambda free (lambda term_var t)) $ depth
bulwahn@45722
   383
    val none_t = Const (@{const_name "None"}, resultT)
bulwahn@45763
   384
    val mk_if = Quickcheck_Common.mk_safe_if genuine_only none_t
bulwahn@45718
   385
    val mk_test_term = mk_test_term lookup mk_exhaustive_closure mk_if none_t return ctxt
bulwahn@45753
   386
  in lambda genuine_only (lambda depth (mk_test_term t)) end
bulwahn@42028
   387
bulwahn@42304
   388
fun mk_parametric_generator_expr mk_generator_expr =
bulwahn@42159
   389
  Quickcheck_Common.gen_mk_parametric_generator_expr 
bulwahn@45754
   390
    ((mk_generator_expr,
bulwahn@45754
   391
      absdummy @{typ bool} (absdummy @{typ "code_numeral"} (Const (@{const_name "None"}, resultT)))),
bulwahn@45754
   392
      @{typ bool} --> @{typ "code_numeral"} --> resultT)
bulwahn@42195
   393
bulwahn@42195
   394
fun mk_validator_expr ctxt t =
bulwahn@42195
   395
  let
bulwahn@42195
   396
    fun bounded_forallT T = (T --> @{typ bool}) --> @{typ code_numeral} --> @{typ bool}
wenzelm@42361
   397
    val thy = Proof_Context.theory_of ctxt
bulwahn@42195
   398
    val ctxt' = Variable.auto_fixes t ctxt
bulwahn@42390
   399
    val names = Term.add_free_names t []
bulwahn@42390
   400
    val frees = map Free (Term.add_frees t [])
bulwahn@42390
   401
    fun lookup v = the (AList.lookup (op =) (names ~~ frees) v)
bulwahn@42195
   402
    val ([depth_name], ctxt'') = Variable.variant_fixes ["depth"] ctxt'
bulwahn@42195
   403
    val depth = Free (depth_name, @{typ code_numeral})
bulwahn@42390
   404
    fun mk_bounded_forall (Free (s, T)) t =
bulwahn@42195
   405
      Const (@{const_name "Quickcheck_Exhaustive.bounded_forall_class.bounded_forall"}, bounded_forallT T)
bulwahn@42195
   406
        $ lambda (Free (s, T)) t $ depth
bulwahn@45761
   407
    fun mk_safe_if (cond, then_t, else_t) genuine = mk_if (cond, then_t, else_t genuine)
bulwahn@45721
   408
    val mk_test_term =
bulwahn@45721
   409
      mk_test_term lookup mk_bounded_forall mk_safe_if @{term True} (K @{term False}) ctxt
bulwahn@42195
   410
  in lambda depth (mk_test_term t) end
bulwahn@42195
   411
bulwahn@42391
   412
bulwahn@42391
   413
fun mk_bounded_forall_generator_expr ctxt (t, eval_terms) = 
bulwahn@42391
   414
  let
bulwahn@42391
   415
    val frees = Term.add_free_names t []
bulwahn@42391
   416
    val dummy_term = @{term "Code_Evaluation.Const (STR ''dummy_pattern'')
bulwahn@42391
   417
      (Typerep.Typerep (STR ''dummy'') [])"}
bulwahn@42391
   418
    val return = @{term "Some :: term list => term list option"} $
bulwahn@42391
   419
      (HOLogic.mk_list @{typ "term"}
bulwahn@42391
   420
        (replicate (length frees + length eval_terms) dummy_term))
wenzelm@44241
   421
    val wrap = absdummy @{typ bool}
wenzelm@44241
   422
      (@{term "If :: bool => term list option => term list option => term list option"} $
wenzelm@44241
   423
        Bound 0 $ @{term "None :: term list option"} $ return)
bulwahn@42391
   424
  in HOLogic.mk_comp (wrap, mk_validator_expr ctxt t) end
bulwahn@42391
   425
  
bulwahn@42028
   426
(** generator compiliation **)
bulwahn@42028
   427
wenzelm@41472
   428
structure Counterexample = Proof_Data
wenzelm@41472
   429
(
bulwahn@45754
   430
  type T = unit -> int -> bool -> int -> (bool * term list) option
wenzelm@41472
   431
  (* FIXME avoid user error with non-user text *)
bulwahn@40420
   432
  fun init _ () = error "Counterexample"
bulwahn@40420
   433
);
bulwahn@40420
   434
val put_counterexample = Counterexample.put;
bulwahn@40420
   435
bulwahn@41861
   436
structure Counterexample_Batch = Proof_Data
bulwahn@41861
   437
(
bulwahn@41861
   438
  type T = unit -> (int -> term list option) list
bulwahn@41861
   439
  (* FIXME avoid user error with non-user text *)
bulwahn@41861
   440
  fun init _ () = error "Counterexample"
bulwahn@41861
   441
);
bulwahn@41861
   442
val put_counterexample_batch = Counterexample_Batch.put;
bulwahn@41861
   443
bulwahn@42195
   444
structure Validator_Batch = Proof_Data
bulwahn@42195
   445
(
bulwahn@42195
   446
  type T = unit -> (int -> bool) list
bulwahn@42195
   447
  (* FIXME avoid user error with non-user text *)
bulwahn@42195
   448
  fun init _ () = error "Counterexample"
bulwahn@42195
   449
);
bulwahn@42195
   450
val put_validator_batch = Validator_Batch.put;
bulwahn@42195
   451
bulwahn@42195
   452
bulwahn@40420
   453
val target = "Quickcheck";
bulwahn@42391
   454
bulwahn@42159
   455
fun compile_generator_expr ctxt ts =
bulwahn@42159
   456
  let
wenzelm@42361
   457
    val thy = Proof_Context.theory_of ctxt
bulwahn@42306
   458
    val mk_generator_expr = 
bulwahn@42306
   459
      if Config.get ctxt fast then mk_fast_generator_expr
bulwahn@42391
   460
      else if Config.get ctxt bounded_forall then mk_bounded_forall_generator_expr
bulwahn@42306
   461
      else if Config.get ctxt full_support then mk_full_generator_expr else mk_generator_expr
bulwahn@42304
   462
    val t' = mk_parametric_generator_expr mk_generator_expr ctxt ts;
bulwahn@42159
   463
    val compile = Code_Runtime.dynamic_value_strict
bulwahn@42159
   464
      (Counterexample.get, put_counterexample, "Exhaustive_Generators.put_counterexample")
bulwahn@42159
   465
      thy (SOME target) (fn proc => fn g =>
bulwahn@45754
   466
        fn card => fn genuine_only => fn size => g card genuine_only size
bulwahn@45754
   467
          |> (Option.map o apsnd o map) proc) t' []
bulwahn@42159
   468
  in
bulwahn@45754
   469
    fn genuine_only => fn [card, size] => rpair NONE (compile card genuine_only size |> 
bulwahn@42159
   470
      (if Config.get ctxt quickcheck_pretty then
bulwahn@45721
   471
        Option.map (apsnd (map Quickcheck_Common.post_process_term)) else I))
bulwahn@42159
   472
  end;
bulwahn@42391
   473
bulwahn@41861
   474
fun compile_generator_exprs ctxt ts =
bulwahn@41861
   475
  let
wenzelm@42361
   476
    val thy = Proof_Context.theory_of ctxt
bulwahn@42028
   477
    val ts' = map (fn t => mk_generator_expr ctxt (t, [])) ts;
bulwahn@41861
   478
    val compiles = Code_Runtime.dynamic_value_strict
bulwahn@41861
   479
      (Counterexample_Batch.get, put_counterexample_batch,
bulwahn@41918
   480
        "Exhaustive_Generators.put_counterexample_batch")
bulwahn@41861
   481
      thy (SOME target) (fn proc => map (fn g => g #> (Option.map o map) proc))
bulwahn@42195
   482
      (HOLogic.mk_list @{typ "code_numeral => term list option"} ts') []
bulwahn@41861
   483
  in
bulwahn@41935
   484
    map (fn compile => fn size => compile size
bulwahn@41935
   485
      |> Option.map (map Quickcheck_Common.post_process_term)) compiles
bulwahn@41861
   486
  end;
bulwahn@42195
   487
bulwahn@42195
   488
fun compile_validator_exprs ctxt ts =
bulwahn@42195
   489
  let
wenzelm@42361
   490
    val thy = Proof_Context.theory_of ctxt
bulwahn@42273
   491
    val ts' = map (mk_validator_expr ctxt) ts
bulwahn@42195
   492
  in
bulwahn@42195
   493
    Code_Runtime.dynamic_value_strict
bulwahn@42195
   494
      (Validator_Batch.get, put_validator_batch, "Exhaustive_Generators.put_validator_batch")
bulwahn@42195
   495
      thy (SOME target) (K I) (HOLogic.mk_list @{typ "code_numeral => bool"} ts') []
bulwahn@42195
   496
  end;
bulwahn@42195
   497
bulwahn@45728
   498
val test_goals = Quickcheck_Common.generator_test_goal_terms ("exhaustive", compile_generator_expr);
bulwahn@43875
   499
  
bulwahn@42308
   500
(* setup *)
bulwahn@40420
   501
bulwahn@45484
   502
val setup_exhaustive_datatype_interpretation =
bulwahn@45484
   503
  Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
bulwahn@45484
   504
      (((@{sort typerep}, @{sort term_of}), @{sort exhaustive}), instantiate_exhaustive_datatype))
bulwahn@45484
   505
bulwahn@43878
   506
val active = Attrib.setup_config_bool @{binding quickcheck_exhaustive_active} (K true);
bulwahn@43878
   507
bulwahn@40420
   508
val setup =
bulwahn@42229
   509
  Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
bulwahn@42316
   510
      (((@{sort typerep}, @{sort term_of}), @{sort full_exhaustive}), instantiate_full_exhaustive_datatype))
bulwahn@42316
   511
(* #> Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
bulwahn@42229
   512
      (((@{sort typerep}, @{sort term_of}), @{sort exhaustive}), instantiate_exhaustive_datatype))
bulwahn@42230
   513
  #> Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
bulwahn@42306
   514
      (((@{sort typerep}, @{sort term_of}), @{sort fast_exhaustive}), instantiate_fast_exhaustive_datatype))
bulwahn@42310
   515
  #> Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
bulwahn@42316
   516
      (((@{sort type}, @{sort type}), @{sort bounded_forall}), instantiate_bounded_forall_datatype))*)
bulwahn@43878
   517
  #> Context.theory_map (Quickcheck.add_tester ("exhaustive", (active, test_goals)))
bulwahn@42195
   518
  #> Context.theory_map (Quickcheck.add_batch_generator ("exhaustive", compile_generator_exprs))
bulwahn@42195
   519
  #> Context.theory_map (Quickcheck.add_batch_validator ("exhaustive", compile_validator_exprs));
bulwahn@40420
   520
bulwahn@40420
   521
end;