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