adding code and theory for smallvalue generators, but do not setup the interpretation yet
authorbulwahn
Mon Nov 08 09:25:43 2010 +0100 (2010-11-08)
changeset 40420552563ea3304
parent 40419 718b44dbd74d
child 40423 6923b39ad91f
adding code and theory for smallvalue generators, but do not setup the interpretation yet
src/HOL/IsaMakefile
src/HOL/Main.thy
src/HOL/Smallcheck.thy
src/HOL/Tools/smallvalue_generators.ML
     1.1 --- a/src/HOL/IsaMakefile	Mon Nov 08 02:33:48 2010 +0100
     1.2 +++ b/src/HOL/IsaMakefile	Mon Nov 08 09:25:43 2010 +0100
     1.3 @@ -270,6 +270,7 @@
     1.4    Semiring_Normalization.thy \
     1.5    SetInterval.thy \
     1.6    Sledgehammer.thy \
     1.7 +  Smallcheck.thy \
     1.8    SMT.thy \
     1.9    String.thy \
    1.10    Typerep.thy \
    1.11 @@ -336,6 +337,7 @@
    1.12    Tools/Sledgehammer/sledgehammer_atp_reconstruct.ML \
    1.13    Tools/Sledgehammer/sledgehammer_atp_translate.ML \
    1.14    Tools/Sledgehammer/sledgehammer_util.ML \
    1.15 +  Tools/smallvalue_generators.ML \
    1.16    Tools/SMT/smtlib_interface.ML \
    1.17    Tools/SMT/smt_builtin.ML \
    1.18    Tools/SMT/smt_monomorph.ML \
     2.1 --- a/src/HOL/Main.thy	Mon Nov 08 02:33:48 2010 +0100
     2.2 +++ b/src/HOL/Main.thy	Mon Nov 08 09:25:43 2010 +0100
     2.3 @@ -1,7 +1,7 @@
     2.4  header {* Main HOL *}
     2.5  
     2.6  theory Main
     2.7 -imports Plain Record Predicate_Compile Nitpick
     2.8 +imports Plain Record Predicate_Compile Smallcheck Nitpick
     2.9  begin
    2.10  
    2.11  text {*
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/src/HOL/Smallcheck.thy	Mon Nov 08 09:25:43 2010 +0100
     3.3 @@ -0,0 +1,69 @@
     3.4 +(* Author: Lukas Bulwahn, TU Muenchen *)
     3.5 +
     3.6 +header {* Another simple counterexample generator *}
     3.7 +
     3.8 +theory Smallcheck
     3.9 +imports Quickcheck
    3.10 +uses ("Tools/smallvalue_generators.ML")
    3.11 +begin
    3.12 +
    3.13 +
    3.14 +section {* small value generator type classes *}
    3.15 +
    3.16 +class small = term_of +
    3.17 +fixes small :: "('a \<Rightarrow> term list option) \<Rightarrow> code_numeral \<Rightarrow> term list option"
    3.18 +
    3.19 +instantiation unit :: small
    3.20 +begin
    3.21 +
    3.22 +definition "find_first f d = f ()"
    3.23 +
    3.24 +instance ..
    3.25 +
    3.26 +end
    3.27 +
    3.28 +instantiation int :: small
    3.29 +begin
    3.30 +
    3.31 +function small' :: "(int => term list option) => int => int => term list option"
    3.32 +where "small' f d i = (if d < i then None else (case f i of Some t => Some t | None => small' f d (i + 1)))"
    3.33 +by pat_completeness auto
    3.34 +
    3.35 +termination 
    3.36 +  by (relation "measure (%(_, d, i). nat (d + 1 - i))") auto
    3.37 +
    3.38 +definition "small f d = small' f (Code_Numeral.int_of d) (- (Code_Numeral.int_of d))"
    3.39 +
    3.40 +instance ..
    3.41 +
    3.42 +end
    3.43 +
    3.44 +instantiation prod :: (small, small) small
    3.45 +begin
    3.46 +
    3.47 +definition
    3.48 +  "small f d = small (%x. small (%y. f (x, y)) d) d"
    3.49 +
    3.50 +instance ..
    3.51 +
    3.52 +end
    3.53 +
    3.54 +section {* Defining combinators for any first-order data type *}
    3.55 +
    3.56 +definition catch_match :: "term list option => term list option => term list option"
    3.57 +where
    3.58 +  [code del]: "catch_match t1 t2 = (SOME t. t = t1 \<or> t = t2)"
    3.59 +
    3.60 +code_const catch_match 
    3.61 +  (SML "(_) handle Match => _")
    3.62 +
    3.63 +use "Tools/smallvalue_generators.ML"
    3.64 +
    3.65 +(* We do not activate smallcheck yet. 
    3.66 +setup {* Smallvalue_Generators.setup *}
    3.67 +*)
    3.68 +
    3.69 +hide_fact catch_match_def
    3.70 +hide_const (open) catch_match
    3.71 +
    3.72 +end
    3.73 \ No newline at end of file
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/src/HOL/Tools/smallvalue_generators.ML	Mon Nov 08 09:25:43 2010 +0100
     4.3 @@ -0,0 +1,249 @@
     4.4 +(*  Title:      HOL/Tools/smallvalue_generators.ML
     4.5 +    Author:     Lukas Bulwahn, TU Muenchen
     4.6 +
     4.7 +Generators for small values for various types.
     4.8 +*)
     4.9 +
    4.10 +signature SMALLVALUE_GENERATORS =
    4.11 +sig
    4.12 +  val ensure_smallvalue_datatype: Datatype.config -> string list -> theory -> theory
    4.13 +  val compile_generator_expr:
    4.14 +    Proof.context -> term -> int -> term list option * (bool list * bool)
    4.15 +  val put_counterexample: (unit -> int -> term list option)
    4.16 +    -> Proof.context -> Proof.context
    4.17 +  val setup: theory -> theory
    4.18 +end;
    4.19 +
    4.20 +structure Smallvalue_Generators : SMALLVALUE_GENERATORS =
    4.21 +struct
    4.22 +
    4.23 +(** general term functions **)
    4.24 +
    4.25 +fun dest_funT (Type ("fun",[S, T])) = (S, T)
    4.26 +  | dest_funT T = raise TYPE ("dest_funT", [T], [])
    4.27 + 
    4.28 +fun mk_fun_comp (t, u) =
    4.29 +  let
    4.30 +    val (_, B) = dest_funT (fastype_of t)
    4.31 +    val (C, A) = dest_funT (fastype_of u)
    4.32 +  in
    4.33 +    Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
    4.34 +  end;
    4.35 +
    4.36 +fun mk_measure f =
    4.37 +  let
    4.38 +    val Type ("fun", [T, @{typ nat}]) = fastype_of f 
    4.39 +  in
    4.40 +    Const (@{const_name Wellfounded.measure},
    4.41 +      (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
    4.42 +    $ f
    4.43 +  end
    4.44 +
    4.45 +fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
    4.46 +  let
    4.47 +    val lt = mk_sumcases rT f TL
    4.48 +    val rt = mk_sumcases rT f TR
    4.49 +  in
    4.50 +    SumTree.mk_sumcase TL TR rT lt rt
    4.51 +  end
    4.52 +  | mk_sumcases _ f T = f T
    4.53 +
    4.54 +
    4.55 +(** abstract syntax **)
    4.56 +
    4.57 +val size = @{term "i :: code_numeral"}
    4.58 +val size_pred = @{term "(i :: code_numeral) - 1"}
    4.59 +val size_ge_zero = @{term "(i :: code_numeral) > 0"}
    4.60 +fun test_function T = Free ("f", T --> @{typ "term list option"})
    4.61 +
    4.62 +fun mk_none_continuation (x, y) =
    4.63 +  let
    4.64 +    val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
    4.65 +  in
    4.66 +    Const (@{const_name Option.option_case}, T --> (T' --> T) --> T --> T)
    4.67 +      $ y $ Const (@{const_name Some}, T' --> T) $ x
    4.68 +  end
    4.69 +
    4.70 +(** datatypes **)
    4.71 +
    4.72 +(* constructing smallvalue generator instances on datatypes *)
    4.73 +
    4.74 +exception FUNCTION_TYPE;
    4.75 +
    4.76 +val smallN = "small";
    4.77 +
    4.78 +fun smallT T = (T --> @{typ "Code_Evaluation.term list option"}) --> @{typ code_numeral}
    4.79 +  --> @{typ "Code_Evaluation.term list option"}
    4.80 +
    4.81 +fun mk_equations thy descr vs tycos (names, auxnames) (Ts, Us) =
    4.82 +  let
    4.83 +    val smallsN = map (prefix (smallN ^ "_")) (names @ auxnames);
    4.84 +    val smalls = map2 (fn name => fn T => Free (name, smallT T))
    4.85 +      smallsN (Ts @ Us)
    4.86 +    fun mk_small_call T =
    4.87 +      let
    4.88 +        val small = Const (@{const_name "Smallcheck.small_class.small"}, smallT T)        
    4.89 +      in
    4.90 +        (T, (fn t => small $ absdummy (T, t) $ size_pred))
    4.91 +      end
    4.92 +    fun mk_small_aux_call fTs (k, _) (tyco, Ts) =
    4.93 +      let
    4.94 +        val T = Type (tyco, Ts)
    4.95 +        val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
    4.96 +        val small = nth smalls k
    4.97 +      in
    4.98 +        (T, (fn t => small $ absdummy (T, t) $ size_pred))
    4.99 +      end
   4.100 +    fun mk_consexpr simpleT (c, xs) =
   4.101 +      let
   4.102 +        val (Ts, fns) = split_list xs
   4.103 +        val constr = Const (c, Ts ---> simpleT)
   4.104 +        val bounds = map Bound (((length xs) - 1) downto 0)
   4.105 +        val start_term = test_function simpleT $ (list_comb (constr, bounds))
   4.106 +      in fold_rev (fn f => fn t => f t) fns start_term end
   4.107 +    fun mk_rhs exprs =
   4.108 +        @{term "If :: bool => term list option => term list option => term list option"}
   4.109 +            $ size_ge_zero $ (foldr1 mk_none_continuation exprs) $ @{term "None :: term list option"}
   4.110 +    val rhss =
   4.111 +      Datatype_Aux.interpret_construction descr vs
   4.112 +        { atyp = mk_small_call, dtyp = mk_small_aux_call }
   4.113 +      |> (map o apfst) Type
   4.114 +      |> map (fn (T, cs) => map (mk_consexpr T) cs)
   4.115 +      |> map mk_rhs
   4.116 +    val lhss = map2 (fn t => fn T => t $ test_function T $ size) smalls (Ts @ Us);
   4.117 +    val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
   4.118 +  in
   4.119 +    (Ts @ Us ~~ (smallsN ~~ eqs))
   4.120 +  end
   4.121 +    
   4.122 +val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
   4.123 +
   4.124 +fun gen_inst_state_tac ctxt rel st =
   4.125 +  case Term.add_vars (prop_of st) [] of
   4.126 +    [v as (_, T)] =>
   4.127 +      let
   4.128 +        val cert = Thm.cterm_of (ProofContext.theory_of ctxt)
   4.129 +        val rel' = cert rel
   4.130 +        val st' = Thm.incr_indexes (#maxidx (Thm.rep_cterm rel') + 1) st (*FIXME??*)
   4.131 +      in        
   4.132 +        PRIMITIVE (Drule.cterm_instantiate [(cert (Var v), rel')]) st'
   4.133 +      end
   4.134 +  | _ => Seq.empty;
   4.135 +
   4.136 +fun instantiate_smallvalue_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   4.137 +  let
   4.138 +    val _ = Datatype_Aux.message config "Creating smallvalue generators ...";
   4.139 +    val eqs = mk_equations thy descr vs tycos (names, auxnames) (Ts, Us)
   4.140 +    fun my_relation_tac ctxt st =
   4.141 +      let
   4.142 +        val ((_ $ (_ $ rel)) :: tl) = prems_of st
   4.143 +        val domT = (HOLogic.dest_setT (fastype_of rel))
   4.144 +        fun mk_single_measure T = mk_fun_comp (@{term "Code_Numeral.nat_of"},
   4.145 +            Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
   4.146 +        val measure = mk_measure (mk_sumcases @{typ nat} mk_single_measure domT)
   4.147 +      in
   4.148 +        (Function_Common.apply_termination_rule ctxt 1
   4.149 +        THEN gen_inst_state_tac ctxt measure) st
   4.150 +      end
   4.151 +    fun termination_tac ctxt = 
   4.152 +      my_relation_tac ctxt
   4.153 +      THEN rtac @{thm wf_measure} 1
   4.154 +      THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
   4.155 +        (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
   4.156 +         @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
   4.157 +    fun pat_completeness_auto ctxt =
   4.158 +      Pat_Completeness.pat_completeness_tac ctxt 1
   4.159 +      THEN auto_tac (clasimpset_of ctxt)
   4.160 +  in
   4.161 +    thy
   4.162 +    |> Class.instantiation (tycos, vs, @{sort small})
   4.163 +    |> Function.add_function
   4.164 +      (map (fn (T, (name, _)) =>
   4.165 +          Syntax.no_syn (Binding.conceal (Binding.name name), SOME (smallT T))) eqs)
   4.166 +        (map (pair (apfst Binding.conceal Attrib.empty_binding) o snd o snd) eqs)
   4.167 +        Function_Common.default_config pat_completeness_auto
   4.168 +    |> snd
   4.169 +    |> Local_Theory.restore
   4.170 +    |> (fn lthy => Function.prove_termination NONE (termination_tac lthy) lthy)
   4.171 +    |> snd
   4.172 +    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   4.173 +  end;
   4.174 +
   4.175 +fun ensure_smallvalue_datatype config raw_tycos thy =
   4.176 +  let
   4.177 +    val algebra = Sign.classes_of thy;
   4.178 +    val (descr, raw_vs, tycos, prfx, (names, auxnames), raw_TUs) =
   4.179 +      Datatype.the_descr thy raw_tycos;
   4.180 +    val typerep_vs = (map o apsnd)
   4.181 +      (curry (Sorts.inter_sort algebra) @{sort typerep}) raw_vs;
   4.182 +    val smallvalue_insts = (map (rpair @{sort small}) o flat o maps snd o maps snd)
   4.183 +      (Datatype_Aux.interpret_construction descr typerep_vs
   4.184 +        { atyp = single, dtyp = (K o K o K) [] });
   4.185 +    (*val term_of_insts = (map (rpair @{sort term_of}) o flat o maps snd o maps snd)
   4.186 +      (Datatype_Aux.interpret_construction descr typerep_vs
   4.187 +        { atyp = K [], dtyp = K o K });*)
   4.188 +    val has_inst = exists (fn tyco =>
   4.189 +      can (Sorts.mg_domain algebra tyco) @{sort small}) tycos;
   4.190 +  in if has_inst then thy
   4.191 +    else case Quickcheck_Generators.perhaps_constrain thy smallvalue_insts typerep_vs
   4.192 +     of SOME constrain => (instantiate_smallvalue_datatype config descr
   4.193 +          (map constrain typerep_vs) tycos prfx (names, auxnames)
   4.194 +            ((pairself o map o map_atyps) (fn TFree v => TFree (constrain v)) raw_TUs) thy
   4.195 +            handle FUNCTION_TYPE =>
   4.196 +              (Datatype_Aux.message config
   4.197 +                "Creation of smallvalue generators failed because the datatype contains a function type";
   4.198 +              thy))
   4.199 +      | NONE => thy
   4.200 +  end;
   4.201 +
   4.202 +(** building and compiling generator expressions **)
   4.203 +
   4.204 +structure Counterexample = Proof_Data (
   4.205 +  type T = unit -> int -> term list option
   4.206 +  fun init _ () = error "Counterexample"
   4.207 +);
   4.208 +val put_counterexample = Counterexample.put;
   4.209 +
   4.210 +val target = "Quickcheck";
   4.211 +
   4.212 +fun mk_generator_expr thy prop Ts =
   4.213 +  let
   4.214 +    val bound_max = length Ts - 1;
   4.215 +    val bounds = map Bound (bound_max downto 0)
   4.216 +    val result = list_comb (prop, bounds);
   4.217 +    val terms = HOLogic.mk_list @{typ term} (map2 HOLogic.mk_term_of Ts bounds);
   4.218 +    val check =
   4.219 +      @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
   4.220 +        (@{term "If :: bool => term list option => term list option => term list option"}
   4.221 +        $ result $ @{term "None :: term list option"}
   4.222 +        $ (@{term "Some :: term list => term list option"} $ terms))
   4.223 +      $ @{term "None :: term list option"};
   4.224 +    fun mk_small_closure (depth, T) t =
   4.225 +      Const (@{const_name "Smallcheck.small_class.small"}, smallT T)
   4.226 +        $ absdummy (T, t) $ depth
   4.227 +  in Abs ("d", @{typ code_numeral}, fold_rev mk_small_closure (rev bounds ~~ Ts) check) end
   4.228 +
   4.229 +fun compile_generator_expr ctxt t =
   4.230 +  let
   4.231 +    val Ts = (map snd o fst o strip_abs) t;
   4.232 +    val thy = ProofContext.theory_of ctxt
   4.233 +  in if Quickcheck.report ctxt then
   4.234 +    error "Compilation with reporting facility is not supported"
   4.235 +  else
   4.236 +    let
   4.237 +      val t' = mk_generator_expr thy t Ts;
   4.238 +      val compile = Code_Runtime.dynamic_value_strict
   4.239 +        (Counterexample.get, put_counterexample, "Smallvalue_Generators.put_counterexample")
   4.240 +        thy (SOME target) (fn proc => fn g => g #> (Option.map o map) proc) t' [];
   4.241 +      val dummy_report = ([], false)
   4.242 +    in compile #> rpair dummy_report end
   4.243 +  end;
   4.244 +
   4.245 +(** setup **)
   4.246 +
   4.247 +val setup =
   4.248 +  Datatype.interpretation ensure_smallvalue_datatype
   4.249 +  #> Context.theory_map
   4.250 +    (Quickcheck.add_generator ("small", compile_generator_expr));
   4.251 +
   4.252 +end;