src/HOL/Tools/smallvalue_generators.ML
author bulwahn
Mon Nov 08 09:25:43 2010 +0100 (2010-11-08)
changeset 40420 552563ea3304
child 40639 f1f0e6adca0a
permissions -rw-r--r--
adding code and theory for smallvalue generators, but do not setup the interpretation yet
     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 ensure_smallvalue_datatype: Datatype.config -> string list -> theory -> theory
    10   val compile_generator_expr:
    11     Proof.context -> term -> int -> term list option * (bool list * bool)
    12   val put_counterexample: (unit -> int -> term list option)
    13     -> Proof.context -> Proof.context
    14   val setup: theory -> theory
    15 end;
    16 
    17 structure Smallvalue_Generators : SMALLVALUE_GENERATORS =
    18 struct
    19 
    20 (** general term functions **)
    21 
    22 fun dest_funT (Type ("fun",[S, T])) = (S, T)
    23   | dest_funT T = raise TYPE ("dest_funT", [T], [])
    24  
    25 fun mk_fun_comp (t, u) =
    26   let
    27     val (_, B) = dest_funT (fastype_of t)
    28     val (C, A) = dest_funT (fastype_of u)
    29   in
    30     Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
    31   end;
    32 
    33 fun mk_measure f =
    34   let
    35     val Type ("fun", [T, @{typ nat}]) = fastype_of f 
    36   in
    37     Const (@{const_name Wellfounded.measure},
    38       (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
    39     $ f
    40   end
    41 
    42 fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
    43   let
    44     val lt = mk_sumcases rT f TL
    45     val rt = mk_sumcases rT f TR
    46   in
    47     SumTree.mk_sumcase TL TR rT lt rt
    48   end
    49   | mk_sumcases _ f T = f T
    50 
    51 
    52 (** abstract syntax **)
    53 
    54 val size = @{term "i :: code_numeral"}
    55 val size_pred = @{term "(i :: code_numeral) - 1"}
    56 val size_ge_zero = @{term "(i :: code_numeral) > 0"}
    57 fun test_function T = Free ("f", T --> @{typ "term list option"})
    58 
    59 fun mk_none_continuation (x, y) =
    60   let
    61     val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
    62   in
    63     Const (@{const_name Option.option_case}, T --> (T' --> T) --> T --> T)
    64       $ y $ Const (@{const_name Some}, T' --> T) $ x
    65   end
    66 
    67 (** datatypes **)
    68 
    69 (* constructing smallvalue generator instances on datatypes *)
    70 
    71 exception FUNCTION_TYPE;
    72 
    73 val smallN = "small";
    74 
    75 fun smallT T = (T --> @{typ "Code_Evaluation.term list option"}) --> @{typ code_numeral}
    76   --> @{typ "Code_Evaluation.term list option"}
    77 
    78 fun mk_equations thy descr vs tycos (names, auxnames) (Ts, Us) =
    79   let
    80     val smallsN = map (prefix (smallN ^ "_")) (names @ auxnames);
    81     val smalls = map2 (fn name => fn T => Free (name, smallT T))
    82       smallsN (Ts @ Us)
    83     fun mk_small_call T =
    84       let
    85         val small = Const (@{const_name "Smallcheck.small_class.small"}, smallT T)        
    86       in
    87         (T, (fn t => small $ absdummy (T, 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 $ absdummy (T, t) $ size_pred))
    96       end
    97     fun mk_consexpr simpleT (c, xs) =
    98       let
    99         val (Ts, fns) = split_list xs
   100         val constr = Const (c, Ts ---> simpleT)
   101         val bounds = map Bound (((length xs) - 1) downto 0)
   102         val start_term = test_function simpleT $ (list_comb (constr, bounds))
   103       in fold_rev (fn f => fn t => f t) fns start_term end
   104     fun mk_rhs exprs =
   105         @{term "If :: bool => term list option => term list option => term list option"}
   106             $ size_ge_zero $ (foldr1 mk_none_continuation exprs) $ @{term "None :: term list option"}
   107     val rhss =
   108       Datatype_Aux.interpret_construction descr vs
   109         { atyp = mk_small_call, dtyp = mk_small_aux_call }
   110       |> (map o apfst) Type
   111       |> map (fn (T, cs) => map (mk_consexpr T) cs)
   112       |> map mk_rhs
   113     val lhss = map2 (fn t => fn T => t $ test_function T $ size) smalls (Ts @ Us);
   114     val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
   115   in
   116     (Ts @ Us ~~ (smallsN ~~ eqs))
   117   end
   118     
   119 val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
   120 
   121 fun gen_inst_state_tac ctxt rel st =
   122   case Term.add_vars (prop_of st) [] of
   123     [v as (_, T)] =>
   124       let
   125         val cert = Thm.cterm_of (ProofContext.theory_of ctxt)
   126         val rel' = cert rel
   127         val st' = Thm.incr_indexes (#maxidx (Thm.rep_cterm rel') + 1) st (*FIXME??*)
   128       in        
   129         PRIMITIVE (Drule.cterm_instantiate [(cert (Var v), rel')]) st'
   130       end
   131   | _ => Seq.empty;
   132 
   133 fun instantiate_smallvalue_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   134   let
   135     val _ = Datatype_Aux.message config "Creating smallvalue generators ...";
   136     val eqs = mk_equations thy descr vs tycos (names, auxnames) (Ts, Us)
   137     fun my_relation_tac ctxt st =
   138       let
   139         val ((_ $ (_ $ rel)) :: tl) = prems_of st
   140         val domT = (HOLogic.dest_setT (fastype_of rel))
   141         fun mk_single_measure T = mk_fun_comp (@{term "Code_Numeral.nat_of"},
   142             Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
   143         val measure = mk_measure (mk_sumcases @{typ nat} mk_single_measure domT)
   144       in
   145         (Function_Common.apply_termination_rule ctxt 1
   146         THEN gen_inst_state_tac ctxt measure) st
   147       end
   148     fun termination_tac ctxt = 
   149       my_relation_tac ctxt
   150       THEN rtac @{thm wf_measure} 1
   151       THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
   152         (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
   153          @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
   154     fun pat_completeness_auto ctxt =
   155       Pat_Completeness.pat_completeness_tac ctxt 1
   156       THEN auto_tac (clasimpset_of ctxt)
   157   in
   158     thy
   159     |> Class.instantiation (tycos, vs, @{sort small})
   160     |> Function.add_function
   161       (map (fn (T, (name, _)) =>
   162           Syntax.no_syn (Binding.conceal (Binding.name name), SOME (smallT T))) eqs)
   163         (map (pair (apfst Binding.conceal Attrib.empty_binding) o snd o snd) eqs)
   164         Function_Common.default_config pat_completeness_auto
   165     |> snd
   166     |> Local_Theory.restore
   167     |> (fn lthy => Function.prove_termination NONE (termination_tac lthy) lthy)
   168     |> snd
   169     |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   170   end;
   171 
   172 fun ensure_smallvalue_datatype config raw_tycos thy =
   173   let
   174     val algebra = Sign.classes_of thy;
   175     val (descr, raw_vs, tycos, prfx, (names, auxnames), raw_TUs) =
   176       Datatype.the_descr thy raw_tycos;
   177     val typerep_vs = (map o apsnd)
   178       (curry (Sorts.inter_sort algebra) @{sort typerep}) raw_vs;
   179     val smallvalue_insts = (map (rpair @{sort small}) o flat o maps snd o maps snd)
   180       (Datatype_Aux.interpret_construction descr typerep_vs
   181         { atyp = single, dtyp = (K o K o K) [] });
   182     (*val term_of_insts = (map (rpair @{sort term_of}) o flat o maps snd o maps snd)
   183       (Datatype_Aux.interpret_construction descr typerep_vs
   184         { atyp = K [], dtyp = K o K });*)
   185     val has_inst = exists (fn tyco =>
   186       can (Sorts.mg_domain algebra tyco) @{sort small}) tycos;
   187   in if has_inst then thy
   188     else case Quickcheck_Generators.perhaps_constrain thy smallvalue_insts typerep_vs
   189      of SOME constrain => (instantiate_smallvalue_datatype config descr
   190           (map constrain typerep_vs) tycos prfx (names, auxnames)
   191             ((pairself o map o map_atyps) (fn TFree v => TFree (constrain v)) raw_TUs) thy
   192             handle FUNCTION_TYPE =>
   193               (Datatype_Aux.message config
   194                 "Creation of smallvalue generators failed because the datatype contains a function type";
   195               thy))
   196       | NONE => thy
   197   end;
   198 
   199 (** building and compiling generator expressions **)
   200 
   201 structure Counterexample = Proof_Data (
   202   type T = unit -> int -> term list option
   203   fun init _ () = error "Counterexample"
   204 );
   205 val put_counterexample = Counterexample.put;
   206 
   207 val target = "Quickcheck";
   208 
   209 fun mk_generator_expr thy prop Ts =
   210   let
   211     val bound_max = length Ts - 1;
   212     val bounds = map Bound (bound_max downto 0)
   213     val result = list_comb (prop, bounds);
   214     val terms = HOLogic.mk_list @{typ term} (map2 HOLogic.mk_term_of Ts bounds);
   215     val check =
   216       @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
   217         (@{term "If :: bool => term list option => term list option => term list option"}
   218         $ result $ @{term "None :: term list option"}
   219         $ (@{term "Some :: term list => term list option"} $ terms))
   220       $ @{term "None :: term list option"};
   221     fun mk_small_closure (depth, T) t =
   222       Const (@{const_name "Smallcheck.small_class.small"}, smallT T)
   223         $ absdummy (T, t) $ depth
   224   in Abs ("d", @{typ code_numeral}, fold_rev mk_small_closure (rev bounds ~~ Ts) check) end
   225 
   226 fun compile_generator_expr ctxt t =
   227   let
   228     val Ts = (map snd o fst o strip_abs) t;
   229     val thy = ProofContext.theory_of ctxt
   230   in if Quickcheck.report ctxt then
   231     error "Compilation with reporting facility is not supported"
   232   else
   233     let
   234       val t' = mk_generator_expr thy t Ts;
   235       val compile = Code_Runtime.dynamic_value_strict
   236         (Counterexample.get, put_counterexample, "Smallvalue_Generators.put_counterexample")
   237         thy (SOME target) (fn proc => fn g => g #> (Option.map o map) proc) t' [];
   238       val dummy_report = ([], false)
   239     in compile #> rpair dummy_report end
   240   end;
   241 
   242 (** setup **)
   243 
   244 val setup =
   245   Datatype.interpretation ensure_smallvalue_datatype
   246   #> Context.theory_map
   247     (Quickcheck.add_generator ("small", compile_generator_expr));
   248 
   249 end;