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