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