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