src/HOL/Tools/datatype_realizer.ML
author berghofe
Mon Oct 21 16:57:39 2002 +0200 (2002-10-21)
changeset 13656 58bb243dbafb
parent 13641 63d1790a43ed
child 13708 a3a410782c95
permissions -rw-r--r--
Changed type of Logic.strip_horn.
     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 (((dt, s), T) :: ds) = 
    92                 let
    93                   val k = body_index dt;
    94                   val (Us, U) = strip_type T;
    95                   val i = length Us;
    96                   val rT = nth_elem (k, rec_result_Ts);
    97                   val r = Free ("r" ^ s, Us ---> rT);
    98                   val (p, f) = mk_prems (vs @ [r]) ds
    99                 in (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
   100                   (list_all (map (pair "x") Us, HOLogic.mk_Trueprop
   101                     (make_pred k rT U (app_bnds r i)
   102                       (app_bnds (Free (s, T)) i))), p)), f)
   103                 end
   104 
   105         in (j + 1,
   106           apfst (curry list_all_free frees) (mk_prems (map Free frees) recs))
   107         end) (j, constrs)) (1, descr ~~ recTs))));
   108  
   109     fun mk_proj j [] t = t
   110       | mk_proj j (i :: is) t = if null is then t else
   111           if j = i then HOLogic.mk_fst t
   112           else mk_proj j is (HOLogic.mk_snd t);
   113 
   114     val tnames = DatatypeProp.make_tnames recTs;
   115     val fTs = map fastype_of rec_fns;
   116     val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
   117       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
   118         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
   119     val r = if null is then Extraction.nullt else
   120       foldr1 HOLogic.mk_prod (mapfilter (fn (((((i, _), T), U), s), tname) =>
   121         if i mem is then Some
   122           (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   123         else None) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   124     val concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
   125       (map (fn ((((i, _), T), U), tname) =>
   126         make_pred i U T (mk_proj i is r) (Free (tname, T)))
   127           (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   128     val cert = cterm_of sg;
   129     val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
   130       (HOLogic.dest_Trueprop (concl_of induction))) ~~ ps);
   131 
   132     val thm = prove_goal' sg (Logic.list_implies (prems, concl))
   133       (fn prems =>
   134          [rewrite_goals_tac (map mk_meta_eq [fst_conv, snd_conv]),
   135           rtac (cterm_instantiate inst induction) 1,
   136           ALLGOALS ObjectLogic.atomize_tac,
   137           rewrite_goals_tac (o_def :: map mk_meta_eq rec_rewrites),
   138           REPEAT ((resolve_tac prems THEN_ALL_NEW (fn i =>
   139             REPEAT (etac allE i) THEN atac i)) 1)]);
   140 
   141     val {path, ...} = Sign.rep_sg sg;
   142     val ind_name = Thm.name_of_thm induction;
   143     val vs = map (fn i => nth_elem (i, pnames)) is;
   144     val (thy', thm') = thy
   145       |> Theory.absolute_path
   146       |> PureThy.store_thm
   147         ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
   148       |>> Theory.add_path (NameSpace.pack (if_none path []));
   149 
   150     val inst = map (fn ((((i, _), s), T), U) => ((s, 0), if i mem is then
   151         Abs ("r", U, Abs ("x", T, mk_realizes U $ Bound 1 $
   152           (Var ((s, 0), T --> HOLogic.boolT) $ Bound 0)))
   153       else Abs ("x", T, mk_realizes Extraction.nullT $ Extraction.nullt $
   154         (Var ((s, 0), T --> HOLogic.boolT) $
   155           Bound 0)))) (descr ~~ pnames ~~ map Type.varifyT recTs ~~
   156             map Type.varifyT rec_result_Ts);
   157 
   158     val ivs = map Var (Drule.vars_of_terms
   159       [Logic.varify (DatatypeProp.make_ind [descr] sorts)]);
   160 
   161     val prf = foldr forall_intr_prf (ivs,
   162       prf_subst_vars inst (foldr (fn ((f, p), prf) =>
   163         (case head_of (strip_abs_body f) of
   164            Free (s, T) =>
   165              let val T' = Type.varifyT T
   166              in Abst (s, Some T', Proofterm.prf_abstract_over
   167                (Var ((s, 0), T')) (AbsP ("H", Some p, prf)))
   168              end
   169          | _ => AbsP ("H", Some p, prf)))
   170            (rec_fns ~~ prems_of thm, Proofterm.proof_combP
   171              (prf_of thm', map PBound (length prems - 1 downto 0)))));
   172 
   173     val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
   174       (map Logic.unvarify ivs @ filter_out is_unit
   175         (map (head_of o strip_abs_body) rec_fns), r));
   176 
   177   in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   178 
   179 
   180 fun make_casedists sorts ({index, descr, case_name, case_rewrites, exhaustion, ...} : datatype_info, thy) =
   181   let
   182     val sg = sign_of thy;
   183     val sorts = map (rpair HOLogic.typeS) (distinct (flat (map
   184       (fn (_, (_, ds, _)) => mapfilter (try dest_DtTFree) ds) descr)));
   185     val cert = cterm_of sg;
   186     val rT = TFree ("'P", HOLogic.typeS);
   187     val rT' = TVar (("'P", 0), HOLogic.typeS);
   188 
   189     fun make_casedist_prem T (cname, cargs) =
   190       let
   191         val Ts = map (typ_of_dtyp descr sorts) cargs;
   192         val frees = variantlist
   193           (DatatypeProp.make_tnames Ts, ["P", "y"]) ~~ Ts;
   194         val free_ts = map Free frees;
   195         val r = Free ("r" ^ NameSpace.base cname, Ts ---> rT)
   196       in (r, list_all_free (frees, Logic.mk_implies (HOLogic.mk_Trueprop
   197         (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   198           HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   199             list_comb (r, free_ts)))))
   200       end;
   201 
   202     val Some (_, _, constrs) = assoc (descr, index);
   203     val T = nth_elem (index, get_rec_types descr sorts);
   204     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   205     val r = Const (case_name, map fastype_of rs ---> T --> rT);
   206 
   207     val y = Var (("y", 0), Type.varifyT T);
   208     val y' = Free ("y", T);
   209 
   210     val thm = prove_goalw_cterm [] (cert (Logic.list_implies (prems,
   211       HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   212         list_comb (r, rs @ [y'])))))
   213       (fn prems =>
   214          [rtac (cterm_instantiate [(cert y, cert y')] exhaustion) 1,
   215           ALLGOALS (EVERY'
   216             [asm_simp_tac (HOL_basic_ss addsimps case_rewrites),
   217              resolve_tac prems, asm_simp_tac HOL_basic_ss])]);
   218 
   219     val {path, ...} = Sign.rep_sg sg;
   220     val exh_name = Thm.name_of_thm exhaustion;
   221     val (thy', thm') = thy
   222       |> Theory.absolute_path
   223       |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
   224       |>> Theory.add_path (NameSpace.pack (if_none path []));
   225 
   226     val P = Var (("P", 0), HOLogic.boolT);
   227     val prf = forall_intr_prf (y, forall_intr_prf (P,
   228       prf_subst_vars [(("P", 0), Abs ("r", rT',
   229         mk_realizes rT' $ Bound 0 $ P))] (foldr (fn ((p, r), prf) =>
   230           forall_intr_prf (Logic.varify r, AbsP ("H", Some (Logic.varify p),
   231             prf))) (prems ~~ rs, Proofterm.proof_combP (prf_of thm',
   232               map PBound (length prems - 1 downto 0))))));
   233     val r' = Logic.varify (Abs ("y", Type.varifyT T,
   234       Abs ("P", HOLogic.boolT, list_abs (map dest_Free rs, list_comb (r,
   235         map Bound ((length rs - 1 downto 0) @ [length rs + 1]))))));
   236 
   237     val prf' = forall_intr_prf (y, forall_intr_prf (P, prf_subst_vars
   238       [(("P", 0), mk_realizes Extraction.nullT $ Extraction.nullt $ P)]
   239         (prf_of exhaustion)));
   240 
   241   in Extraction.add_realizers_i
   242     [(exh_name, (["P"], r', prf)),
   243      (exh_name, ([], Extraction.nullt, prf'))] thy'
   244   end;
   245 
   246 
   247 fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
   248   (message "Adding realizers for induction and case analysis ..."; thy
   249    |> curry (foldr (make_ind sorts (hd infos)))
   250      (subsets 0 (length (#descr (hd infos)) - 1))
   251    |> curry (foldr (make_casedists sorts)) infos);
   252 
   253 end;