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