src/HOL/Tools/Datatype/datatype_realizer.ML
author wenzelm
Sat Mar 22 18:19:57 2014 +0100 (2014-03-22)
changeset 56254 a2dd9200854d
parent 54895 515630483010
child 58111 82db9ad610b9
permissions -rw-r--r--
more antiquotations;
     1 (*  Title:      HOL/Tools/Datatype/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: Datatype.config -> string list -> theory -> theory
    11   val setup: theory -> theory
    12 end;
    13 
    14 structure Datatype_Realizer : DATATYPE_REALIZER =
    15 struct
    16 
    17 fun subsets i j =
    18   if i <= j then
    19     let val is = subsets (i+1) j
    20     in map (fn ks => i::ks) is @ is end
    21   else [[]];
    22 
    23 fun is_unit t = body_type (fastype_of t) = HOLogic.unitT;
    24 
    25 fun tname_of (Type (s, _)) = s
    26   | tname_of _ = "";
    27 
    28 fun make_ind ({descr, rec_names, rec_rewrites, induct, ...} : Datatype.info) is thy =
    29   let
    30     val ctxt = Proof_Context.init_global thy;
    31     val cert = cterm_of thy;
    32 
    33     val recTs = Datatype_Aux.get_rec_types descr;
    34     val pnames =
    35       if length descr = 1 then ["P"]
    36       else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
    37 
    38     val rec_result_Ts = map (fn ((i, _), P) =>
    39         if member (op =) is i then TFree ("'" ^ P, @{sort type}) else HOLogic.unitT)
    40       (descr ~~ pnames);
    41 
    42     fun make_pred i T U r x =
    43       if member (op =) is i then
    44         Free (nth pnames i, T --> U --> HOLogic.boolT) $ r $ x
    45       else Free (nth pnames i, U --> HOLogic.boolT) $ x;
    46 
    47     fun mk_all i s T t =
    48       if member (op =) is i then Logic.all (Free (s, T)) t else t;
    49 
    50     val (prems, rec_fns) = split_list (flat (fst (fold_map
    51       (fn ((i, (_, _, constrs)), T) => fold_map (fn (cname, cargs) => fn j =>
    52         let
    53           val Ts = map (Datatype_Aux.typ_of_dtyp descr) cargs;
    54           val tnames = Name.variant_list pnames (Datatype_Prop.make_tnames Ts);
    55           val recs = filter (Datatype_Aux.is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
    56           val frees = tnames ~~ Ts;
    57 
    58           fun mk_prems vs [] =
    59                 let
    60                   val rT = nth (rec_result_Ts) i;
    61                   val vs' = filter_out is_unit vs;
    62                   val f = Datatype_Aux.mk_Free "f" (map fastype_of vs' ---> rT) j;
    63                   val f' =
    64                     Envir.eta_contract (fold_rev (absfree o dest_Free) vs
    65                       (if member (op =) is i then list_comb (f, vs') else HOLogic.unit));
    66                 in
    67                   (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
    68                     (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
    69                 end
    70             | mk_prems vs (((dt, s), T) :: ds) =
    71                 let
    72                   val k = Datatype_Aux.body_index dt;
    73                   val (Us, U) = strip_type T;
    74                   val i = length Us;
    75                   val rT = nth (rec_result_Ts) k;
    76                   val r = Free ("r" ^ s, Us ---> rT);
    77                   val (p, f) = mk_prems (vs @ [r]) ds;
    78                 in
    79                   (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
    80                     (Logic.list_all (map (pair "x") Us, HOLogic.mk_Trueprop
    81                       (make_pred k rT U (Datatype_Aux.app_bnds r i)
    82                         (Datatype_Aux.app_bnds (Free (s, T)) i))), p)), f)
    83                 end;
    84         in (apfst (fold_rev (Logic.all o Free) frees) (mk_prems (map Free frees) recs), j + 1) end)
    85           constrs) (descr ~~ recTs) 1)));
    86 
    87     fun mk_proj j [] t = t
    88       | mk_proj j (i :: is) t =
    89           if null is then t
    90           else if (j: int) = i then HOLogic.mk_fst t
    91           else mk_proj j is (HOLogic.mk_snd t);
    92 
    93     val tnames = Datatype_Prop.make_tnames recTs;
    94     val fTs = map fastype_of rec_fns;
    95     val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
    96       (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
    97         (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
    98     val r =
    99       if null is then Extraction.nullt
   100       else
   101         foldr1 HOLogic.mk_prod (map_filter (fn (((((i, _), T), U), s), tname) =>
   102           if member (op =) is i then SOME
   103             (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
   104           else NONE) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
   105     val concl =
   106       HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop @{const_name HOL.conj})
   107         (map (fn ((((i, _), T), U), tname) =>
   108           make_pred i U T (mk_proj i is r) (Free (tname, T)))
   109             (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
   110     val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
   111       (HOLogic.dest_Trueprop (concl_of induct))) ~~ ps);
   112 
   113     val thm =
   114       Goal.prove_internal ctxt (map cert prems) (cert concl)
   115         (fn prems =>
   116            EVERY [
   117             rewrite_goals_tac ctxt (map mk_meta_eq [@{thm fst_conv}, @{thm snd_conv}]),
   118             rtac (cterm_instantiate 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 prems THEN_ALL_NEW (fn i =>
   122               REPEAT (etac allE i) THEN atac 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 (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 ~~ 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 
   162 fun make_casedists ({index, descr, case_name, case_rewrites, exhaust, ...} : Datatype.info) thy =
   163   let
   164     val ctxt = Proof_Context.init_global thy;
   165     val cert = cterm_of thy;
   166     val rT = TFree ("'P", @{sort type});
   167     val rT' = TVar (("'P", 0), @{sort type});
   168 
   169     fun make_casedist_prem T (cname, cargs) =
   170       let
   171         val Ts = map (Datatype_Aux.typ_of_dtyp descr) cargs;
   172         val frees = Name.variant_list ["P", "y"] (Datatype_Prop.make_tnames Ts) ~~ Ts;
   173         val free_ts = map Free frees;
   174         val r = Free ("r" ^ Long_Name.base_name cname, Ts ---> rT)
   175       in
   176         (r, fold_rev Logic.all free_ts
   177           (Logic.mk_implies (HOLogic.mk_Trueprop
   178             (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
   179               HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
   180                 list_comb (r, free_ts)))))
   181       end;
   182 
   183     val SOME (_, _, constrs) = AList.lookup (op =) descr index;
   184     val T = nth (Datatype_Aux.get_rec_types descr) index;
   185     val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
   186     val r = Const (case_name, map fastype_of rs ---> T --> rT);
   187 
   188     val y = Var (("y", 0), Logic.varifyT_global T);
   189     val y' = Free ("y", T);
   190 
   191     val thm =
   192       Goal.prove_internal ctxt (map cert prems)
   193         (cert (HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $ list_comb (r, rs @ [y']))))
   194         (fn prems =>
   195            EVERY [
   196             rtac (cterm_instantiate [(cert y, cert y')] exhaust) 1,
   197             ALLGOALS (EVERY'
   198               [asm_simp_tac (put_simpset HOL_basic_ss ctxt addsimps case_rewrites),
   199                resolve_tac prems, asm_simp_tac (put_simpset HOL_basic_ss ctxt)])])
   200       |> Drule.export_without_context;
   201 
   202     val exh_name = Thm.derivation_name exhaust;
   203     val (thm', thy') = thy
   204       |> Sign.root_path
   205       |> Global_Theory.store_thm (Binding.qualified_name (exh_name ^ "_P_correctness"), thm)
   206       ||> Sign.restore_naming thy;
   207 
   208     val P = Var (("P", 0), rT' --> HOLogic.boolT);
   209     val prf =
   210       Extraction.abs_corr_shyps thy' exhaust ["P"] [y, P]
   211         (fold_rev (fn (p, r) => fn prf =>
   212             Proofterm.forall_intr_proof' (Logic.varify_global r)
   213               (AbsP ("H", SOME (Logic.varify_global p), prf)))
   214           (prems ~~ rs)
   215           (Proofterm.proof_combP
   216             (Reconstruct.proof_of thm', map PBound (length prems - 1 downto 0))));
   217     val prf' =
   218       Extraction.abs_corr_shyps thy' exhaust []
   219         (map Var (Term.add_vars (prop_of exhaust) [])) (Reconstruct.proof_of exhaust);
   220     val r' =
   221       Logic.varify_global (Abs ("y", T,
   222         (fold_rev (Term.abs o dest_Free) rs
   223           (list_comb (r, map Bound ((length rs - 1 downto 0) @ [length rs]))))));
   224   in
   225     Extraction.add_realizers_i
   226       [(exh_name, (["P"], r', prf)),
   227        (exh_name, ([], Extraction.nullt, prf'))] thy'
   228   end;
   229 
   230 fun add_dt_realizers config names thy =
   231   if not (Proofterm.proofs_enabled ()) then thy
   232   else
   233     let
   234       val _ = Datatype_Aux.message config "Adding realizers for induction and case analysis ...";
   235       val infos = map (Datatype.the_info thy) names;
   236       val info :: _ = infos;
   237     in
   238       thy
   239       |> fold_rev (make_ind info) (subsets 0 (length (#descr info) - 1))
   240       |> fold_rev make_casedists infos
   241     end;
   242 
   243 val setup = Datatype.interpretation add_dt_realizers;
   244 
   245 end;