src/HOL/Tools/smallvalue_generators.ML
author bulwahn
Mon Nov 22 10:42:07 2010 +0100 (2010-11-22)
changeset 40644 0850a2a16dce
parent 40641 5615cc557120
child 40840 2f97215e79bf
permissions -rw-r--r--
changed old-style quickcheck configurations to new Config.T configurations
     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 (** general term functions **)
    20 
    21 fun dest_funT (Type ("fun",[S, T])) = (S, T)
    22   | dest_funT T = raise TYPE ("dest_funT", [T], [])
    23  
    24 fun mk_fun_comp (t, u) =
    25   let
    26     val (_, B) = dest_funT (fastype_of t)
    27     val (C, A) = dest_funT (fastype_of u)
    28   in
    29     Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
    30   end;
    31 
    32 fun mk_measure f =
    33   let
    34     val Type ("fun", [T, @{typ nat}]) = fastype_of f 
    35   in
    36     Const (@{const_name Wellfounded.measure},
    37       (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
    38     $ f
    39   end
    40 
    41 fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
    42   let
    43     val lt = mk_sumcases rT f TL
    44     val rt = mk_sumcases rT f TR
    45   in
    46     SumTree.mk_sumcase TL TR rT lt rt
    47   end
    48   | mk_sumcases _ f T = f T
    49 
    50 
    51 (** abstract syntax **)
    52 
    53 fun termifyT T = HOLogic.mk_prodT (T, @{typ "unit => Code_Evaluation.term"});
    54 
    55 val size = @{term "i :: code_numeral"}
    56 val size_pred = @{term "(i :: code_numeral) - 1"}
    57 val size_ge_zero = @{term "(i :: code_numeral) > 0"}
    58 fun test_function T = Free ("f", termifyT T --> @{typ "term list option"})
    59 
    60 fun mk_none_continuation (x, y) =
    61   let
    62     val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
    63   in
    64     Const (@{const_name Option.option_case}, T --> (T' --> T) --> T --> T)
    65       $ y $ Const (@{const_name Some}, T' --> T) $ x
    66   end
    67 
    68 (** datatypes **)
    69 
    70 (* constructing smallvalue generator instances on datatypes *)
    71 
    72 exception FUNCTION_TYPE;
    73 
    74 val smallN = "small";
    75 
    76 fun smallT T = (T --> @{typ "Code_Evaluation.term list option"}) --> @{typ code_numeral}
    77   --> @{typ "Code_Evaluation.term list option"}
    78 
    79 val full_smallN = "full_small";
    80 
    81 fun full_smallT T = (termifyT T --> @{typ "Code_Evaluation.term list option"})
    82   --> @{typ code_numeral} --> @{typ "Code_Evaluation.term list option"}
    83  
    84 fun mk_equations thy descr vs tycos (names, auxnames) (Ts, Us) =
    85   let
    86     val smallsN = map (prefix (full_smallN ^ "_")) (names @ auxnames);
    87     val smalls = map2 (fn name => fn T => Free (name, full_smallT T))
    88       smallsN (Ts @ Us)
    89     fun mk_small_call T =
    90       let
    91         val small = Const (@{const_name "Smallcheck.full_small_class.full_small"}, full_smallT T)        
    92       in
    93         (T, (fn t => small $
    94           (HOLogic.split_const (T, @{typ "unit => Code_Evaluation.term"}, @{typ "Code_Evaluation.term list option"})
    95           $ absdummy (T, absdummy (@{typ "unit => Code_Evaluation.term"}, t))) $ size_pred))
    96       end
    97     fun mk_small_aux_call fTs (k, _) (tyco, Ts) =
    98       let
    99         val T = Type (tyco, Ts)
   100         val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
   101         val small = nth smalls k
   102       in
   103        (T, (fn t => small $
   104           (HOLogic.split_const (T, @{typ "unit => Code_Evaluation.term"}, @{typ "Code_Evaluation.term list option"})
   105             $ absdummy (T, absdummy (@{typ "unit => Code_Evaluation.term"}, t))) $ size_pred))  
   106       end
   107     fun mk_consexpr simpleT (c, xs) =
   108       let
   109         val (Ts, fns) = split_list xs
   110         val constr = Const (c, Ts ---> simpleT)
   111         val bounds = map (fn x => Bound (2 * x + 1)) (((length xs) - 1) downto 0)
   112         val term_bounds = map (fn x => Bound (2 * x)) (((length xs) - 1) downto 0)
   113         val Eval_App = Const ("Code_Evaluation.App", HOLogic.termT --> HOLogic.termT --> HOLogic.termT)
   114         val Eval_Const = Const ("Code_Evaluation.Const", HOLogic.literalT --> @{typ typerep} --> HOLogic.termT)
   115         val term = fold (fn u => fn t => Eval_App $ t $ (u $ @{term "()"}))
   116           bounds (Eval_Const $ HOLogic.mk_literal c $ HOLogic.mk_typerep (Ts ---> simpleT))
   117         val start_term = test_function simpleT $ 
   118         (HOLogic.pair_const simpleT @{typ "unit => Code_Evaluation.term"}
   119           $ (list_comb (constr, bounds)) $ absdummy (@{typ unit}, term))
   120       in fold_rev (fn f => fn t => f t) fns start_term end
   121     fun mk_rhs exprs =
   122         @{term "If :: bool => term list option => term list option => term list option"}
   123             $ size_ge_zero $ (foldr1 mk_none_continuation exprs) $ @{term "None :: term list option"}
   124     val rhss =
   125       Datatype_Aux.interpret_construction descr vs
   126         { atyp = mk_small_call, dtyp = mk_small_aux_call }
   127       |> (map o apfst) Type
   128       |> map (fn (T, cs) => map (mk_consexpr T) cs)
   129       |> map mk_rhs
   130     val lhss = map2 (fn t => fn T => t $ test_function T $ size) smalls (Ts @ Us);
   131     val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
   132   in
   133     (Ts @ Us ~~ (smallsN ~~ eqs))
   134   end
   135     
   136 val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
   137   
   138 fun instantiate_smallvalue_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   139   let
   140     val _ = Datatype_Aux.message config "Creating smallvalue generators ...";
   141     val eqs = mk_equations thy descr vs tycos (names, auxnames) (Ts, Us)
   142     fun mk_single_measure T = mk_fun_comp (@{term "Code_Numeral.nat_of"},
   143       Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
   144     fun mk_termination_measure T =
   145       let
   146         val T' = fst (HOLogic.dest_prodT (HOLogic.dest_setT T))
   147       in
   148         mk_measure (mk_sumcases @{typ nat} mk_single_measure T')
   149       end
   150     fun termination_tac ctxt = 
   151       Function_Relation.relation_tac ctxt mk_termination_measure 1
   152       THEN rtac @{thm wf_measure} 1
   153       THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
   154         (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
   155          @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
   156     fun pat_completeness_auto ctxt =
   157       Pat_Completeness.pat_completeness_tac ctxt 1
   158       THEN auto_tac (clasimpset_of ctxt)
   159   in 
   160     thy
   161     |> Class.instantiation (tycos, vs, @{sort full_small})
   162     |> Function.add_function
   163       (map (fn (T, (name, _)) =>
   164           Syntax.no_syn (Binding.conceal (Binding.name name), SOME (full_smallT T))) eqs)
   165         (map (pair (apfst Binding.conceal Attrib.empty_binding) o snd o snd) eqs)
   166         Function_Common.default_config pat_completeness_auto
   167     |> snd
   168     |> Local_Theory.restore
   169     |> (fn lthy => Function.prove_termination NONE (termination_tac lthy) lthy)
   170     |> snd
   171     |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   172   end handle FUNCTION_TYPE =>
   173     (Datatype_Aux.message config
   174       "Creation of smallvalue generators failed because the datatype contains a function type";
   175     thy)
   176 
   177 (** building and compiling generator expressions **)
   178 
   179 structure Counterexample = Proof_Data (
   180   type T = unit -> int -> term list option
   181   fun init _ () = error "Counterexample"
   182 );
   183 val put_counterexample = Counterexample.put;
   184 
   185 val target = "Quickcheck";
   186 
   187 fun mk_generator_expr thy prop Ts =
   188   let
   189     val bound_max = length Ts - 1;
   190     val bounds = map_index (fn (i, ty) =>
   191       (2 * (bound_max - i) + 1, 2 * (bound_max - i), 2 * i, ty)) Ts;
   192     val result = list_comb (prop, map (fn (i, _, _, _) => Bound i) bounds);
   193     val terms = HOLogic.mk_list @{typ term} (map (fn (_, i, _, _) => Bound i $ @{term "()"}) bounds);
   194     val check =
   195       @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
   196         (@{term "If :: bool => term list option => term list option => term list option"}
   197         $ result $ @{term "None :: term list option"} $ (@{term "Some :: term list => term list option"} $ terms))
   198       $ @{term "None :: term list option"};
   199     fun mk_small_closure (_, _, i, T) t =
   200       Const (@{const_name "Smallcheck.full_small_class.full_small"}, full_smallT T)
   201         $ (HOLogic.split_const (T, @{typ "unit => term"}, @{typ "term list option"}) 
   202         $ absdummy (T, absdummy (@{typ "unit => term"}, t))) $ Bound i
   203   in Abs ("d", @{typ code_numeral}, fold_rev mk_small_closure bounds check) end
   204 
   205 fun compile_generator_expr ctxt t =
   206   let
   207     val Ts = (map snd o fst o strip_abs) t;
   208     val thy = ProofContext.theory_of ctxt
   209   in if Config.get ctxt Quickcheck.report then
   210     error "Compilation with reporting facility is not supported"
   211   else
   212     let
   213       val t' = mk_generator_expr thy t Ts;
   214       val compile = Code_Runtime.dynamic_value_strict
   215         (Counterexample.get, put_counterexample, "Smallvalue_Generators.put_counterexample")
   216         thy (SOME target) (fn proc => fn g => g #> (Option.map o map) proc) t' [];
   217       val dummy_report = ([], false)
   218     in compile #> rpair dummy_report end
   219   end;
   220 
   221 (** setup **)
   222 
   223 val setup =
   224   Datatype.interpretation
   225     (Quickcheck_Generators.ensure_sort_datatype (@{sort full_small}, instantiate_smallvalue_datatype))
   226   #> Context.theory_map
   227     (Quickcheck.add_generator ("small", compile_generator_expr));
   228 
   229 end;