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