src/HOL/Tools/datatype_realizer.ML
author wenzelm
Sat Jul 25 23:41:53 2015 +0200 (2015-07-25)
changeset 60781 2da59cdf531c
parent 60752 b48830b670a1
child 60826 695cf1fab6cc
permissions -rw-r--r--
updated to infer_instantiate;
tuned;
     1 (*  Title:      HOL/Tools/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 DATATYPE_REALIZER =
     9 sig
    10   val add_dt_realizers: Old_Datatype_Aux.config -> string list -> theory -> theory
    11 end;
    12 
    13 structure Datatype_Realizer : 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 
    31     val recTs = Old_Datatype_Aux.get_rec_types descr;
    32     val pnames =
    33       if length descr = 1 then ["P"]
    34       else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
    35 
    36     val rec_result_Ts = map (fn ((i, _), P) =>
    37         if member (op =) is i then TFree ("'" ^ P, @{sort type}) else HOLogic.unitT)
    38       (descr ~~ pnames);
    39 
    40     fun make_pred i T U r x =
    41       if member (op =) is i then
    42         Free (nth pnames i, T --> U --> HOLogic.boolT) $ r $ x
    43       else Free (nth pnames i, U --> HOLogic.boolT) $ x;
    44 
    45     fun mk_all i s T t =
    46       if member (op =) is i then Logic.all (Free (s, T)) t else t;
    47 
    48     val (prems, rec_fns) = split_list (flat (fst (fold_map
    49       (fn ((i, (_, _, constrs)), T) => fold_map (fn (cname, cargs) => fn j =>
    50         let
    51           val Ts = map (Old_Datatype_Aux.typ_of_dtyp descr) cargs;
    52           val tnames = Name.variant_list pnames (Old_Datatype_Prop.make_tnames Ts);
    53           val recs = filter (Old_Datatype_Aux.is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
    54           val frees = tnames ~~ Ts;
    55 
    56           fun mk_prems vs [] =
    57                 let
    58                   val rT = nth (rec_result_Ts) i;
    59                   val vs' = filter_out is_unit vs;
    60                   val f = Old_Datatype_Aux.mk_Free "f" (map fastype_of vs' ---> rT) j;
    61                   val f' =
    62                     Envir.eta_contract (fold_rev (absfree o dest_Free) vs
    63                       (if member (op =) is i then list_comb (f, vs') else HOLogic.unit));
    64                 in
    65                   (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
    66                     (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
    67                 end
    68             | mk_prems vs (((dt, s), T) :: ds) =
    69                 let
    70                   val k = Old_Datatype_Aux.body_index dt;
    71                   val (Us, U) = strip_type T;
    72                   val i = length Us;
    73                   val rT = nth (rec_result_Ts) k;
    74                   val r = Free ("r" ^ s, Us ---> rT);
    75                   val (p, f) = mk_prems (vs @ [r]) ds;
    76                 in
    77                   (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
    78                     (Logic.list_all (map (pair "x") Us, HOLogic.mk_Trueprop
    79                       (make_pred k rT U (Old_Datatype_Aux.app_bnds r i)
    80                         (Old_Datatype_Aux.app_bnds (Free (s, T)) i))), p)), f)
    81                 end;
    82         in (apfst (fold_rev (Logic.all o Free) frees) (mk_prems (map Free frees) recs), j + 1) end)
    83           constrs) (descr ~~ recTs) 1)));
    84 
    85     fun mk_proj _ [] t = t
    86       | mk_proj j (i :: is) t =
    87           if null is then t
    88           else if (j: int) = i then HOLogic.mk_fst t
    89           else mk_proj j is (HOLogic.mk_snd t);
    90 
    91     val tnames = Old_Datatype_Prop.make_tnames recTs;
    92     val fTs = map fastype_of rec_fns;
    93     val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
    94       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
    95         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
    96     val r =
    97       if null is then Extraction.nullt
    98       else
    99         foldr1 HOLogic.mk_prod (map_filter (fn (((((i, _), T), U), s), tname) =>
   100           if member (op =) is i then SOME
   101             (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   102           else NONE) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   103     val concl =
   104       HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop @{const_name HOL.conj})
   105         (map (fn ((((i, _), T), U), tname) =>
   106           make_pred i U T (mk_proj i is r) (Free (tname, T)))
   107             (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   108     val inst =
   109       map (#1 o dest_Var o head_of)
   110         (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induct))) ~~
   111       map (Thm.cterm_of ctxt) ps;
   112 
   113     val thm =
   114       Goal.prove_internal ctxt (map (Thm.cterm_of ctxt) prems) (Thm.cterm_of ctxt concl)
   115         (fn prems =>
   116            EVERY [
   117             rewrite_goals_tac ctxt (map mk_meta_eq [@{thm fst_conv}, @{thm snd_conv}]),
   118             resolve_tac ctxt [infer_instantiate ctxt inst induct] 1,
   119             ALLGOALS (Object_Logic.atomize_prems_tac ctxt),
   120             rewrite_goals_tac ctxt (@{thm o_def} :: map mk_meta_eq rec_rewrites),
   121             REPEAT ((resolve_tac ctxt prems THEN_ALL_NEW (fn i =>
   122               REPEAT (eresolve_tac ctxt [allE] i) THEN assume_tac ctxt i)) 1)])
   123       |> Drule.export_without_context;
   124 
   125     val ind_name = Thm.derivation_name induct;
   126     val vs = map (nth pnames) is;
   127     val (thm', thy') = thy
   128       |> Sign.root_path
   129       |> Global_Theory.store_thm
   130         (Binding.qualified_name (space_implode "_" (ind_name :: vs @ ["correctness"])), thm)
   131       ||> Sign.restore_naming thy;
   132 
   133     val ivs = rev (Term.add_vars (Logic.varify_global (Old_Datatype_Prop.make_ind [descr])) []);
   134     val rvs = rev (Thm.fold_terms Term.add_vars thm' []);
   135     val ivs1 = map Var (filter_out (fn (_, T) => @{type_name bool} = tname_of (body_type T)) ivs);
   136     val ivs2 = map (fn (ixn, _) => Var (ixn, the (AList.lookup (op =) rvs ixn))) ivs;
   137 
   138     val prf =
   139       Extraction.abs_corr_shyps thy' induct vs ivs2
   140         (fold_rev (fn (f, p) => fn prf =>
   141             (case head_of (strip_abs_body f) of
   142               Free (s, T) =>
   143                 let val T' = Logic.varifyT_global T in
   144                   Abst (s, SOME T', Proofterm.prf_abstract_over
   145                     (Var ((s, 0), T')) (AbsP ("H", SOME p, prf)))
   146                 end
   147             | _ => AbsP ("H", SOME p, prf)))
   148           (rec_fns ~~ Thm.prems_of thm)
   149           (Proofterm.proof_combP
   150             (Reconstruct.proof_of thm', map PBound (length prems - 1 downto 0))));
   151 
   152     val r' =
   153       if null is then r
   154       else
   155         Logic.varify_global (fold_rev lambda
   156           (map Logic.unvarify_global ivs1 @ filter_out is_unit
   157               (map (head_of o strip_abs_body) rec_fns)) r);
   158 
   159   in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
   160 
   161 fun make_casedists ({index, descr, case_name, case_rewrites, exhaust, ...} : Old_Datatype_Aux.info) thy =
   162   let
   163     val ctxt = Proof_Context.init_global 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 (Thm.cterm_of ctxt) prems)
   191         (Thm.cterm_of ctxt
   192           (HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $ list_comb (r, rs @ [y']))))
   193         (fn prems =>
   194            EVERY [
   195             resolve_tac ctxt [infer_instantiate ctxt [(#1 (dest_Var y), Thm.cterm_of ctxt y')] exhaust] 1,
   196             ALLGOALS (EVERY'
   197               [asm_simp_tac (put_simpset HOL_basic_ss ctxt addsimps case_rewrites),
   198                resolve_tac ctxt prems, asm_simp_tac (put_simpset HOL_basic_ss ctxt)])])
   199       |> Drule.export_without_context;
   200 
   201     val exh_name = Thm.derivation_name exhaust;
   202     val (thm', thy') = thy
   203       |> Sign.root_path
   204       |> Global_Theory.store_thm (Binding.qualified_name (exh_name ^ "_P_correctness"), thm)
   205       ||> Sign.restore_naming thy;
   206 
   207     val P = Var (("P", 0), rT' --> HOLogic.boolT);
   208     val prf =
   209       Extraction.abs_corr_shyps thy' exhaust ["P"] [y, P]
   210         (fold_rev (fn (p, r) => fn prf =>
   211             Proofterm.forall_intr_proof' (Logic.varify_global r)
   212               (AbsP ("H", SOME (Logic.varify_global p), prf)))
   213           (prems ~~ rs)
   214           (Proofterm.proof_combP
   215             (Reconstruct.proof_of thm', map PBound (length prems - 1 downto 0))));
   216     val prf' =
   217       Extraction.abs_corr_shyps thy' exhaust []
   218         (map Var (Term.add_vars (Thm.prop_of exhaust) [])) (Reconstruct.proof_of exhaust);
   219     val r' =
   220       Logic.varify_global (Abs ("y", T,
   221         (fold_rev (Term.abs o dest_Free) rs
   222           (list_comb (r, map Bound ((length rs - 1 downto 0) @ [length rs]))))));
   223   in
   224     Extraction.add_realizers_i
   225       [(exh_name, (["P"], r', prf)),
   226        (exh_name, ([], Extraction.nullt, prf'))] thy'
   227   end;
   228 
   229 fun add_dt_realizers config names thy =
   230   if not (Proofterm.proofs_enabled ()) then thy
   231   else
   232     let
   233       val _ = Old_Datatype_Aux.message config "Adding realizers for induction and case analysis ...";
   234       val infos = map (BNF_LFP_Compat.the_info thy []) names;
   235       val info :: _ = infos;
   236     in
   237       thy
   238       |> fold_rev (perhaps o try o make_ind info) (subsets 0 (length (#descr info) - 1))
   239       |> fold_rev (perhaps o try o make_casedists) infos
   240     end;
   241 
   242 val _ = Theory.setup (BNF_LFP_Compat.interpretation @{plugin extraction} [] add_dt_realizers);
   243 
   244 end;