src/HOL/Tools/smallvalue_generators.ML
author haftmann
Wed Dec 08 13:34:50 2010 +0100 (2010-12-08)
changeset 41075 4bed56dc95fb
parent 40913 99a4ef20704d
child 41085 a549ff1d4070
permissions -rw-r--r--
primitive definitions of bot/top/inf/sup for bool and fun are named with canonical suffix `_def` rather than `_eq`
bulwahn@40420
     1
(*  Title:      HOL/Tools/smallvalue_generators.ML
bulwahn@40420
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@40420
     3
bulwahn@40420
     4
Generators for small values for various types.
bulwahn@40420
     5
*)
bulwahn@40420
     6
bulwahn@40420
     7
signature SMALLVALUE_GENERATORS =
bulwahn@40420
     8
sig
bulwahn@40420
     9
  val compile_generator_expr:
bulwahn@40911
    10
    Proof.context -> term -> int -> term list option * Quickcheck.report option
bulwahn@40420
    11
  val put_counterexample: (unit -> int -> term list option)
bulwahn@40420
    12
    -> Proof.context -> Proof.context
bulwahn@40907
    13
  val smart_quantifier : bool Config.T;
bulwahn@40420
    14
  val setup: theory -> theory
bulwahn@40420
    15
end;
bulwahn@40420
    16
bulwahn@40420
    17
structure Smallvalue_Generators : SMALLVALUE_GENERATORS =
bulwahn@40420
    18
struct
bulwahn@40420
    19
bulwahn@40901
    20
(* static options *)
bulwahn@40901
    21
bulwahn@40901
    22
val define_foundationally = false
bulwahn@40901
    23
bulwahn@40907
    24
(* dynamic options *)
bulwahn@40907
    25
bulwahn@40907
    26
val (smart_quantifier, setup_smart_quantifier) =
bulwahn@40907
    27
  Attrib.config_bool "quickcheck_smart_quantifier" (K true)
bulwahn@40907
    28
bulwahn@40420
    29
(** general term functions **)
bulwahn@40420
    30
bulwahn@40420
    31
fun mk_measure f =
bulwahn@40420
    32
  let
bulwahn@40420
    33
    val Type ("fun", [T, @{typ nat}]) = fastype_of f 
bulwahn@40420
    34
  in
bulwahn@40420
    35
    Const (@{const_name Wellfounded.measure},
bulwahn@40420
    36
      (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
bulwahn@40420
    37
    $ f
bulwahn@40420
    38
  end
bulwahn@40420
    39
bulwahn@40420
    40
fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
bulwahn@40420
    41
  let
bulwahn@40420
    42
    val lt = mk_sumcases rT f TL
bulwahn@40420
    43
    val rt = mk_sumcases rT f TR
bulwahn@40420
    44
  in
bulwahn@40420
    45
    SumTree.mk_sumcase TL TR rT lt rt
bulwahn@40420
    46
  end
bulwahn@40420
    47
  | mk_sumcases _ f T = f T
bulwahn@40420
    48
bulwahn@40901
    49
fun mk_undefined T = Const(@{const_name undefined}, T)
bulwahn@40901
    50
  
bulwahn@40420
    51
bulwahn@40420
    52
(** abstract syntax **)
bulwahn@40420
    53
bulwahn@40639
    54
fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => Code_Evaluation.term"});
bulwahn@40639
    55
bulwahn@40420
    56
val size = @{term "i :: code_numeral"}
bulwahn@40420
    57
val size_pred = @{term "(i :: code_numeral) - 1"}
bulwahn@40420
    58
val size_ge_zero = @{term "(i :: code_numeral) > 0"}
bulwahn@40639
    59
fun test_function T = Free ("f", termifyT T --> @{typ "term list option"})
bulwahn@40420
    60
bulwahn@40420
    61
fun mk_none_continuation (x, y) =
bulwahn@40420
    62
  let
bulwahn@40420
    63
    val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
bulwahn@40420
    64
  in
bulwahn@40899
    65
    Const (@{const_name "Smallcheck.orelse"}, T --> T --> T)
bulwahn@40899
    66
      $ x $ y
bulwahn@40420
    67
  end
bulwahn@40420
    68
bulwahn@40420
    69
(** datatypes **)
bulwahn@40420
    70
bulwahn@40420
    71
(* constructing smallvalue generator instances on datatypes *)
bulwahn@40420
    72
bulwahn@40420
    73
exception FUNCTION_TYPE;
bulwahn@40420
    74
bulwahn@40420
    75
val smallN = "small";
bulwahn@40420
    76
bulwahn@40420
    77
fun smallT T = (T --> @{typ "Code_Evaluation.term list option"}) --> @{typ code_numeral}
bulwahn@40420
    78
  --> @{typ "Code_Evaluation.term list option"}
bulwahn@40420
    79
bulwahn@40639
    80
val full_smallN = "full_small";
bulwahn@40639
    81
bulwahn@40639
    82
fun full_smallT T = (termifyT T --> @{typ "Code_Evaluation.term list option"})
bulwahn@40639
    83
  --> @{typ code_numeral} --> @{typ "Code_Evaluation.term list option"}
bulwahn@40639
    84
 
bulwahn@40901
    85
fun mk_equations thy descr vs tycos smalls (Ts, Us) =
bulwahn@40420
    86
  let
bulwahn@40420
    87
    fun mk_small_call T =
bulwahn@40420
    88
      let
bulwahn@40639
    89
        val small = Const (@{const_name "Smallcheck.full_small_class.full_small"}, full_smallT T)        
bulwahn@40420
    90
      in
bulwahn@40639
    91
        (T, (fn t => small $
bulwahn@40639
    92
          (HOLogic.split_const (T, @{typ "unit => Code_Evaluation.term"}, @{typ "Code_Evaluation.term list option"})
bulwahn@40639
    93
          $ absdummy (T, absdummy (@{typ "unit => Code_Evaluation.term"}, t))) $ size_pred))
bulwahn@40420
    94
      end
bulwahn@40420
    95
    fun mk_small_aux_call fTs (k, _) (tyco, Ts) =
bulwahn@40420
    96
      let
bulwahn@40420
    97
        val T = Type (tyco, Ts)
bulwahn@40420
    98
        val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
bulwahn@40420
    99
        val small = nth smalls k
bulwahn@40420
   100
      in
bulwahn@40639
   101
       (T, (fn t => small $
bulwahn@40639
   102
          (HOLogic.split_const (T, @{typ "unit => Code_Evaluation.term"}, @{typ "Code_Evaluation.term list option"})
bulwahn@40639
   103
            $ absdummy (T, absdummy (@{typ "unit => Code_Evaluation.term"}, t))) $ size_pred))  
bulwahn@40420
   104
      end
bulwahn@40420
   105
    fun mk_consexpr simpleT (c, xs) =
bulwahn@40420
   106
      let
bulwahn@40420
   107
        val (Ts, fns) = split_list xs
bulwahn@40420
   108
        val constr = Const (c, Ts ---> simpleT)
bulwahn@40639
   109
        val bounds = map (fn x => Bound (2 * x + 1)) (((length xs) - 1) downto 0)
bulwahn@40639
   110
        val term_bounds = map (fn x => Bound (2 * x)) (((length xs) - 1) downto 0)
bulwahn@40639
   111
        val Eval_App = Const ("Code_Evaluation.App", HOLogic.termT --> HOLogic.termT --> HOLogic.termT)
bulwahn@40639
   112
        val Eval_Const = Const ("Code_Evaluation.Const", HOLogic.literalT --> @{typ typerep} --> HOLogic.termT)
bulwahn@40639
   113
        val term = fold (fn u => fn t => Eval_App $ t $ (u $ @{term "()"}))
bulwahn@40639
   114
          bounds (Eval_Const $ HOLogic.mk_literal c $ HOLogic.mk_typerep (Ts ---> simpleT))
bulwahn@40639
   115
        val start_term = test_function simpleT $ 
bulwahn@40639
   116
        (HOLogic.pair_const simpleT @{typ "unit => Code_Evaluation.term"}
bulwahn@40639
   117
          $ (list_comb (constr, bounds)) $ absdummy (@{typ unit}, term))
bulwahn@40420
   118
      in fold_rev (fn f => fn t => f t) fns start_term end
bulwahn@40420
   119
    fun mk_rhs exprs =
bulwahn@40420
   120
        @{term "If :: bool => term list option => term list option => term list option"}
bulwahn@40420
   121
            $ size_ge_zero $ (foldr1 mk_none_continuation exprs) $ @{term "None :: term list option"}
bulwahn@40420
   122
    val rhss =
bulwahn@40420
   123
      Datatype_Aux.interpret_construction descr vs
bulwahn@40420
   124
        { atyp = mk_small_call, dtyp = mk_small_aux_call }
bulwahn@40420
   125
      |> (map o apfst) Type
bulwahn@40420
   126
      |> map (fn (T, cs) => map (mk_consexpr T) cs)
bulwahn@40420
   127
      |> map mk_rhs
bulwahn@40420
   128
    val lhss = map2 (fn t => fn T => t $ test_function T $ size) smalls (Ts @ Us);
bulwahn@40420
   129
    val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
bulwahn@40420
   130
  in
bulwahn@40901
   131
    eqs
bulwahn@40901
   132
  end
bulwahn@40901
   133
bulwahn@40901
   134
(* foundational definition with the function package *)
bulwahn@40901
   135
bulwahn@40901
   136
val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
bulwahn@40901
   137
bulwahn@40901
   138
fun mk_single_measure T = HOLogic.mk_comp (@{term "Code_Numeral.nat_of"},
bulwahn@40901
   139
    Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
bulwahn@40901
   140
bulwahn@40901
   141
fun mk_termination_measure T =
bulwahn@40901
   142
  let
bulwahn@40901
   143
    val T' = fst (HOLogic.dest_prodT (HOLogic.dest_setT T))
bulwahn@40901
   144
  in
bulwahn@40901
   145
    mk_measure (mk_sumcases @{typ nat} mk_single_measure T')
bulwahn@40420
   146
  end
bulwahn@40901
   147
bulwahn@40901
   148
fun termination_tac ctxt = 
bulwahn@40901
   149
  Function_Relation.relation_tac ctxt mk_termination_measure 1
bulwahn@40901
   150
  THEN rtac @{thm wf_measure} 1
bulwahn@40901
   151
  THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
bulwahn@40901
   152
    (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
bulwahn@40901
   153
     @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
bulwahn@40901
   154
bulwahn@40901
   155
fun pat_completeness_auto ctxt =
bulwahn@40901
   156
  Pat_Completeness.pat_completeness_tac ctxt 1
bulwahn@40901
   157
  THEN auto_tac (clasimpset_of ctxt)    
bulwahn@40901
   158
bulwahn@40901
   159
bulwahn@40901
   160
(* creating the instances *)
bulwahn@40901
   161
bulwahn@40420
   162
fun instantiate_smallvalue_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
bulwahn@40420
   163
  let
bulwahn@40420
   164
    val _ = Datatype_Aux.message config "Creating smallvalue generators ...";
bulwahn@40901
   165
    val smallsN = map (prefix (full_smallN ^ "_")) (names @ auxnames);
bulwahn@40901
   166
  in
bulwahn@40641
   167
    thy
bulwahn@40639
   168
    |> Class.instantiation (tycos, vs, @{sort full_small})
bulwahn@40901
   169
    |> (if define_foundationally then
bulwahn@40901
   170
      let
bulwahn@40901
   171
        val smalls = map2 (fn name => fn T => Free (name, full_smallT T)) smallsN (Ts @ Us)
bulwahn@40901
   172
        val eqs = mk_equations thy descr vs tycos smalls (Ts, Us)
bulwahn@40901
   173
      in
bulwahn@40901
   174
        Function.add_function
bulwahn@40901
   175
          (map (fn (name, T) =>
bulwahn@40901
   176
              Syntax.no_syn (Binding.conceal (Binding.name name), SOME (full_smallT T)))
bulwahn@40901
   177
                (smallsN ~~ (Ts @ Us)))
bulwahn@40901
   178
            (map (pair (apfst Binding.conceal Attrib.empty_binding)) eqs)
bulwahn@40901
   179
          Function_Common.default_config pat_completeness_auto
bulwahn@40901
   180
        #> snd
bulwahn@40901
   181
        #> Local_Theory.restore
bulwahn@40901
   182
        #> (fn lthy => Function.prove_termination NONE (termination_tac lthy) lthy)
bulwahn@40901
   183
        #> snd
bulwahn@40901
   184
      end
bulwahn@40901
   185
    else
bulwahn@40901
   186
      fold_map (fn (name, T) => Local_Theory.define
bulwahn@40901
   187
          ((Binding.conceal (Binding.name name), NoSyn),
bulwahn@40901
   188
            (apfst Binding.conceal Attrib.empty_binding, mk_undefined (full_smallT T)))
bulwahn@40901
   189
        #> apfst fst) (smallsN ~~ (Ts @ Us))
bulwahn@40901
   190
      #> (fn (smalls, lthy) =>
bulwahn@40901
   191
        let
bulwahn@40901
   192
          val eqs_t = mk_equations thy descr vs tycos smalls (Ts, Us)
bulwahn@40901
   193
          val eqs = map (fn eq => Goal.prove lthy ["f", "i"] [] eq
bulwahn@40901
   194
            (fn _ => Skip_Proof.cheat_tac (ProofContext.theory_of lthy))) eqs_t
bulwahn@40901
   195
        in
bulwahn@40901
   196
          fold (fn (name, eq) => Local_Theory.note
bulwahn@40901
   197
          ((Binding.conceal (Binding.qualify true prfx
bulwahn@40901
   198
             (Binding.qualify true name (Binding.name "simps"))),
bulwahn@40901
   199
             Code.add_default_eqn_attrib :: map (Attrib.internal o K)
bulwahn@40901
   200
               [Simplifier.simp_add, Nitpick_Simps.add]), [eq]) #> snd) (smallsN ~~ eqs) lthy
bulwahn@40901
   201
        end))
bulwahn@40641
   202
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
bulwahn@40641
   203
  end handle FUNCTION_TYPE =>
bulwahn@40639
   204
    (Datatype_Aux.message config
bulwahn@40639
   205
      "Creation of smallvalue generators failed because the datatype contains a function type";
bulwahn@40639
   206
    thy)
bulwahn@40420
   207
bulwahn@40420
   208
(** building and compiling generator expressions **)
bulwahn@40420
   209
bulwahn@40420
   210
structure Counterexample = Proof_Data (
bulwahn@40420
   211
  type T = unit -> int -> term list option
bulwahn@40420
   212
  fun init _ () = error "Counterexample"
bulwahn@40420
   213
);
bulwahn@40420
   214
val put_counterexample = Counterexample.put;
bulwahn@40420
   215
bulwahn@40420
   216
val target = "Quickcheck";
bulwahn@40420
   217
bulwahn@40907
   218
fun mk_smart_generator_expr ctxt t =
bulwahn@40420
   219
  let
bulwahn@40907
   220
    val ((vnames, Ts), t') = apfst split_list (strip_abs t)
bulwahn@40907
   221
    val ([depth_name], ctxt') = Variable.variant_fixes ["depth"] ctxt
bulwahn@40907
   222
    val (names, ctxt'') = Variable.variant_fixes vnames ctxt'
bulwahn@40907
   223
    val (term_names, ctxt''') = Variable.variant_fixes (map (prefix "t_") vnames) ctxt''
bulwahn@40907
   224
    val depth = Free (depth_name, @{typ code_numeral})
bulwahn@40907
   225
    val frees = map2 (curry Free) names Ts
bulwahn@40907
   226
    val term_vars = map (fn n => Free (n, @{typ "unit => term"})) term_names 
bulwahn@40907
   227
    fun strip_imp (Const(@{const_name HOL.implies},_) $ A $ B) = apfst (cons A) (strip_imp B)
bulwahn@40907
   228
      | strip_imp A = ([], A)
bulwahn@40907
   229
    val (assms, concl) = strip_imp (subst_bounds (rev frees, t'))
bulwahn@40907
   230
    val terms = HOLogic.mk_list @{typ term} (map (fn v => v $ @{term "()"}) term_vars)
bulwahn@40907
   231
    fun mk_small_closure (free as Free (_, T), term_var) t =
bulwahn@40907
   232
      Const (@{const_name "Smallcheck.full_small_class.full_small"}, full_smallT T)
bulwahn@40907
   233
        $ (HOLogic.split_const (T, @{typ "unit => term"}, @{typ "term list option"}) 
bulwahn@40907
   234
          $ lambda free (lambda term_var t)) $ depth
bulwahn@40907
   235
    fun lookup v = the (AList.lookup (op =) (names ~~ (frees ~~ term_vars)) v)
bulwahn@40907
   236
    val none_t = @{term "None :: term list option"}
bulwahn@40907
   237
    fun mk_safe_if (cond, then_t, else_t) =
bulwahn@40907
   238
      @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
bulwahn@40907
   239
        (@{term "If :: bool => term list option => term list option => term list option"}
bulwahn@40907
   240
        $ cond $ then_t $ else_t) $ none_t;
bulwahn@40907
   241
    fun mk_test_term bound_vars assms =
bulwahn@40907
   242
      let
bulwahn@40907
   243
        fun vars_of t = subtract (op =) bound_vars (Term.add_free_names t [])
bulwahn@40907
   244
        val (vars, check) =
bulwahn@40907
   245
          case assms of [] =>
bulwahn@40907
   246
            (vars_of concl, (concl, none_t, @{term "Some :: term list => term list option"} $ terms))
bulwahn@40907
   247
          | assm :: assms =>
bulwahn@40907
   248
            (vars_of assm, (assm, mk_test_term (union (op =) (vars_of assm) bound_vars) assms, none_t))
bulwahn@40907
   249
      in
bulwahn@40907
   250
        fold_rev mk_small_closure (map lookup vars) (mk_safe_if check)
bulwahn@40907
   251
      end
bulwahn@40907
   252
  in lambda depth (mk_test_term [] assms) end
bulwahn@40907
   253
bulwahn@40907
   254
fun mk_generator_expr ctxt t =
bulwahn@40907
   255
  let
bulwahn@40907
   256
    val Ts = (map snd o fst o strip_abs) t;
bulwahn@40907
   257
    val thy = ProofContext.theory_of ctxt
bulwahn@40420
   258
    val bound_max = length Ts - 1;
bulwahn@40639
   259
    val bounds = map_index (fn (i, ty) =>
bulwahn@40639
   260
      (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
bulwahn@40907
   261
    val result = list_comb (t, map (fn (i, _, _, _) => Bound i) bounds);
bulwahn@40639
   262
    val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
bulwahn@40420
   263
    val check =
bulwahn@40420
   264
      @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
bulwahn@40420
   265
        (@{term "If :: bool => term list option => term list option => term list option"}
bulwahn@40639
   266
        $ result $ @{term "None :: term list option"} $ (@{term "Some :: term list => term list option"} $ terms))
bulwahn@40420
   267
      $ @{term "None :: term list option"};
bulwahn@40639
   268
    fun mk_small_closure (_, _, i, T) t =
bulwahn@40639
   269
      Const (@{const_name "Smallcheck.full_small_class.full_small"}, full_smallT T)
bulwahn@40639
   270
        $ (HOLogic.split_const (T, @{typ "unit => term"}, @{typ "term list option"}) 
bulwahn@40639
   271
        $ absdummy (T, absdummy (@{typ "unit => term"}, t))) $ Bound i
bulwahn@40639
   272
  in Abs ("d", @{typ code_numeral}, fold_rev mk_small_closure bounds check) end
bulwahn@40420
   273
bulwahn@40420
   274
fun compile_generator_expr ctxt t =
bulwahn@40911
   275
  let
bulwahn@40911
   276
    val thy = ProofContext.theory_of ctxt
bulwahn@40911
   277
    val t' =
bulwahn@40911
   278
      (if Config.get ctxt smart_quantifier then mk_smart_generator_expr else mk_generator_expr)
bulwahn@40911
   279
        ctxt t;
bulwahn@40911
   280
    val compile = Code_Runtime.dynamic_value_strict
bulwahn@40911
   281
      (Counterexample.get, put_counterexample, "Smallvalue_Generators.put_counterexample")
bulwahn@40911
   282
      thy (SOME target) (fn proc => fn g => g #> (Option.map o map) proc) t' [];
bulwahn@40911
   283
  in fn size => rpair NONE (compile size) end;
bulwahn@40420
   284
bulwahn@40420
   285
(** setup **)
bulwahn@40420
   286
bulwahn@40420
   287
val setup =
bulwahn@40639
   288
  Datatype.interpretation
bulwahn@40639
   289
    (Quickcheck_Generators.ensure_sort_datatype (@{sort full_small}, instantiate_smallvalue_datatype))
bulwahn@40907
   290
  #> setup_smart_quantifier
bulwahn@40420
   291
  #> Context.theory_map
bulwahn@40913
   292
    (Quickcheck.add_generator ("exhaustive", compile_generator_expr));
bulwahn@40420
   293
bulwahn@40420
   294
end;