src/HOL/Tools/datatype_realizer.ML
changeset 13467 d66b526192bf
child 13641 63d1790a43ed
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Tools/datatype_realizer.ML	Wed Aug 07 16:46:15 2002 +0200
     1.3 @@ -0,0 +1,258 @@
     1.4 +(*  Title:      HOL/Tools/datatype_realizer.ML
     1.5 +    ID:         $Id$
     1.6 +    Author:     Stefan Berghofer, TU Muenchen
     1.7 +    License:    GPL (GNU GENERAL PUBLIC LICENSE)
     1.8 +
     1.9 +Porgram extraction from proofs involving datatypes:
    1.10 +Realizers for induction and case analysis
    1.11 +*)
    1.12 +
    1.13 +signature DATATYPE_REALIZER =
    1.14 +sig
    1.15 +  val add_dt_realizers: (string * sort) list ->
    1.16 +    DatatypeAux.datatype_info list -> theory -> theory
    1.17 +end;
    1.18 +
    1.19 +structure DatatypeRealizer : DATATYPE_REALIZER =
    1.20 +struct
    1.21 +
    1.22 +open DatatypeAux;
    1.23 +
    1.24 +fun subsets i j = if i <= j then
    1.25 +       let val is = subsets (i+1) j
    1.26 +       in map (fn ks => i::ks) is @ is end
    1.27 +     else [[]];
    1.28 +
    1.29 +fun forall_intr_prf (t, prf) =
    1.30 +  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
    1.31 +  in Abst (a, Some T, Proofterm.prf_abstract_over t prf) end;
    1.32 +
    1.33 +fun prove_goal' sg p f =
    1.34 +  let
    1.35 +    val (_, As, B) = Logic.strip_horn p;
    1.36 +    val cAs = map (cterm_of sg) As;
    1.37 +    val asms = map (norm_hhf_rule o assume) cAs;
    1.38 +    fun check thm = if nprems_of thm > 0 then
    1.39 +      error "prove_goal': unsolved goals" else thm
    1.40 +  in
    1.41 +    standard (implies_intr_list cAs
    1.42 +      (check (Seq.hd (EVERY (f asms) (trivial (cterm_of sg B))))))
    1.43 +  end;
    1.44 +
    1.45 +fun prf_of thm =
    1.46 +  let val {sign, prop, der = (_, prf), ...} = rep_thm thm
    1.47 +  in Reconstruct.reconstruct_proof sign prop prf end;
    1.48 +
    1.49 +fun prf_subst_vars inst =
    1.50 +  Proofterm.map_proof_terms (subst_vars ([], inst)) I;
    1.51 +
    1.52 +fun is_unit t = snd (strip_type (fastype_of t)) = HOLogic.unitT;
    1.53 +
    1.54 +fun mk_realizes T = Const ("realizes", T --> HOLogic.boolT --> HOLogic.boolT);
    1.55 +
    1.56 +fun make_ind sorts ({descr, rec_names, rec_rewrites, induction, ...} : datatype_info) (is, thy) =
    1.57 +  let
    1.58 +    val sg = sign_of thy;
    1.59 +    val recTs = get_rec_types descr sorts;
    1.60 +    val pnames = if length descr = 1 then ["P"]
    1.61 +      else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
    1.62 +
    1.63 +    val rec_result_Ts = map (fn ((i, _), P) =>
    1.64 +      if i mem is then TFree ("'" ^ P, HOLogic.typeS) else HOLogic.unitT)
    1.65 +        (descr ~~ pnames);
    1.66 +
    1.67 +    fun make_pred i T U r x =
    1.68 +      if i mem is then
    1.69 +        Free (nth_elem (i, pnames), T --> U --> HOLogic.boolT) $ r $ x
    1.70 +      else Free (nth_elem (i, pnames), U --> HOLogic.boolT) $ x;
    1.71 +
    1.72 +    fun mk_all i s T t =
    1.73 +      if i mem is then list_all_free ([(s, T)], t) else t;
    1.74 +
    1.75 +    val (prems, rec_fns) = split_list (flat (snd (foldl_map
    1.76 +      (fn (j, ((i, (_, _, constrs)), T)) => foldl_map (fn (j, (cname, cargs)) =>
    1.77 +        let
    1.78 +          val Ts = map (typ_of_dtyp descr sorts) cargs;
    1.79 +          val tnames = variantlist (DatatypeProp.make_tnames Ts, pnames);
    1.80 +          val recs = filter (is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
    1.81 +          val frees = tnames ~~ Ts;
    1.82 +
    1.83 +          fun mk_prems vs [] = 
    1.84 +                let
    1.85 +                  val rT = nth_elem (i, rec_result_Ts);
    1.86 +                  val vs' = filter_out is_unit vs;
    1.87 +                  val f = mk_Free "f" (map fastype_of vs' ---> rT) j;
    1.88 +                  val f' = Pattern.eta_contract (list_abs_free
    1.89 +                    (map dest_Free vs, if i mem is then list_comb (f, vs')
    1.90 +                      else HOLogic.unit));
    1.91 +                in (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
    1.92 +                  (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
    1.93 +                end
    1.94 +            | mk_prems vs (((DtRec k, s), T) :: ds) = 
    1.95 +                let
    1.96 +                  val rT = nth_elem (k, rec_result_Ts);
    1.97 +                  val r = Free ("r" ^ s, rT);
    1.98 +                  val (p, f) = mk_prems (vs @ [r]) ds
    1.99 +                in (mk_all k ("r" ^ s) rT (Logic.mk_implies
   1.100 +                  (HOLogic.mk_Trueprop (make_pred k rT T r (Free (s, T))), p)), f)
   1.101 +                end
   1.102 +            | mk_prems vs (((DtType ("fun", [_, DtRec k]), s),
   1.103 +                  T' as Type ("fun", [T, U])) :: ds) =
   1.104 +                let
   1.105 +                  val rT = nth_elem (k, rec_result_Ts);
   1.106 +                  val r = Free ("r" ^ s, T --> rT);
   1.107 +                  val (p, f) = mk_prems (vs @ [r]) ds
   1.108 +                in (mk_all k ("r" ^ s) (T --> rT) (Logic.mk_implies
   1.109 +                  (all T $ Abs ("x", T, HOLogic.mk_Trueprop (make_pred k rT U
   1.110 +                    (r $ Bound 0) (Free (s, T') $ Bound 0))), p)), f)
   1.111 +                end
   1.112 +
   1.113 +        in (j + 1,
   1.114 +          apfst (curry list_all_free frees) (mk_prems (map Free frees) recs))
   1.115 +        end) (j, constrs)) (1, descr ~~ recTs))));
   1.116 + 
   1.117 +    fun mk_proj j [] t = t
   1.118 +      | mk_proj j (i :: is) t = if null is then t else
   1.119 +          if j = i then HOLogic.mk_fst t
   1.120 +          else mk_proj j is (HOLogic.mk_snd t);
   1.121 +
   1.122 +    val tnames = DatatypeProp.make_tnames recTs;
   1.123 +    val fTs = map fastype_of rec_fns;
   1.124 +    val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
   1.125 +      (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
   1.126 +        (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
   1.127 +    val r = if null is then Extraction.nullt else
   1.128 +      foldr1 HOLogic.mk_prod (mapfilter (fn (((((i, _), T), U), s), tname) =>
   1.129 +        if i mem is then Some
   1.130 +          (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   1.131 +        else None) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   1.132 +    val concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
   1.133 +      (map (fn ((((i, _), T), U), tname) =>
   1.134 +        make_pred i U T (mk_proj i is r) (Free (tname, T)))
   1.135 +          (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   1.136 +    val cert = cterm_of sg;
   1.137 +    val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
   1.138 +      (HOLogic.dest_Trueprop (concl_of induction))) ~~ ps);
   1.139 +
   1.140 +    val thm = prove_goal' sg (Logic.list_implies (prems, concl))
   1.141 +      (fn prems =>
   1.142 +         [rewrite_goals_tac (map mk_meta_eq [fst_conv, snd_conv]),
   1.143 +          rtac (cterm_instantiate inst induction) 1,
   1.144 +          ALLGOALS ObjectLogic.atomize_tac,
   1.145 +          rewrite_goals_tac (o_def :: map mk_meta_eq rec_rewrites),
   1.146 +          REPEAT ((resolve_tac prems THEN_ALL_NEW (fn i =>
   1.147 +            REPEAT (etac allE i) THEN atac i)) 1)]);
   1.148 +
   1.149 +    val {path, ...} = Sign.rep_sg sg;
   1.150 +    val ind_name = Thm.name_of_thm induction;
   1.151 +    val vs = map (fn i => nth_elem (i, pnames)) is;
   1.152 +    val (thy', thm') = thy
   1.153 +      |> Theory.absolute_path
   1.154 +      |> PureThy.store_thm
   1.155 +        ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
   1.156 +      |>> Theory.add_path (NameSpace.pack (if_none path []));
   1.157 +
   1.158 +    val inst = map (fn ((((i, _), s), T), U) => ((s, 0), if i mem is then
   1.159 +        Abs ("r", U, Abs ("x", T, mk_realizes U $ Bound 1 $
   1.160 +          (Var ((s, 0), T --> HOLogic.boolT) $ Bound 0)))
   1.161 +      else Abs ("x", T, mk_realizes Extraction.nullT $ Extraction.nullt $
   1.162 +        (Var ((s, 0), T --> HOLogic.boolT) $
   1.163 +          Bound 0)))) (descr ~~ pnames ~~ map Type.varifyT recTs ~~
   1.164 +            map Type.varifyT rec_result_Ts);
   1.165 +
   1.166 +    val ivs = map Var (Drule.vars_of_terms
   1.167 +      [Logic.varify (DatatypeProp.make_ind [descr] sorts)]);
   1.168 +
   1.169 +    val prf = foldr forall_intr_prf (ivs,
   1.170 +      prf_subst_vars inst (foldr (fn ((f, p), prf) =>
   1.171 +        (case head_of (strip_abs_body f) of
   1.172 +           Free (s, T) =>
   1.173 +             let val T' = Type.varifyT T
   1.174 +             in Abst (s, Some T', Proofterm.prf_abstract_over
   1.175 +               (Var ((s, 0), T')) (AbsP ("H", Some p, prf)))
   1.176 +             end
   1.177 +         | _ => AbsP ("H", Some p, prf)))
   1.178 +           (rec_fns ~~ prems_of thm, Proofterm.proof_combP
   1.179 +             (prf_of thm', map PBound (length prems - 1 downto 0)))));
   1.180 +
   1.181 +    val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
   1.182 +      (map Logic.unvarify ivs @ filter_out is_unit
   1.183 +        (map (head_of o strip_abs_body) rec_fns), r));
   1.184 +
   1.185 +  in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   1.186 +
   1.187 +
   1.188 +fun make_casedists sorts ({index, descr, case_name, case_rewrites, exhaustion, ...} : datatype_info, thy) =
   1.189 +  let
   1.190 +    val sg = sign_of thy;
   1.191 +    val sorts = map (rpair HOLogic.typeS) (distinct (flat (map
   1.192 +      (fn (_, (_, ds, _)) => mapfilter (try dest_DtTFree) ds) descr)));
   1.193 +    val cert = cterm_of sg;
   1.194 +    val rT = TFree ("'P", HOLogic.typeS);
   1.195 +    val rT' = TVar (("'P", 0), HOLogic.typeS);
   1.196 +
   1.197 +    fun make_casedist_prem T (cname, cargs) =
   1.198 +      let
   1.199 +        val Ts = map (typ_of_dtyp descr sorts) cargs;
   1.200 +        val frees = variantlist
   1.201 +          (DatatypeProp.make_tnames Ts, ["P", "y"]) ~~ Ts;
   1.202 +        val free_ts = map Free frees;
   1.203 +        val r = Free ("r" ^ NameSpace.base cname, Ts ---> rT)
   1.204 +      in (r, list_all_free (frees, Logic.mk_implies (HOLogic.mk_Trueprop
   1.205 +        (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   1.206 +          HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   1.207 +            list_comb (r, free_ts)))))
   1.208 +      end;
   1.209 +
   1.210 +    val Some (_, _, constrs) = assoc (descr, index);
   1.211 +    val T = nth_elem (index, get_rec_types descr sorts);
   1.212 +    val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   1.213 +    val r = Const (case_name, map fastype_of rs ---> T --> rT);
   1.214 +
   1.215 +    val y = Var (("y", 0), Type.varifyT T);
   1.216 +    val y' = Free ("y", T);
   1.217 +
   1.218 +    val thm = prove_goalw_cterm [] (cert (Logic.list_implies (prems,
   1.219 +      HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   1.220 +        list_comb (r, rs @ [y'])))))
   1.221 +      (fn prems =>
   1.222 +         [rtac (cterm_instantiate [(cert y, cert y')] exhaustion) 1,
   1.223 +          ALLGOALS (EVERY'
   1.224 +            [asm_simp_tac (HOL_basic_ss addsimps case_rewrites),
   1.225 +             resolve_tac prems, asm_simp_tac HOL_basic_ss])]);
   1.226 +
   1.227 +    val {path, ...} = Sign.rep_sg sg;
   1.228 +    val exh_name = Thm.name_of_thm exhaustion;
   1.229 +    val (thy', thm') = thy
   1.230 +      |> Theory.absolute_path
   1.231 +      |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
   1.232 +      |>> Theory.add_path (NameSpace.pack (if_none path []));
   1.233 +
   1.234 +    val P = Var (("P", 0), HOLogic.boolT);
   1.235 +    val prf = forall_intr_prf (y, forall_intr_prf (P,
   1.236 +      prf_subst_vars [(("P", 0), Abs ("r", rT',
   1.237 +        mk_realizes rT' $ Bound 0 $ P))] (foldr (fn ((p, r), prf) =>
   1.238 +          forall_intr_prf (Logic.varify r, AbsP ("H", Some (Logic.varify p),
   1.239 +            prf))) (prems ~~ rs, Proofterm.proof_combP (prf_of thm',
   1.240 +              map PBound (length prems - 1 downto 0))))));
   1.241 +    val r' = Logic.varify (Abs ("y", Type.varifyT T,
   1.242 +      Abs ("P", HOLogic.boolT, list_abs (map dest_Free rs, list_comb (r,
   1.243 +        map Bound ((length rs - 1 downto 0) @ [length rs + 1]))))));
   1.244 +
   1.245 +    val prf' = forall_intr_prf (y, forall_intr_prf (P, prf_subst_vars
   1.246 +      [(("P", 0), mk_realizes Extraction.nullT $ Extraction.nullt $ P)]
   1.247 +        (prf_of exhaustion)));
   1.248 +
   1.249 +  in Extraction.add_realizers_i
   1.250 +    [(exh_name, (["P"], r', prf)),
   1.251 +     (exh_name, ([], Extraction.nullt, prf'))] thy'
   1.252 +  end;
   1.253 +
   1.254 +
   1.255 +fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
   1.256 +  (message "Adding realizers for induction and case analysis ..."; thy
   1.257 +   |> curry (foldr (make_ind sorts (hd infos)))
   1.258 +     (subsets 0 (length (#descr (hd infos)) - 1))
   1.259 +   |> curry (foldr (make_casedists sorts)) infos);
   1.260 +
   1.261 +end;