src/HOL/Tools/datatype_realizer.ML
author haftmann
Tue Sep 20 16:17:34 2005 +0200 (2005-09-20)
changeset 17521 0f1c48de39f5
parent 16123 1381e90c2694
child 17959 8db36a108213
permissions -rw-r--r--
introduced AList module in favor of assoc etc.
     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 (List.nth (pnames, i), T --> U --> HOLogic.boolT) $ r $ x
    57       else Free (List.nth (pnames, i), 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 (List.concat (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 = List.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 = List.nth (rec_result_Ts, i);
    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 = List.nth (rec_result_Ts, k);
    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 (List.mapPartial (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 ind_name = Thm.name_of_thm induction;
   132     val vs = map (fn i => List.nth (pnames, i)) is;
   133     val (thy', thm') = thy
   134       |> Theory.absolute_path
   135       |> PureThy.store_thm
   136         ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
   137       |>> Theory.restore_naming thy;
   138 
   139     val ivs = Drule.vars_of_terms
   140       [Logic.varify (DatatypeProp.make_ind [descr] sorts)];
   141     val rvs = Drule.vars_of_terms [prop_of thm'];
   142     val ivs1 = map Var (filter_out (fn (_, T) =>
   143       tname_of (body_type T) mem ["set", "bool"]) ivs);
   144     val ivs2 = map (fn (ixn, _) => Var (ixn, valOf (AList.lookup (op =) rvs ixn))) ivs;
   145 
   146     val prf = foldr forall_intr_prf
   147      (foldr (fn ((f, p), prf) =>
   148         (case head_of (strip_abs_body f) of
   149            Free (s, T) =>
   150              let val T' = Type.varifyT T
   151              in Abst (s, SOME T', Proofterm.prf_abstract_over
   152                (Var ((s, 0), T')) (AbsP ("H", SOME p, prf)))
   153              end
   154          | _ => AbsP ("H", SOME p, prf)))
   155            (Proofterm.proof_combP
   156              (prf_of thm', map PBound (length prems - 1 downto 0))) (rec_fns ~~ prems_of thm)) ivs2;
   157 
   158     val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
   159       r (map Logic.unvarify ivs1 @ filter_out is_unit
   160           (map (head_of o strip_abs_body) rec_fns)));
   161 
   162   in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   163 
   164 
   165 fun make_casedists sorts ({index, descr, case_name, case_rewrites, exhaustion, ...} : datatype_info, thy) =
   166   let
   167     val sg = sign_of thy;
   168     val cert = cterm_of sg;
   169     val rT = TFree ("'P", HOLogic.typeS);
   170     val rT' = TVar (("'P", 0), HOLogic.typeS);
   171 
   172     fun make_casedist_prem T (cname, cargs) =
   173       let
   174         val Ts = map (typ_of_dtyp descr sorts) cargs;
   175         val frees = variantlist
   176           (DatatypeProp.make_tnames Ts, ["P", "y"]) ~~ Ts;
   177         val free_ts = map Free frees;
   178         val r = Free ("r" ^ NameSpace.base cname, Ts ---> rT)
   179       in (r, list_all_free (frees, Logic.mk_implies (HOLogic.mk_Trueprop
   180         (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   181           HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   182             list_comb (r, free_ts)))))
   183       end;
   184 
   185     val SOME (_, _, constrs) = AList.lookup (op =) descr index;
   186     val T = List.nth (get_rec_types descr sorts, index);
   187     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   188     val r = Const (case_name, map fastype_of rs ---> T --> rT);
   189 
   190     val y = Var (("y", 0), Type.varifyT T);
   191     val y' = Free ("y", T);
   192 
   193     val thm = prove_goalw_cterm [] (cert (Logic.list_implies (prems,
   194       HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   195         list_comb (r, rs @ [y'])))))
   196       (fn prems =>
   197          [rtac (cterm_instantiate [(cert y, cert y')] exhaustion) 1,
   198           ALLGOALS (EVERY'
   199             [asm_simp_tac (HOL_basic_ss addsimps case_rewrites),
   200              resolve_tac prems, asm_simp_tac HOL_basic_ss])]);
   201 
   202     val exh_name = Thm.name_of_thm exhaustion;
   203     val (thy', thm') = thy
   204       |> Theory.absolute_path
   205       |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
   206       |>> Theory.restore_naming thy;
   207 
   208     val P = Var (("P", 0), rT' --> HOLogic.boolT);
   209     val prf = forall_intr_prf (y, forall_intr_prf (P,
   210       foldr (fn ((p, r), prf) =>
   211         forall_intr_prf (Logic.varify r, AbsP ("H", SOME (Logic.varify p),
   212           prf))) (Proofterm.proof_combP (prf_of thm',
   213             map PBound (length prems - 1 downto 0))) (prems ~~ rs)));
   214     val r' = Logic.varify (Abs ("y", Type.varifyT T,
   215       list_abs (map dest_Free rs, list_comb (r,
   216         map Bound ((length rs - 1 downto 0) @ [length rs])))));
   217 
   218   in Extraction.add_realizers_i
   219     [(exh_name, (["P"], r', prf)),
   220      (exh_name, ([], Extraction.nullt, prf_of exhaustion))] thy'
   221   end;
   222 
   223 
   224 fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
   225   (message "Adding realizers for induction and case analysis ..."; thy
   226    |> curry (Library.foldr (make_ind sorts (hd infos)))
   227      (subsets 0 (length (#descr (hd infos)) - 1))
   228    |> curry (Library.foldr (make_casedists sorts)) infos);
   229 
   230 end;