src/HOL/Tools/smallvalue_generators.ML
changeset 40420 552563ea3304
child 40639 f1f0e6adca0a
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/smallvalue_generators.ML	Mon Nov 08 09:25:43 2010 +0100
     1.3 @@ -0,0 +1,249 @@
     1.4 +(*  Title:      HOL/Tools/smallvalue_generators.ML
     1.5 +    Author:     Lukas Bulwahn, TU Muenchen
     1.6 +
     1.7 +Generators for small values for various types.
     1.8 +*)
     1.9 +
    1.10 +signature SMALLVALUE_GENERATORS =
    1.11 +sig
    1.12 +  val ensure_smallvalue_datatype: Datatype.config -> string list -> theory -> theory
    1.13 +  val compile_generator_expr:
    1.14 +    Proof.context -> term -> int -> term list option * (bool list * bool)
    1.15 +  val put_counterexample: (unit -> int -> term list option)
    1.16 +    -> Proof.context -> Proof.context
    1.17 +  val setup: theory -> theory
    1.18 +end;
    1.19 +
    1.20 +structure Smallvalue_Generators : SMALLVALUE_GENERATORS =
    1.21 +struct
    1.22 +
    1.23 +(** general term functions **)
    1.24 +
    1.25 +fun dest_funT (Type ("fun",[S, T])) = (S, T)
    1.26 +  | dest_funT T = raise TYPE ("dest_funT", [T], [])
    1.27 + 
    1.28 +fun mk_fun_comp (t, u) =
    1.29 +  let
    1.30 +    val (_, B) = dest_funT (fastype_of t)
    1.31 +    val (C, A) = dest_funT (fastype_of u)
    1.32 +  in
    1.33 +    Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
    1.34 +  end;
    1.35 +
    1.36 +fun mk_measure f =
    1.37 +  let
    1.38 +    val Type ("fun", [T, @{typ nat}]) = fastype_of f 
    1.39 +  in
    1.40 +    Const (@{const_name Wellfounded.measure},
    1.41 +      (T --> @{typ nat}) --> HOLogic.mk_prodT (T, T) --> @{typ bool})
    1.42 +    $ f
    1.43 +  end
    1.44 +
    1.45 +fun mk_sumcases rT f (Type (@{type_name Sum_Type.sum}, [TL, TR])) =
    1.46 +  let
    1.47 +    val lt = mk_sumcases rT f TL
    1.48 +    val rt = mk_sumcases rT f TR
    1.49 +  in
    1.50 +    SumTree.mk_sumcase TL TR rT lt rt
    1.51 +  end
    1.52 +  | mk_sumcases _ f T = f T
    1.53 +
    1.54 +
    1.55 +(** abstract syntax **)
    1.56 +
    1.57 +val size = @{term "i :: code_numeral"}
    1.58 +val size_pred = @{term "(i :: code_numeral) - 1"}
    1.59 +val size_ge_zero = @{term "(i :: code_numeral) > 0"}
    1.60 +fun test_function T = Free ("f", T --> @{typ "term list option"})
    1.61 +
    1.62 +fun mk_none_continuation (x, y) =
    1.63 +  let
    1.64 +    val (T as Type(@{type_name "option"}, [T'])) = fastype_of x
    1.65 +  in
    1.66 +    Const (@{const_name Option.option_case}, T --> (T' --> T) --> T --> T)
    1.67 +      $ y $ Const (@{const_name Some}, T' --> T) $ x
    1.68 +  end
    1.69 +
    1.70 +(** datatypes **)
    1.71 +
    1.72 +(* constructing smallvalue generator instances on datatypes *)
    1.73 +
    1.74 +exception FUNCTION_TYPE;
    1.75 +
    1.76 +val smallN = "small";
    1.77 +
    1.78 +fun smallT T = (T --> @{typ "Code_Evaluation.term list option"}) --> @{typ code_numeral}
    1.79 +  --> @{typ "Code_Evaluation.term list option"}
    1.80 +
    1.81 +fun mk_equations thy descr vs tycos (names, auxnames) (Ts, Us) =
    1.82 +  let
    1.83 +    val smallsN = map (prefix (smallN ^ "_")) (names @ auxnames);
    1.84 +    val smalls = map2 (fn name => fn T => Free (name, smallT T))
    1.85 +      smallsN (Ts @ Us)
    1.86 +    fun mk_small_call T =
    1.87 +      let
    1.88 +        val small = Const (@{const_name "Smallcheck.small_class.small"}, smallT T)        
    1.89 +      in
    1.90 +        (T, (fn t => small $ absdummy (T, t) $ size_pred))
    1.91 +      end
    1.92 +    fun mk_small_aux_call fTs (k, _) (tyco, Ts) =
    1.93 +      let
    1.94 +        val T = Type (tyco, Ts)
    1.95 +        val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
    1.96 +        val small = nth smalls k
    1.97 +      in
    1.98 +        (T, (fn t => small $ absdummy (T, t) $ size_pred))
    1.99 +      end
   1.100 +    fun mk_consexpr simpleT (c, xs) =
   1.101 +      let
   1.102 +        val (Ts, fns) = split_list xs
   1.103 +        val constr = Const (c, Ts ---> simpleT)
   1.104 +        val bounds = map Bound (((length xs) - 1) downto 0)
   1.105 +        val start_term = test_function simpleT $ (list_comb (constr, bounds))
   1.106 +      in fold_rev (fn f => fn t => f t) fns start_term end
   1.107 +    fun mk_rhs exprs =
   1.108 +        @{term "If :: bool => term list option => term list option => term list option"}
   1.109 +            $ size_ge_zero $ (foldr1 mk_none_continuation exprs) $ @{term "None :: term list option"}
   1.110 +    val rhss =
   1.111 +      Datatype_Aux.interpret_construction descr vs
   1.112 +        { atyp = mk_small_call, dtyp = mk_small_aux_call }
   1.113 +      |> (map o apfst) Type
   1.114 +      |> map (fn (T, cs) => map (mk_consexpr T) cs)
   1.115 +      |> map mk_rhs
   1.116 +    val lhss = map2 (fn t => fn T => t $ test_function T $ size) smalls (Ts @ Us);
   1.117 +    val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
   1.118 +  in
   1.119 +    (Ts @ Us ~~ (smallsN ~~ eqs))
   1.120 +  end
   1.121 +    
   1.122 +val less_int_pred = @{lemma "i > 0 ==> Code_Numeral.nat_of ((i :: code_numeral) - 1) < Code_Numeral.nat_of i" by auto}
   1.123 +
   1.124 +fun gen_inst_state_tac ctxt rel st =
   1.125 +  case Term.add_vars (prop_of st) [] of
   1.126 +    [v as (_, T)] =>
   1.127 +      let
   1.128 +        val cert = Thm.cterm_of (ProofContext.theory_of ctxt)
   1.129 +        val rel' = cert rel
   1.130 +        val st' = Thm.incr_indexes (#maxidx (Thm.rep_cterm rel') + 1) st (*FIXME??*)
   1.131 +      in        
   1.132 +        PRIMITIVE (Drule.cterm_instantiate [(cert (Var v), rel')]) st'
   1.133 +      end
   1.134 +  | _ => Seq.empty;
   1.135 +
   1.136 +fun instantiate_smallvalue_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   1.137 +  let
   1.138 +    val _ = Datatype_Aux.message config "Creating smallvalue generators ...";
   1.139 +    val eqs = mk_equations thy descr vs tycos (names, auxnames) (Ts, Us)
   1.140 +    fun my_relation_tac ctxt st =
   1.141 +      let
   1.142 +        val ((_ $ (_ $ rel)) :: tl) = prems_of st
   1.143 +        val domT = (HOLogic.dest_setT (fastype_of rel))
   1.144 +        fun mk_single_measure T = mk_fun_comp (@{term "Code_Numeral.nat_of"},
   1.145 +            Const (@{const_name "Product_Type.snd"}, T --> @{typ "code_numeral"}))
   1.146 +        val measure = mk_measure (mk_sumcases @{typ nat} mk_single_measure domT)
   1.147 +      in
   1.148 +        (Function_Common.apply_termination_rule ctxt 1
   1.149 +        THEN gen_inst_state_tac ctxt measure) st
   1.150 +      end
   1.151 +    fun termination_tac ctxt = 
   1.152 +      my_relation_tac ctxt
   1.153 +      THEN rtac @{thm wf_measure} 1
   1.154 +      THEN (REPEAT_DETERM (Simplifier.asm_full_simp_tac 
   1.155 +        (HOL_basic_ss addsimps [@{thm in_measure}, @{thm o_def}, @{thm snd_conv},
   1.156 +         @{thm nat_mono_iff}, less_int_pred] @ @{thms sum.cases}) 1))
   1.157 +    fun pat_completeness_auto ctxt =
   1.158 +      Pat_Completeness.pat_completeness_tac ctxt 1
   1.159 +      THEN auto_tac (clasimpset_of ctxt)
   1.160 +  in
   1.161 +    thy
   1.162 +    |> Class.instantiation (tycos, vs, @{sort small})
   1.163 +    |> Function.add_function
   1.164 +      (map (fn (T, (name, _)) =>
   1.165 +          Syntax.no_syn (Binding.conceal (Binding.name name), SOME (smallT T))) eqs)
   1.166 +        (map (pair (apfst Binding.conceal Attrib.empty_binding) o snd o snd) eqs)
   1.167 +        Function_Common.default_config pat_completeness_auto
   1.168 +    |> snd
   1.169 +    |> Local_Theory.restore
   1.170 +    |> (fn lthy => Function.prove_termination NONE (termination_tac lthy) lthy)
   1.171 +    |> snd
   1.172 +    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   1.173 +  end;
   1.174 +
   1.175 +fun ensure_smallvalue_datatype config raw_tycos thy =
   1.176 +  let
   1.177 +    val algebra = Sign.classes_of thy;
   1.178 +    val (descr, raw_vs, tycos, prfx, (names, auxnames), raw_TUs) =
   1.179 +      Datatype.the_descr thy raw_tycos;
   1.180 +    val typerep_vs = (map o apsnd)
   1.181 +      (curry (Sorts.inter_sort algebra) @{sort typerep}) raw_vs;
   1.182 +    val smallvalue_insts = (map (rpair @{sort small}) o flat o maps snd o maps snd)
   1.183 +      (Datatype_Aux.interpret_construction descr typerep_vs
   1.184 +        { atyp = single, dtyp = (K o K o K) [] });
   1.185 +    (*val term_of_insts = (map (rpair @{sort term_of}) o flat o maps snd o maps snd)
   1.186 +      (Datatype_Aux.interpret_construction descr typerep_vs
   1.187 +        { atyp = K [], dtyp = K o K });*)
   1.188 +    val has_inst = exists (fn tyco =>
   1.189 +      can (Sorts.mg_domain algebra tyco) @{sort small}) tycos;
   1.190 +  in if has_inst then thy
   1.191 +    else case Quickcheck_Generators.perhaps_constrain thy smallvalue_insts typerep_vs
   1.192 +     of SOME constrain => (instantiate_smallvalue_datatype config descr
   1.193 +          (map constrain typerep_vs) tycos prfx (names, auxnames)
   1.194 +            ((pairself o map o map_atyps) (fn TFree v => TFree (constrain v)) raw_TUs) thy
   1.195 +            handle FUNCTION_TYPE =>
   1.196 +              (Datatype_Aux.message config
   1.197 +                "Creation of smallvalue generators failed because the datatype contains a function type";
   1.198 +              thy))
   1.199 +      | NONE => thy
   1.200 +  end;
   1.201 +
   1.202 +(** building and compiling generator expressions **)
   1.203 +
   1.204 +structure Counterexample = Proof_Data (
   1.205 +  type T = unit -> int -> term list option
   1.206 +  fun init _ () = error "Counterexample"
   1.207 +);
   1.208 +val put_counterexample = Counterexample.put;
   1.209 +
   1.210 +val target = "Quickcheck";
   1.211 +
   1.212 +fun mk_generator_expr thy prop Ts =
   1.213 +  let
   1.214 +    val bound_max = length Ts - 1;
   1.215 +    val bounds = map Bound (bound_max downto 0)
   1.216 +    val result = list_comb (prop, bounds);
   1.217 +    val terms = HOLogic.mk_list @{typ term} (map2 HOLogic.mk_term_of Ts bounds);
   1.218 +    val check =
   1.219 +      @{term "Smallcheck.catch_match :: term list option => term list option => term list option"} $
   1.220 +        (@{term "If :: bool => term list option => term list option => term list option"}
   1.221 +        $ result $ @{term "None :: term list option"}
   1.222 +        $ (@{term "Some :: term list => term list option"} $ terms))
   1.223 +      $ @{term "None :: term list option"};
   1.224 +    fun mk_small_closure (depth, T) t =
   1.225 +      Const (@{const_name "Smallcheck.small_class.small"}, smallT T)
   1.226 +        $ absdummy (T, t) $ depth
   1.227 +  in Abs ("d", @{typ code_numeral}, fold_rev mk_small_closure (rev bounds ~~ Ts) check) end
   1.228 +
   1.229 +fun compile_generator_expr ctxt t =
   1.230 +  let
   1.231 +    val Ts = (map snd o fst o strip_abs) t;
   1.232 +    val thy = ProofContext.theory_of ctxt
   1.233 +  in if Quickcheck.report ctxt then
   1.234 +    error "Compilation with reporting facility is not supported"
   1.235 +  else
   1.236 +    let
   1.237 +      val t' = mk_generator_expr thy t Ts;
   1.238 +      val compile = Code_Runtime.dynamic_value_strict
   1.239 +        (Counterexample.get, put_counterexample, "Smallvalue_Generators.put_counterexample")
   1.240 +        thy (SOME target) (fn proc => fn g => g #> (Option.map o map) proc) t' [];
   1.241 +      val dummy_report = ([], false)
   1.242 +    in compile #> rpair dummy_report end
   1.243 +  end;
   1.244 +
   1.245 +(** setup **)
   1.246 +
   1.247 +val setup =
   1.248 +  Datatype.interpretation ensure_smallvalue_datatype
   1.249 +  #> Context.theory_map
   1.250 +    (Quickcheck.add_generator ("small", compile_generator_expr));
   1.251 +
   1.252 +end;