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.
berghofe@13467
     1
(*  Title:      HOL/Tools/datatype_realizer.ML
berghofe@13467
     2
    ID:         $Id$
berghofe@13467
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@13467
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
berghofe@13467
     5
berghofe@13467
     6
Porgram extraction from proofs involving datatypes:
berghofe@13467
     7
Realizers for induction and case analysis
berghofe@13467
     8
*)
berghofe@13467
     9
berghofe@13467
    10
signature DATATYPE_REALIZER =
berghofe@13467
    11
sig
berghofe@13467
    12
  val add_dt_realizers: (string * sort) list ->
berghofe@13467
    13
    DatatypeAux.datatype_info list -> theory -> theory
berghofe@13467
    14
end;
berghofe@13467
    15
berghofe@13467
    16
structure DatatypeRealizer : DATATYPE_REALIZER =
berghofe@13467
    17
struct
berghofe@13467
    18
berghofe@13467
    19
open DatatypeAux;
berghofe@13467
    20
berghofe@13467
    21
fun subsets i j = if i <= j then
berghofe@13467
    22
       let val is = subsets (i+1) j
berghofe@13467
    23
       in map (fn ks => i::ks) is @ is end
berghofe@13467
    24
     else [[]];
berghofe@13467
    25
berghofe@13467
    26
fun forall_intr_prf (t, prf) =
berghofe@13467
    27
  let val (a, T) = (case t of Var ((a, _), T) => (a, T) | Free p => p)
berghofe@13467
    28
  in Abst (a, Some T, Proofterm.prf_abstract_over t prf) end;
berghofe@13467
    29
berghofe@13467
    30
fun prove_goal' sg p f =
berghofe@13467
    31
  let
berghofe@13656
    32
    val (As, B) = Logic.strip_horn p;
berghofe@13467
    33
    val cAs = map (cterm_of sg) As;
berghofe@13467
    34
    val asms = map (norm_hhf_rule o assume) cAs;
berghofe@13467
    35
    fun check thm = if nprems_of thm > 0 then
berghofe@13467
    36
      error "prove_goal': unsolved goals" else thm
berghofe@13467
    37
  in
berghofe@13467
    38
    standard (implies_intr_list cAs
berghofe@13467
    39
      (check (Seq.hd (EVERY (f asms) (trivial (cterm_of sg B))))))
berghofe@13467
    40
  end;
berghofe@13467
    41
berghofe@13467
    42
fun prf_of thm =
berghofe@13467
    43
  let val {sign, prop, der = (_, prf), ...} = rep_thm thm
berghofe@13467
    44
  in Reconstruct.reconstruct_proof sign prop prf end;
berghofe@13467
    45
berghofe@13467
    46
fun prf_subst_vars inst =
berghofe@13467
    47
  Proofterm.map_proof_terms (subst_vars ([], inst)) I;
berghofe@13467
    48
berghofe@13467
    49
fun is_unit t = snd (strip_type (fastype_of t)) = HOLogic.unitT;
berghofe@13467
    50
berghofe@13467
    51
fun mk_realizes T = Const ("realizes", T --> HOLogic.boolT --> HOLogic.boolT);
berghofe@13467
    52
berghofe@13467
    53
fun make_ind sorts ({descr, rec_names, rec_rewrites, induction, ...} : datatype_info) (is, thy) =
berghofe@13467
    54
  let
berghofe@13467
    55
    val sg = sign_of thy;
berghofe@13467
    56
    val recTs = get_rec_types descr sorts;
berghofe@13467
    57
    val pnames = if length descr = 1 then ["P"]
berghofe@13467
    58
      else map (fn i => "P" ^ string_of_int i) (1 upto length descr);
berghofe@13467
    59
berghofe@13467
    60
    val rec_result_Ts = map (fn ((i, _), P) =>
berghofe@13467
    61
      if i mem is then TFree ("'" ^ P, HOLogic.typeS) else HOLogic.unitT)
berghofe@13467
    62
        (descr ~~ pnames);
berghofe@13467
    63
berghofe@13467
    64
    fun make_pred i T U r x =
berghofe@13467
    65
      if i mem is then
berghofe@13467
    66
        Free (nth_elem (i, pnames), T --> U --> HOLogic.boolT) $ r $ x
berghofe@13467
    67
      else Free (nth_elem (i, pnames), U --> HOLogic.boolT) $ x;
berghofe@13467
    68
berghofe@13467
    69
    fun mk_all i s T t =
berghofe@13467
    70
      if i mem is then list_all_free ([(s, T)], t) else t;
berghofe@13467
    71
berghofe@13467
    72
    val (prems, rec_fns) = split_list (flat (snd (foldl_map
berghofe@13467
    73
      (fn (j, ((i, (_, _, constrs)), T)) => foldl_map (fn (j, (cname, cargs)) =>
berghofe@13467
    74
        let
berghofe@13467
    75
          val Ts = map (typ_of_dtyp descr sorts) cargs;
berghofe@13467
    76
          val tnames = variantlist (DatatypeProp.make_tnames Ts, pnames);
berghofe@13467
    77
          val recs = filter (is_rec_type o fst o fst) (cargs ~~ tnames ~~ Ts);
berghofe@13467
    78
          val frees = tnames ~~ Ts;
berghofe@13467
    79
berghofe@13467
    80
          fun mk_prems vs [] = 
berghofe@13467
    81
                let
berghofe@13467
    82
                  val rT = nth_elem (i, rec_result_Ts);
berghofe@13467
    83
                  val vs' = filter_out is_unit vs;
berghofe@13467
    84
                  val f = mk_Free "f" (map fastype_of vs' ---> rT) j;
berghofe@13467
    85
                  val f' = Pattern.eta_contract (list_abs_free
berghofe@13467
    86
                    (map dest_Free vs, if i mem is then list_comb (f, vs')
berghofe@13467
    87
                      else HOLogic.unit));
berghofe@13467
    88
                in (HOLogic.mk_Trueprop (make_pred i rT T (list_comb (f, vs'))
berghofe@13467
    89
                  (list_comb (Const (cname, Ts ---> T), map Free frees))), f')
berghofe@13467
    90
                end
berghofe@13641
    91
            | mk_prems vs (((dt, s), T) :: ds) = 
berghofe@13467
    92
                let
berghofe@13641
    93
                  val k = body_index dt;
berghofe@13641
    94
                  val (Us, U) = strip_type T;
berghofe@13641
    95
                  val i = length Us;
berghofe@13467
    96
                  val rT = nth_elem (k, rec_result_Ts);
berghofe@13641
    97
                  val r = Free ("r" ^ s, Us ---> rT);
berghofe@13467
    98
                  val (p, f) = mk_prems (vs @ [r]) ds
berghofe@13641
    99
                in (mk_all k ("r" ^ s) (Us ---> rT) (Logic.mk_implies
berghofe@13641
   100
                  (list_all (map (pair "x") Us, HOLogic.mk_Trueprop
berghofe@13641
   101
                    (make_pred k rT U (app_bnds r i)
berghofe@13641
   102
                      (app_bnds (Free (s, T)) i))), p)), f)
berghofe@13467
   103
                end
berghofe@13467
   104
berghofe@13467
   105
        in (j + 1,
berghofe@13467
   106
          apfst (curry list_all_free frees) (mk_prems (map Free frees) recs))
berghofe@13467
   107
        end) (j, constrs)) (1, descr ~~ recTs))));
berghofe@13467
   108
 
berghofe@13467
   109
    fun mk_proj j [] t = t
berghofe@13467
   110
      | mk_proj j (i :: is) t = if null is then t else
berghofe@13467
   111
          if j = i then HOLogic.mk_fst t
berghofe@13467
   112
          else mk_proj j is (HOLogic.mk_snd t);
berghofe@13467
   113
berghofe@13467
   114
    val tnames = DatatypeProp.make_tnames recTs;
berghofe@13467
   115
    val fTs = map fastype_of rec_fns;
berghofe@13467
   116
    val ps = map (fn ((((i, _), T), U), s) => Abs ("x", T, make_pred i U T
berghofe@13467
   117
      (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Bound 0) (Bound 0)))
berghofe@13467
   118
        (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names);
berghofe@13467
   119
    val r = if null is then Extraction.nullt else
berghofe@13467
   120
      foldr1 HOLogic.mk_prod (mapfilter (fn (((((i, _), T), U), s), tname) =>
berghofe@13467
   121
        if i mem is then Some
berghofe@13467
   122
          (list_comb (Const (s, fTs ---> T --> U), rec_fns) $ Free (tname, T))
berghofe@13467
   123
        else None) (descr ~~ recTs ~~ rec_result_Ts ~~ rec_names ~~ tnames));
berghofe@13467
   124
    val concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
berghofe@13467
   125
      (map (fn ((((i, _), T), U), tname) =>
berghofe@13467
   126
        make_pred i U T (mk_proj i is r) (Free (tname, T)))
berghofe@13467
   127
          (descr ~~ recTs ~~ rec_result_Ts ~~ tnames)));
berghofe@13467
   128
    val cert = cterm_of sg;
berghofe@13467
   129
    val inst = map (pairself cert) (map head_of (HOLogic.dest_conj
berghofe@13467
   130
      (HOLogic.dest_Trueprop (concl_of induction))) ~~ ps);
berghofe@13467
   131
berghofe@13467
   132
    val thm = prove_goal' sg (Logic.list_implies (prems, concl))
berghofe@13467
   133
      (fn prems =>
berghofe@13467
   134
         [rewrite_goals_tac (map mk_meta_eq [fst_conv, snd_conv]),
berghofe@13467
   135
          rtac (cterm_instantiate inst induction) 1,
berghofe@13467
   136
          ALLGOALS ObjectLogic.atomize_tac,
berghofe@13467
   137
          rewrite_goals_tac (o_def :: map mk_meta_eq rec_rewrites),
berghofe@13467
   138
          REPEAT ((resolve_tac prems THEN_ALL_NEW (fn i =>
berghofe@13467
   139
            REPEAT (etac allE i) THEN atac i)) 1)]);
berghofe@13467
   140
berghofe@13467
   141
    val {path, ...} = Sign.rep_sg sg;
berghofe@13467
   142
    val ind_name = Thm.name_of_thm induction;
berghofe@13467
   143
    val vs = map (fn i => nth_elem (i, pnames)) is;
berghofe@13467
   144
    val (thy', thm') = thy
berghofe@13467
   145
      |> Theory.absolute_path
berghofe@13467
   146
      |> PureThy.store_thm
berghofe@13467
   147
        ((space_implode "_" (ind_name :: vs @ ["correctness"]), thm), [])
berghofe@13467
   148
      |>> Theory.add_path (NameSpace.pack (if_none path []));
berghofe@13467
   149
berghofe@13467
   150
    val inst = map (fn ((((i, _), s), T), U) => ((s, 0), if i mem is then
berghofe@13467
   151
        Abs ("r", U, Abs ("x", T, mk_realizes U $ Bound 1 $
berghofe@13467
   152
          (Var ((s, 0), T --> HOLogic.boolT) $ Bound 0)))
berghofe@13467
   153
      else Abs ("x", T, mk_realizes Extraction.nullT $ Extraction.nullt $
berghofe@13467
   154
        (Var ((s, 0), T --> HOLogic.boolT) $
berghofe@13467
   155
          Bound 0)))) (descr ~~ pnames ~~ map Type.varifyT recTs ~~
berghofe@13467
   156
            map Type.varifyT rec_result_Ts);
berghofe@13467
   157
berghofe@13467
   158
    val ivs = map Var (Drule.vars_of_terms
berghofe@13467
   159
      [Logic.varify (DatatypeProp.make_ind [descr] sorts)]);
berghofe@13467
   160
berghofe@13467
   161
    val prf = foldr forall_intr_prf (ivs,
berghofe@13467
   162
      prf_subst_vars inst (foldr (fn ((f, p), prf) =>
berghofe@13467
   163
        (case head_of (strip_abs_body f) of
berghofe@13467
   164
           Free (s, T) =>
berghofe@13467
   165
             let val T' = Type.varifyT T
berghofe@13467
   166
             in Abst (s, Some T', Proofterm.prf_abstract_over
berghofe@13467
   167
               (Var ((s, 0), T')) (AbsP ("H", Some p, prf)))
berghofe@13467
   168
             end
berghofe@13467
   169
         | _ => AbsP ("H", Some p, prf)))
berghofe@13467
   170
           (rec_fns ~~ prems_of thm, Proofterm.proof_combP
berghofe@13467
   171
             (prf_of thm', map PBound (length prems - 1 downto 0)))));
berghofe@13467
   172
berghofe@13467
   173
    val r' = if null is then r else Logic.varify (foldr (uncurry lambda)
berghofe@13467
   174
      (map Logic.unvarify ivs @ filter_out is_unit
berghofe@13467
   175
        (map (head_of o strip_abs_body) rec_fns), r));
berghofe@13467
   176
berghofe@13467
   177
  in Extraction.add_realizers_i [(ind_name, (vs, r', prf))] thy' end;
berghofe@13467
   178
berghofe@13467
   179
berghofe@13467
   180
fun make_casedists sorts ({index, descr, case_name, case_rewrites, exhaustion, ...} : datatype_info, thy) =
berghofe@13467
   181
  let
berghofe@13467
   182
    val sg = sign_of thy;
berghofe@13467
   183
    val sorts = map (rpair HOLogic.typeS) (distinct (flat (map
berghofe@13467
   184
      (fn (_, (_, ds, _)) => mapfilter (try dest_DtTFree) ds) descr)));
berghofe@13467
   185
    val cert = cterm_of sg;
berghofe@13467
   186
    val rT = TFree ("'P", HOLogic.typeS);
berghofe@13467
   187
    val rT' = TVar (("'P", 0), HOLogic.typeS);
berghofe@13467
   188
berghofe@13467
   189
    fun make_casedist_prem T (cname, cargs) =
berghofe@13467
   190
      let
berghofe@13467
   191
        val Ts = map (typ_of_dtyp descr sorts) cargs;
berghofe@13467
   192
        val frees = variantlist
berghofe@13467
   193
          (DatatypeProp.make_tnames Ts, ["P", "y"]) ~~ Ts;
berghofe@13467
   194
        val free_ts = map Free frees;
berghofe@13467
   195
        val r = Free ("r" ^ NameSpace.base cname, Ts ---> rT)
berghofe@13467
   196
      in (r, list_all_free (frees, Logic.mk_implies (HOLogic.mk_Trueprop
berghofe@13467
   197
        (HOLogic.mk_eq (Free ("y", T), list_comb (Const (cname, Ts ---> T), free_ts))),
berghofe@13467
   198
          HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
berghofe@13467
   199
            list_comb (r, free_ts)))))
berghofe@13467
   200
      end;
berghofe@13467
   201
berghofe@13467
   202
    val Some (_, _, constrs) = assoc (descr, index);
berghofe@13467
   203
    val T = nth_elem (index, get_rec_types descr sorts);
berghofe@13467
   204
    val (rs, prems) = split_list (map (make_casedist_prem T) constrs);
berghofe@13467
   205
    val r = Const (case_name, map fastype_of rs ---> T --> rT);
berghofe@13467
   206
berghofe@13467
   207
    val y = Var (("y", 0), Type.varifyT T);
berghofe@13467
   208
    val y' = Free ("y", T);
berghofe@13467
   209
berghofe@13467
   210
    val thm = prove_goalw_cterm [] (cert (Logic.list_implies (prems,
berghofe@13467
   211
      HOLogic.mk_Trueprop (Free ("P", rT --> HOLogic.boolT) $
berghofe@13467
   212
        list_comb (r, rs @ [y'])))))
berghofe@13467
   213
      (fn prems =>
berghofe@13467
   214
         [rtac (cterm_instantiate [(cert y, cert y')] exhaustion) 1,
berghofe@13467
   215
          ALLGOALS (EVERY'
berghofe@13467
   216
            [asm_simp_tac (HOL_basic_ss addsimps case_rewrites),
berghofe@13467
   217
             resolve_tac prems, asm_simp_tac HOL_basic_ss])]);
berghofe@13467
   218
berghofe@13467
   219
    val {path, ...} = Sign.rep_sg sg;
berghofe@13467
   220
    val exh_name = Thm.name_of_thm exhaustion;
berghofe@13467
   221
    val (thy', thm') = thy
berghofe@13467
   222
      |> Theory.absolute_path
berghofe@13467
   223
      |> PureThy.store_thm ((exh_name ^ "_P_correctness", thm), [])
berghofe@13467
   224
      |>> Theory.add_path (NameSpace.pack (if_none path []));
berghofe@13467
   225
berghofe@13467
   226
    val P = Var (("P", 0), HOLogic.boolT);
berghofe@13467
   227
    val prf = forall_intr_prf (y, forall_intr_prf (P,
berghofe@13467
   228
      prf_subst_vars [(("P", 0), Abs ("r", rT',
berghofe@13467
   229
        mk_realizes rT' $ Bound 0 $ P))] (foldr (fn ((p, r), prf) =>
berghofe@13467
   230
          forall_intr_prf (Logic.varify r, AbsP ("H", Some (Logic.varify p),
berghofe@13467
   231
            prf))) (prems ~~ rs, Proofterm.proof_combP (prf_of thm',
berghofe@13467
   232
              map PBound (length prems - 1 downto 0))))));
berghofe@13467
   233
    val r' = Logic.varify (Abs ("y", Type.varifyT T,
berghofe@13467
   234
      Abs ("P", HOLogic.boolT, list_abs (map dest_Free rs, list_comb (r,
berghofe@13467
   235
        map Bound ((length rs - 1 downto 0) @ [length rs + 1]))))));
berghofe@13467
   236
berghofe@13467
   237
    val prf' = forall_intr_prf (y, forall_intr_prf (P, prf_subst_vars
berghofe@13467
   238
      [(("P", 0), mk_realizes Extraction.nullT $ Extraction.nullt $ P)]
berghofe@13467
   239
        (prf_of exhaustion)));
berghofe@13467
   240
berghofe@13467
   241
  in Extraction.add_realizers_i
berghofe@13467
   242
    [(exh_name, (["P"], r', prf)),
berghofe@13467
   243
     (exh_name, ([], Extraction.nullt, prf'))] thy'
berghofe@13467
   244
  end;
berghofe@13467
   245
berghofe@13467
   246
berghofe@13467
   247
fun add_dt_realizers sorts infos thy = if !proofs < 2 then thy else
berghofe@13467
   248
  (message "Adding realizers for induction and case analysis ..."; thy
berghofe@13467
   249
   |> curry (foldr (make_ind sorts (hd infos)))
berghofe@13467
   250
     (subsets 0 (length (#descr (hd infos)) - 1))
berghofe@13467
   251
   |> curry (foldr (make_casedists sorts)) infos);
berghofe@13467
   252
berghofe@13467
   253
end;