src/HOL/Tools/datatype_realizer.ML
author berghofe
Wed Aug 07 16:46:15 2002 +0200 (2002-08-07)
changeset 13467 d66b526192bf
child 13641 63d1790a43ed
permissions -rw-r--r--
Module for defining realizers for induction and case analysis theorems
for datatypes.
     1 (*  Title:      HOL/Tools/datatype_realizer.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Porgram extraction from proofs involving datatypes:
     7 Realizers for induction and case analysis
     8 *)
     9 
    10 signature DATATYPE_REALIZER =
    11 sig
    12   val add_dt_realizers: (string * sort) list ->
    13     DatatypeAux.datatype_info list -> theory -> theory
    14 end;
    15 
    16 structure DatatypeRealizer : DATATYPE_REALIZER =
    17 struct
    18 
    19 open DatatypeAux;
    20 
    21 fun subsets i j = if i <= j then
    22        let val is = subsets (i+1) j
    23        in map (fn ks => i::ks) is @ is end
    24      else [[]];
    25 
    26 fun forall_intr_prf (t, prf) =
    27   let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
    28   in Abst (a, Some T, Proofterm.prf_abstract_over t prf) end;
    29 
    30 fun prove_goal' sg p f =
    31   let
    32     val (_, As, B) = Logic.strip_horn p;
    33     val cAs = map (cterm_of sg) As;
    34     val asms = map (norm_hhf_rule o assume) cAs;
    35     fun check thm = if nprems_of thm > 0 then
    36       error "prove_goal': unsolved goals" else thm
    37   in
    38     standard (implies_intr_list cAs
    39       (check (Seq.hd (EVERY (f asms) (trivial (cterm_of sg B))))))
    40   end;
    41 
    42 fun prf_of thm =
    43   let val {sign, prop, der = (_, prf), ...} = rep_thm thm
    44   in Reconstruct.reconstruct_proof sign prop prf end;
    45 
    46 fun prf_subst_vars inst =
    47   Proofterm.map_proof_terms (subst_vars ([], inst)) I;
    48 
    49 fun is_unit t = snd (strip_type (fastype_of t)) = HOLogic.unitT;
    50 
    51 fun mk_realizes T = Const ("realizes", T --> HOLogic.boolT --> HOLogic.boolT);
    52 
    53 fun make_ind sorts ({descr, rec_names, rec_rewrites, induction, ...} : datatype_info) (is, thy) =
    54   let
    55     val sg = sign_of thy;
    56     val recTs = get_rec_types descr sorts;
    57     val pnames = if length descr = 1 then ["P"]
    58       else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
    59 
    60     val rec_result_Ts = map (fn ((i, _), P) =>
    61       if i mem is then TFree ("'" ^ P, HOLogic.typeS) else HOLogic.unitT)
    62         (descr ~~ pnames);
    63 
    64     fun make_pred i T U r x =
    65       if i mem is then
    66         Free (nth_elem (i, pnames), T --> U --> HOLogic.boolT) $ r $ x
    67       else Free (nth_elem (i, pnames), U --> HOLogic.boolT) $ x;
    68 
    69     fun mk_all i s T t =
    70       if i mem is then list_all_free ([(s, T)], t) else t;
    71 
    72     val (prems, rec_fns) = split_list (flat (snd (foldl_map
    73       (fn (j, ((i, (_, _, constrs)), T)) => foldl_map (fn (j, (cname, cargs)) =>
    74         let
    75           val Ts = map (typ_of_dtyp descr sorts) cargs;
    76           val tnames = variantlist (DatatypeProp.make_tnames Ts, pnames);
    77           val recs = filter (is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
    78           val frees = tnames ~~ Ts;
    79 
    80           fun mk_prems vs [] = 
    81                 let
    82                   val rT = nth_elem (i, rec_result_Ts);
    83                   val vs' = filter_out is_unit vs;
    84                   val f = mk_Free "f" (map fastype_of vs' ---> rT) j;
    85                   val f' = Pattern.eta_contract (list_abs_free
    86                     (map dest_Free vs, if i mem is then list_comb (f, vs')
    87                       else HOLogic.unit));
    88                 in (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
    89                   (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
    90                 end
    91             | mk_prems vs (((DtRec k, s), T) :: ds) = 
    92                 let
    93                   val rT = nth_elem (k, rec_result_Ts);
    94                   val r = Free ("r" ^ s, rT);
    95                   val (p, f) = mk_prems (vs @ [r]) ds
    96                 in (mk_all k ("r" ^ s) rT (Logic.mk_implies
    97                   (HOLogic.mk_Trueprop (make_pred k rT T r (Free (s, T))), p)), f)
    98                 end
    99             | mk_prems vs (((DtType ("fun", [_, DtRec k]), s),
   100                   T' as Type ("fun", [T, U])) :: ds) =
   101                 let
   102                   val rT = nth_elem (k, rec_result_Ts);
   103                   val r = Free ("r" ^ s, T --> rT);
   104                   val (p, f) = mk_prems (vs @ [r]) ds
   105                 in (mk_all k ("r" ^ s) (T --> rT) (Logic.mk_implies
   106                   (all T $ Abs ("x", T, HOLogic.mk_Trueprop (make_pred k rT U
   107                     (r $ Bound 0) (Free (s, T') $ Bound 0))), p)), f)
   108                 end
   109 
   110         in (j + 1,
   111           apfst (curry list_all_free frees) (mk_prems (map Free frees) recs))
   112         end) (j, constrs)) (1, descr ~~ recTs))));
   113  
   114     fun mk_proj j [] t = t
   115       | mk_proj j (i :: is) t = if null is then t else
   116           if j = i then HOLogic.mk_fst t
   117           else mk_proj j is (HOLogic.mk_snd t);
   118 
   119     val tnames = DatatypeProp.make_tnames recTs;
   120     val fTs = map fastype_of rec_fns;
   121     val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
   122       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
   123         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
   124     val r = if null is then Extraction.nullt else
   125       foldr1 HOLogic.mk_prod (mapfilter (fn (((((i, _), T), U), s), tname) =>
   126         if i mem is then Some
   127           (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   128         else None) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   129     val concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
   130       (map (fn ((((i, _), T), U), tname) =>
   131         make_pred i U T (mk_proj i is r) (Free (tname, T)))
   132           (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   133     val cert = cterm_of sg;
   134     val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
   135       (HOLogic.dest_Trueprop (concl_of induction))) ~~ ps);
   136 
   137     val thm = prove_goal' sg (Logic.list_implies (prems, concl))
   138       (fn prems =>
   139          [rewrite_goals_tac (map mk_meta_eq [fst_conv, snd_conv]),
   140           rtac (cterm_instantiate inst induction) 1,
   141           ALLGOALS ObjectLogic.atomize_tac,
   142           rewrite_goals_tac (o_def :: map mk_meta_eq rec_rewrites),
   143           REPEAT ((resolve_tac prems THEN_ALL_NEW (fn i =>
   144             REPEAT (etac allE i) THEN atac i)) 1)]);
   145 
   146     val {path, ...} = Sign.rep_sg sg;
   147     val ind_name = Thm.name_of_thm induction;
   148     val vs = map (fn i => nth_elem (i, pnames)) is;
   149     val (thy', thm') = thy
   150       |> Theory.absolute_path
   151       |> PureThy.store_thm
   152         ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
   153       |>> Theory.add_path (NameSpace.pack (if_none path []));
   154 
   155     val inst = map (fn ((((i, _), s), T), U) => ((s, 0), if i mem is then
   156         Abs ("r", U, Abs ("x", T, mk_realizes U $ Bound 1 $
   157           (Var ((s, 0), T --> HOLogic.boolT) $ Bound 0)))
   158       else Abs ("x", T, mk_realizes Extraction.nullT $ Extraction.nullt $
   159         (Var ((s, 0), T --> HOLogic.boolT) $
   160           Bound 0)))) (descr ~~ pnames ~~ map Type.varifyT recTs ~~
   161             map Type.varifyT rec_result_Ts);
   162 
   163     val ivs = map Var (Drule.vars_of_terms
   164       [Logic.varify (DatatypeProp.make_ind [descr] sorts)]);
   165 
   166     val prf = foldr forall_intr_prf (ivs,
   167       prf_subst_vars inst (foldr (fn ((f, p), prf) =>
   168         (case head_of (strip_abs_body f) of
   169            Free (s, T) =>
   170              let val T' = Type.varifyT T
   171              in Abst (s, Some T', Proofterm.prf_abstract_over
   172                (Var ((s, 0), T')) (AbsP ("H", Some p, prf)))
   173              end
   174          | _ => AbsP ("H", Some p, prf)))
   175            (rec_fns ~~ prems_of thm, Proofterm.proof_combP
   176              (prf_of thm', map PBound (length prems - 1 downto 0)))));
   177 
   178     val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
   179       (map Logic.unvarify ivs @ filter_out is_unit
   180         (map (head_of o strip_abs_body) rec_fns), r));
   181 
   182   in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   183 
   184 
   185 fun make_casedists sorts ({index, descr, case_name, case_rewrites, exhaustion, ...} : datatype_info, thy) =
   186   let
   187     val sg = sign_of thy;
   188     val sorts = map (rpair HOLogic.typeS) (distinct (flat (map
   189       (fn (_, (_, ds, _)) => mapfilter (try dest_DtTFree) ds) descr)));
   190     val cert = cterm_of sg;
   191     val rT = TFree ("'P", HOLogic.typeS);
   192     val rT' = TVar (("'P", 0), HOLogic.typeS);
   193 
   194     fun make_casedist_prem T (cname, cargs) =
   195       let
   196         val Ts = map (typ_of_dtyp descr sorts) cargs;
   197         val frees = variantlist
   198           (DatatypeProp.make_tnames Ts, ["P", "y"]) ~~ Ts;
   199         val free_ts = map Free frees;
   200         val r = Free ("r" ^ NameSpace.base cname, Ts ---> rT)
   201       in (r, list_all_free (frees, Logic.mk_implies (HOLogic.mk_Trueprop
   202         (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   203           HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   204             list_comb (r, free_ts)))))
   205       end;
   206 
   207     val Some (_, _, constrs) = assoc (descr, index);
   208     val T = nth_elem (index, get_rec_types descr sorts);
   209     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   210     val r = Const (case_name, map fastype_of rs ---> T --> rT);
   211 
   212     val y = Var (("y", 0), Type.varifyT T);
   213     val y' = Free ("y", T);
   214 
   215     val thm = prove_goalw_cterm [] (cert (Logic.list_implies (prems,
   216       HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   217         list_comb (r, rs @ [y'])))))
   218       (fn prems =>
   219          [rtac (cterm_instantiate [(cert y, cert y')] exhaustion) 1,
   220           ALLGOALS (EVERY'
   221             [asm_simp_tac (HOL_basic_ss addsimps case_rewrites),
   222              resolve_tac prems, asm_simp_tac HOL_basic_ss])]);
   223 
   224     val {path, ...} = Sign.rep_sg sg;
   225     val exh_name = Thm.name_of_thm exhaustion;
   226     val (thy', thm') = thy
   227       |> Theory.absolute_path
   228       |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
   229       |>> Theory.add_path (NameSpace.pack (if_none path []));
   230 
   231     val P = Var (("P", 0), HOLogic.boolT);
   232     val prf = forall_intr_prf (y, forall_intr_prf (P,
   233       prf_subst_vars [(("P", 0), Abs ("r", rT',
   234         mk_realizes rT' $ Bound 0 $ P))] (foldr (fn ((p, r), prf) =>
   235           forall_intr_prf (Logic.varify r, AbsP ("H", Some (Logic.varify p),
   236             prf))) (prems ~~ rs, Proofterm.proof_combP (prf_of thm',
   237               map PBound (length prems - 1 downto 0))))));
   238     val r' = Logic.varify (Abs ("y", Type.varifyT T,
   239       Abs ("P", HOLogic.boolT, list_abs (map dest_Free rs, list_comb (r,
   240         map Bound ((length rs - 1 downto 0) @ [length rs + 1]))))));
   241 
   242     val prf' = forall_intr_prf (y, forall_intr_prf (P, prf_subst_vars
   243       [(("P", 0), mk_realizes Extraction.nullT $ Extraction.nullt $ P)]
   244         (prf_of exhaustion)));
   245 
   246   in Extraction.add_realizers_i
   247     [(exh_name, (["P"], r', prf)),
   248      (exh_name, ([], Extraction.nullt, prf'))] thy'
   249   end;
   250 
   251 
   252 fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
   253   (message "Adding realizers for induction and case analysis ..."; thy
   254    |> curry (foldr (make_ind sorts (hd infos)))
   255      (subsets 0 (length (#descr (hd infos)) - 1))
   256    |> curry (foldr (make_casedists sorts)) infos);
   257 
   258 end;