src/HOL/Tools/Old_Datatype/old_datatype_realizer.ML
author blanchet
Thu Sep 04 11:20:59 2014 +0200 (2014-09-04)
changeset 58182 82478e6c60cb
parent 58112 8081087096ad
child 58274 4a84e94e58a2
permissions -rw-r--r--
tweaked setup for datatype realizer
     1 (*  Title:      HOL/Tools/Old_Datatype/old_datatype_realizer.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Program extraction from proofs involving datatypes:
     5 realizers for induction and case analysis.
     6 *)
     7 
     8 signature OLD_DATATYPE_REALIZER =
     9 sig
    10   val add_dt_realizers: Old_Datatype_Aux.config -> string list -> theory -> theory
    11 end;
    12 
    13 structure Old_Datatype_Realizer : OLD_DATATYPE_REALIZER =
    14 struct
    15 
    16 fun subsets i j =
    17   if i <= j then
    18     let val is = subsets (i+1) j
    19     in map (fn ks => i::ks) is @ is end
    20   else [[]];
    21 
    22 fun is_unit t = body_type (fastype_of t) = HOLogic.unitT;
    23 
    24 fun tname_of (Type (s, _)) = s
    25   | tname_of _ = "";
    26 
    27 fun make_ind ({descr, rec_names, rec_rewrites, induct, ...} : Old_Datatype_Aux.info) is thy =
    28   let
    29     val ctxt = Proof_Context.init_global thy;
    30     val cert = cterm_of thy;
    31 
    32     val recTs = Old_Datatype_Aux.get_rec_types descr;
    33     val pnames =
    34       if length descr = 1 then ["P"]
    35       else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
    36 
    37     val rec_result_Ts = map (fn ((i, _), P) =>
    38         if member (op =) is i then TFree ("'" ^ P, @{sort type}) else HOLogic.unitT)
    39       (descr ~~ pnames);
    40 
    41     fun make_pred i T U r x =
    42       if member (op =) is i then
    43         Free (nth pnames i, T --> U --> HOLogic.boolT) $ r $ x
    44       else Free (nth pnames i, U --> HOLogic.boolT) $ x;
    45 
    46     fun mk_all i s T t =
    47       if member (op =) is i then Logic.all (Free (s, T)) t else t;
    48 
    49     val (prems, rec_fns) = split_list (flat (fst (fold_map
    50       (fn ((i, (_, _, constrs)), T) => fold_map (fn (cname, cargs) => fn j =>
    51         let
    52           val Ts = map (Old_Datatype_Aux.typ_of_dtyp descr) cargs;
    53           val tnames = Name.variant_list pnames (Old_Datatype_Prop.make_tnames Ts);
    54           val recs = filter (Old_Datatype_Aux.is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
    55           val frees = tnames ~~ Ts;
    56 
    57           fun mk_prems vs [] =
    58                 let
    59                   val rT = nth (rec_result_Ts) i;
    60                   val vs' = filter_out is_unit vs;
    61                   val f = Old_Datatype_Aux.mk_Free "f" (map fastype_of vs' ---> rT) j;
    62                   val f' =
    63                     Envir.eta_contract (fold_rev (absfree o dest_Free) vs
    64                       (if member (op =) is i then list_comb (f, vs') else HOLogic.unit));
    65                 in
    66                   (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
    67                     (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
    68                 end
    69             | mk_prems vs (((dt, s), T) :: ds) =
    70                 let
    71                   val k = Old_Datatype_Aux.body_index dt;
    72                   val (Us, U) = strip_type T;
    73                   val i = length Us;
    74                   val rT = nth (rec_result_Ts) k;
    75                   val r = Free ("r" ^ s, Us ---> rT);
    76                   val (p, f) = mk_prems (vs @ [r]) ds;
    77                 in
    78                   (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
    79                     (Logic.list_all (map (pair "x") Us, HOLogic.mk_Trueprop
    80                       (make_pred k rT U (Old_Datatype_Aux.app_bnds r i)
    81                         (Old_Datatype_Aux.app_bnds (Free (s, T)) i))), p)), f)
    82                 end;
    83         in (apfst (fold_rev (Logic.all o Free) frees) (mk_prems (map Free frees) recs), j + 1) end)
    84           constrs) (descr ~~ recTs) 1)));
    85 
    86     fun mk_proj _ [] t = t
    87       | mk_proj j (i :: is) t =
    88           if null is then t
    89           else if (j: int) = i then HOLogic.mk_fst t
    90           else mk_proj j is (HOLogic.mk_snd t);
    91 
    92     val tnames = Old_Datatype_Prop.make_tnames recTs;
    93     val fTs = map fastype_of rec_fns;
    94     val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
    95       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
    96         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
    97     val r =
    98       if null is then Extraction.nullt
    99       else
   100         foldr1 HOLogic.mk_prod (map_filter (fn (((((i, _), T), U), s), tname) =>
   101           if member (op =) is i then SOME
   102             (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   103           else NONE) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   104     val concl =
   105       HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop @{const_name HOL.conj})
   106         (map (fn ((((i, _), T), U), tname) =>
   107           make_pred i U T (mk_proj i is r) (Free (tname, T)))
   108             (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   109     val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
   110       (HOLogic.dest_Trueprop (concl_of induct))) ~~ ps);
   111 
   112     val thm =
   113       Goal.prove_internal ctxt (map cert prems) (cert concl)
   114         (fn prems =>
   115            EVERY [
   116             rewrite_goals_tac ctxt (map mk_meta_eq [@{thm fst_conv}, @{thm snd_conv}]),
   117             rtac (cterm_instantiate inst induct) 1,
   118             ALLGOALS (Object_Logic.atomize_prems_tac ctxt),
   119             rewrite_goals_tac ctxt (@{thm o_def} :: map mk_meta_eq rec_rewrites),
   120             REPEAT ((resolve_tac prems THEN_ALL_NEW (fn i =>
   121               REPEAT (etac allE i) THEN atac i)) 1)])
   122       |> Drule.export_without_context;
   123 
   124     val ind_name = Thm.derivation_name induct;
   125     val vs = map (nth pnames) is;
   126     val (thm', thy') = thy
   127       |> Sign.root_path
   128       |> Global_Theory.store_thm
   129         (Binding.qualified_name (space_implode "_" (ind_name :: vs @ ["correctness"])), thm)
   130       ||> Sign.restore_naming thy;
   131 
   132     val ivs = rev (Term.add_vars (Logic.varify_global (Old_Datatype_Prop.make_ind [descr])) []);
   133     val rvs = rev (Thm.fold_terms Term.add_vars thm' []);
   134     val ivs1 = map Var (filter_out (fn (_, T) => @{type_name bool} = tname_of (body_type T)) ivs);
   135     val ivs2 = map (fn (ixn, _) => Var (ixn, the (AList.lookup (op =) rvs ixn))) ivs;
   136 
   137     val prf =
   138       Extraction.abs_corr_shyps thy' induct vs ivs2
   139         (fold_rev (fn (f, p) => fn prf =>
   140             (case head_of (strip_abs_body f) of
   141               Free (s, T) =>
   142                 let val T' = Logic.varifyT_global T in
   143                   Abst (s, SOME T', Proofterm.prf_abstract_over
   144                     (Var ((s, 0), T')) (AbsP ("H", SOME p, prf)))
   145                 end
   146             | _ => AbsP ("H", SOME p, prf)))
   147           (rec_fns ~~ prems_of thm)
   148           (Proofterm.proof_combP
   149             (Reconstruct.proof_of thm', map PBound (length prems - 1 downto 0))));
   150 
   151     val r' =
   152       if null is then r
   153       else
   154         Logic.varify_global (fold_rev lambda
   155           (map Logic.unvarify_global ivs1 @ filter_out is_unit
   156               (map (head_of o strip_abs_body) rec_fns)) r);
   157 
   158   in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   159 
   160 fun make_casedists ({index, descr, case_name, case_rewrites, exhaust, ...} : Old_Datatype_Aux.info) thy =
   161   let
   162     val ctxt = Proof_Context.init_global thy;
   163     val cert = cterm_of thy;
   164     val rT = TFree ("'P", @{sort type});
   165     val rT' = TVar (("'P", 0), @{sort type});
   166 
   167     fun make_casedist_prem T (cname, cargs) =
   168       let
   169         val Ts = map (Old_Datatype_Aux.typ_of_dtyp descr) cargs;
   170         val frees = Name.variant_list ["P", "y"] (Old_Datatype_Prop.make_tnames Ts) ~~ Ts;
   171         val free_ts = map Free frees;
   172         val r = Free ("r" ^ Long_Name.base_name cname, Ts ---> rT)
   173       in
   174         (r, fold_rev Logic.all free_ts
   175           (Logic.mk_implies (HOLogic.mk_Trueprop
   176             (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   177               HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   178                 list_comb (r, free_ts)))))
   179       end;
   180 
   181     val SOME (_, _, constrs) = AList.lookup (op =) descr index;
   182     val T = nth (Old_Datatype_Aux.get_rec_types descr) index;
   183     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   184     val r = Const (case_name, map fastype_of rs ---> T --> rT);
   185 
   186     val y = Var (("y", 0), Logic.varifyT_global T);
   187     val y' = Free ("y", T);
   188 
   189     val thm =
   190       Goal.prove_internal ctxt (map cert prems)
   191         (cert (HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $ list_comb (r, rs @ [y']))))
   192         (fn prems =>
   193            EVERY [
   194             rtac (cterm_instantiate [(cert y, cert y')] exhaust) 1,
   195             ALLGOALS (EVERY'
   196               [asm_simp_tac (put_simpset HOL_basic_ss ctxt addsimps case_rewrites),
   197                resolve_tac prems, asm_simp_tac (put_simpset HOL_basic_ss ctxt)])])
   198       |> Drule.export_without_context;
   199 
   200     val exh_name = Thm.derivation_name exhaust;
   201     val (thm', thy') = thy
   202       |> Sign.root_path
   203       |> Global_Theory.store_thm (Binding.qualified_name (exh_name ^ "_P_correctness"), thm)
   204       ||> Sign.restore_naming thy;
   205 
   206     val P = Var (("P", 0), rT' --> HOLogic.boolT);
   207     val prf =
   208       Extraction.abs_corr_shyps thy' exhaust ["P"] [y, P]
   209         (fold_rev (fn (p, r) => fn prf =>
   210             Proofterm.forall_intr_proof' (Logic.varify_global r)
   211               (AbsP ("H", SOME (Logic.varify_global p), prf)))
   212           (prems ~~ rs)
   213           (Proofterm.proof_combP
   214             (Reconstruct.proof_of thm', map PBound (length prems - 1 downto 0))));
   215     val prf' =
   216       Extraction.abs_corr_shyps thy' exhaust []
   217         (map Var (Term.add_vars (prop_of exhaust) [])) (Reconstruct.proof_of exhaust);
   218     val r' =
   219       Logic.varify_global (Abs ("y", T,
   220         (fold_rev (Term.abs o dest_Free) rs
   221           (list_comb (r, map Bound ((length rs - 1 downto 0) @ [length rs]))))));
   222   in
   223     Extraction.add_realizers_i
   224       [(exh_name, (["P"], r', prf)),
   225        (exh_name, ([], Extraction.nullt, prf'))] thy'
   226   end;
   227 
   228 fun add_dt_realizers config names thy =
   229   if not (Proofterm.proofs_enabled ()) then thy
   230   else
   231     let
   232       val _ = Old_Datatype_Aux.message config "Adding realizers for induction and case analysis ...";
   233       val infos = map (Old_Datatype_Data.the_info thy) names;
   234       val info :: _ = infos;
   235     in
   236       thy
   237       |> fold_rev (make_ind info) (subsets 0 (length (#descr info) - 1))
   238       |> fold_rev make_casedists infos
   239     end;
   240 
   241 val _ = Theory.setup (Old_Datatype_Data.interpretation add_dt_realizers);
   242 
   243 end;